using a colon in a string in python - python

i am using python 2.6.5 to develop an app for google app engine - i am not too familiar with python, but i'm learning.
i am trying to put a url into a string so variable = "string http://domain.name"
then i print the string out. the problem is, if the colon (after http) is in the string, i don't get any output and i don't know why.
i've tried escaping the string with:
"""http://domain.name"""
r"http://domain.name"
"http\://domain.name"
"http\://domain.name"
"http\\://domain.name"
"http:://domain.name"
none of them seem to work and i'm not sure what else to try
The context is like so
variables.py is:
...
HOST_URL = "http://domain.name"
...
example logout.py
import variables
import sys
...
class Logout(webapp.RequestHandler):
""" RequestHandler for when a user wishes to logout from the system."""
def post(self):
self.get()
def get(self):
print(variables.HOST_URL)
print('hi')
self.redirect(variables.HOST_URL)
sys.exit()
or
in file functions.py
import variables
import sys
...
def sendhome(requesthandler)
print 'go to '+variables.HOST_URL
requesthandler.redirect(variables.HOST_URL)
sys.exit()
called from a context like:
from functions import sendhome
...
class Logout(webapp.RequestHandler):
""" RequestHandler for when a user wishes to logout from the system."""
def post(self):
self.get()
def get(self):
sendhome(self)
any help would be appreciated
thanks

If I'm not terrible mistaken, GAE uses WSGI, you do not simply print things, you are supposed to return a proper HTTP response object (it is not PHP).
I guess that if you access the page using firefox+firebug and look at the network->header you will see that the browser is taking http: as an HTTP header with value "//domain.name".
Edited: By the way, should not you be using "self.response.out.write" instead of "print"?

The problem was the sys.exit() after the call to print or redirect

Related

Global GET Management in Flask

Is there any way of a 'global GET management' in Flask?
For example:
I want to show an error message, via popover, on any page of my flask application. If the user clicks on the 'close' button, the application will make a reload of the page with a new get parameter 'message_read=1'.
I want to catch this GET parameter. I am quite sure there is a better way then writing a check in every single app.route (which are a lot). Could you give me a hint please.
Thank you.
Add a before request function and handle it there. http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request
#app.before_request
def do_stuff():
arg = request.args.get('message_read')
You may use decrators . Read about python decorators here
Here is a demonstration of custom decorator with flask.The code below shows a decorator definition and usage for your use case
Code
from flask import Flask,request
from functools import wraps
def popup_message(f):
#wraps(f)
def f_(*args,**argv):
message_read = request.args.get('message_read', None)
if message_read is not None:
return message_read
else:
return f(*args,**argv)
return f_
app = Flask(__name__)
#app.route('/earth')
#popup_message
def hello_earth():
return 'Hello,earth'
#app.route('/world')
#popup_message
def hello_world():
return 'Hello, World!'
app.run()
Usage
Run the app as
python main.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
and try making request to /earth and /world with and without message_read

How to use correctly importlib in a flask controller?

I am trying to load a module according to some settings. I have found a working solution but I need a confirmation from an advanced python developer that this solution is the best performance wise as the API endpoint which will use it will be under heavy load.
The idea is to change the working of an endpoint based on parameters from the user and other systems configuration. I am loading the correct handler class based on these settings. The goal is to be able to easily create new handlers without having to modify the code calling the handlers.
This is a working example :
./run.py :
from flask import Flask, abort
import importlib
import handlers
app = Flask(__name__)
#app.route('/')
def api_endpoint():
try:
endpoint = "simple" # Custom logic to choose the right handler
handlerClass = getattr(importlib.import_module('.'+str(endpoint), 'handlers'), 'Handler')
handler = handlerClass()
except Exception as e:
print(e)
abort(404)
print(handlerClass, handler, handler.value, handler.name())
# Handler processing. Not yet implemented
return "Hello World"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
One "simple" handler example. A handler is a module which needs to define an Handler class :
./handlers/simple.py :
import os
class Handler:
def __init__(self):
self.value = os.urandom(5)
def name(self):
return "simple"
If I understand correctly, the import is done on each query to the endpoint. It means IO in the filesystem with lookup for the modules, ...
Is it the correct/"pythonic" way to implement this strategy ?
Question moved to codereview. Thanks all for your help : https://codereview.stackexchange.com/questions/96533/extension-pattern-in-a-flask-controller-using-importlib
I am closing this thread.

Python Webapp2 call Handler function from within separate Handler

Python 2.7, webapp2, Jinja2
I am trying to call a Handler function from within another Handler with the end goal of rendering a Landing page with a passed argument. Previously, I used self.redirect(/landing) but now need to pass arguments.
Simplified example:
class Landing(Handler):
def render_index(self, error = ""):
self.render("index.html", error=error)
def get(self):
self.render index()
class Login(Handler):
def post(self):
try:
verify_user()
except:
# self.redirect('/landing')
error = "error message"
-> # would like to render Landing page and pass error argument
I am not sure how to do this - any advice is appreciated.
Is Landing.get(Landing(request=self.request)) what you are looking for?

Python AppEngine, how to take parameters to another page

In my app, each page is each Python class. From page A, I want to take some data in this page and redirect to page B.
Does Google App Engine has some ways to do it ? (I don't want to use something like: global variable or cookie for this small work)
Thanks :)
You can compute the value you need in the first handler (AHandler), then redirect to the second handler (BHandler) passing that value as a GET parameter. Finally BHandler, reads that parameter and does something with it. Here is some code:
import urllib
class AHandler(webapp2.RequestHandler):
def get(self):
name = 'Some name'
redirect('b?%s' % urllib.urlencode({'name': name}))
class BHandler(webapp2.RequestHandler):
def get(self):
name = self.request.get('name')
# do something with name

get_current_session returns None

I've been using geasessions for a while, been working great. It's simple and fast.
But today I started a new project (GAE v1.3.7) and can't get it to work, get_current_session() just returns None
I've split the code in to a new project that's just using gaesessions:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from gaesessions import get_current_session
import logging
class MainHandler(webapp.RequestHandler):
def get(self):
session = get_current_session()
logging.info(session)
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, { }))
And in the log it just says None.
The strange part is that the other solutions it still works. (I'm guessing it's due to that the db.Model for Session is already present). Tested both the version I use there and downloaded the latest version (1.04)
I've looked at the source code for gaesessions and it kinda make sense that it returns None:
_current_session = None
def get_current_session():
"""Returns the session associated with the current request."""
return _current_session
And I can't find anywhere where the Session class is invoked, but then again it could be my laking python skills.
Does anyone use gaesession and know what's happening?
I think you have missed something in the installation process.
Anyway, if you scroll down the source code you will notice also this part of code that actually valorize the _current_session variable.
def __call__(self, environ, start_response):
# initialize a session for the current user
global _current_session
_current_session = Session(lifetime=self.lifetime, no_datastore=self.no_datastore, cookie_only_threshold=self.cookie_only_thresh, cookie_key=self.cookie_key)

Categories