Pass errors in Django using HttpResponseRedirect - python

I know that HttpResponseRedirect only takes one parameter, a URL. But there are cases when I want to redirect with an error message to display.
I was reading this post: How to pass information using an HTTP redirect (in Django) and there were a lot of good suggestions. I don't really want to use a library that I don't know how works. I don't want to rely on messages which, according to the Django docs, is going to be removed. I thought about using sessions. I also like the idea of passing it in a URL, something like:
return HttpResponseRedirect('/someurl/?error=1')
and then having some map from error code to message. Is it good practice to have a global map-like structure which hard codes in these error messages or is there a better way?
Or should I just use a session
EDIT: I got it working using a session. Is that a good practice to put things like this in the session?

You are right about the auth messages. They are deprecated but as the docs suggest you should use the django messages framework instead, which I think is the exact soultion for your case.

Related

Middleware in flask

I just stated using Flask and was trying to implement a small feature in my project. The objective is to set a cookie only if the request comes from a authenticated user.
I found two ways of doing this.
First method
#app.before_request
def before_request():
# set cookie if user is logged in
Second method, by implementing something like this
adding-a-simple-middleware-to-your-flask-application
Can someone explain to me what are the main differences between the two methods and when and where which method should be used.
Also, I am currently using "flask-login" to keep track of the logged in user.
If I use the first method, I can easily verify if someone is logged in by importing the current_user
from flask.ext.login import current_user
but if I try to do the same while using the second method, the current_user is always "None" as the application context is incorrect.
So, I wanted to know if I decided to go ahead with the second implementation, how do I check if the user is logged in or not.
I've never used the second method you've mentioned. I'm sure that it can be done with it, but it's very uncommon. I would suggest to use more common features of flask. For sake of maintainers of your code :)
So the first method you've mentioned is fine.
Or you can use decorators for more granular access restrictions. Keep in mind that setting cookies in flask can be done when making actual response object. That means you should use Deferred Request Callbacks for setting cookies in decorated function.

Checking login status at every page load in CherryPy

I am in the midst of writing a web app in CherryPy. I have set it up so that it uses OpenID auth, and can successfully get user's ID/email address.
I would like to have it set so that whenever a page loads, it checks to see if the user is logged in, and if so displays some information about their login.
As I see it, the basic workflow should be like this:
Is there a userid stored in the current session? If so, we're golden.
If not, does the user have cookies with a userid and login token? If so, process them, invalidate the current token and assign a new one, and add the user information to the session. Once again, we're good.
If neither condition holds, display a "Login" link directing to my OpenID form.
Obviously, I could just include code (or a decorator) in every public page that would handle this. But that seems very... irritating.
I could also set up a default index method in each class, which would do this and then use a (page-by-page) helper method to display the rest of the content. But this seems like a nightmare when it comes to the occasional exposed method other than index.
So, my hope is this: is there a way in CherryPy to set some code to be run whenever a request is received? If so, I could use this to have it set up so that the current session always includes all the information I need.
Alternatively, is it safe to create a wrapper around the cherrypy.expose decorator, so that every exposed page also runs this code?
Or, failing either of those: I'm also open to suggestions of a different workflow. I haven't written this kind of system before, and am always open to advice.
Edit: I have included an answer below on how to accomplish what I want. However, if anybody has any workflow change suggestions, I would love the advice! Thanks all.
Nevermind, folks. Turns out that this isn't so bad to do; it is simply a matter of doing the following:
Write a function that does what I want.
Make the function in to a custom CherryPy Tool, set to the before_handler hook.
Enable that tool globally in my config.

Blank responses from Django runserver when checking user permissions

I have a similar problem to those listed in
Django produces blank pages when POST data is sent and Models are accessed
and
Nginx connection reset, response from uWsgi lost
Here is one of the views in question:
#transaction.commit_on_success
#occ_update
#checks_status
def hold(request):
if not request.user.has_perm('orders.hold'):
return error_response_rollback(NO_PERMISSION_MSG % "hold orders")
order = Order.objects.get(pk=request.POST.get('pk'))
occ_revision = int(request.POST.get('occ_revision'))
agent = Agent.get_agent(request.user)
action = Action(agent=agent, type='hold_order',
comments=request.POST.get('comments'))
action.save()
order.hold(action, occ_revision)
return ok_response_commit("Order held successfully.")
error_response_rollback rolls back the transaction and returns an HttpResponse with JSON as its contents.
I am adding permission checking to many of my views in my application and when the user does not have the correct permission, a blank response is returned.
However like the questions referenced above, if you put a
print request
or
request.POST
statement BEFORE the permission check, the NO_PERMISSION_MSG JSON string is returned to the browser correctly every time (error_response_rollback returns an HttpResponse object with JSON in it.)
You get blank responses when you check permissions before the "print request" and they do not have the correct permissions.
You do NOT get blank responses when:
the user has the correct permissions
a "print request" statement is before any permission check
you use Firefox at any point.
The #occ_update and #checks_status decorators just catch exceptions. These problems occur with and without them present.
I'm developing in Chrome and none of this is an issue in Firefox.
One page I found suggested overloading the WSGIRequest object to read the request before it is passed to the view but this seems icky to me and I'd rather find out the real solution.
Does anyone know of any fixes/settings to the runserver command to help this issue without hacking on the request? My users are primarily using Chrome so I'd prefer to keep using it... we'll see. Currently developing in Windows using Django 1.3.1
One option I have considered is making another manage.py command to handle this but that, too, seems icky.
Thanks
Update:
I have been able to re-organize my code so that any permission checks happen after some bit of data is read from the POST. This seems to have eliminated any symptoms of this problem. It's still not ideal but it is a good alternative to inserting middleware to read the post. and won't always be possible in all applications.
Please comment if you have a similar situation and just can't figure it out.
As saying in the second link in your post, especially http://forum.nginx.org/read.php?2,196581 : when you works w/ Nginx and uWSGI and get a non-empty POST, always read the request.POST before return an HttpResponse. The reason is described in the link.
You don't have to override an handler, just put the request.POST line before the return code, or inside some decorator or middleware.
I encountered this issue for production site half a year ago and put the line in a middleware to solve it.

How to see current context when debugging template errors?

I am getting a template error during rendering, which I think would be easy to fix if I could just see what's in the context that is passed into the template that is being rendered. Django's debug error page provides a lot of information, but I'm not seeing my context anywhere. Am I missing something? Also, I am using Django-debug-toolbar, but that only seems to come up if the page successfully renders. Not being able to see the contents of the context that is passed to the template makes debugging some types of template errors hard! What do I need to do to be able to see it in this scenario? (Note that I'm not asking for a fix to my specific error, which is why I'm not providing more information about it).
From the comments:
I think you need to walk up the stacktrace (in the django debug page) to actually see your context variables. I don't understand your problem exactly. If I have a template error I can inspect my context somewhere in the traceback.
Yes, setting a "breakpoint" in django can sometimes mean just inserting a non-defined variable at the point you want to inspect. The last entry in the traceback is usually the one for this variable. It will give you all context details in the traceback of the debug page.
The easiest way to do this is with the Django Debug Toolbar. it will give you a popup tab on the right hand side of your screen that you can use to inspect various things about the current page's request. Things like SQL statements, versions, logging, and all the templates that were used to render the page, and the context available to each of them.

How to manage authentication across handler classes in google app engine /w python

Taking into account that I barely know python and am simply following the "hello-world" example here: http://code.google.com/appengine/docs/python/gettingstarted/
I'm unclear as to how I would: use a "MainHandler" class mapped to '/' as a welcome page, ask the user to login and then only allow logged-in users to access a "EditorHandler" class mapped to '/editor'
You've asked a very broad question, and provided no details about what (if any) framework you're planning to use to implement your app. I guess you are probably using webapp?
The basic idea would be to create a login url that you redirect the user to, or you provide to them. If you want them redirected to an edit page on your app, you can specify a dest_url when calling create_login_url:
users.create_login_url(dest_url='/edit')
Within your code you can secure your edit handler easily in app.yaml or with the '#login_required' decorator, depending on how you've setup your app.
This seems to work: http://appengine-cookbook.appspot.com/recipe/login-decorator
Although I dont understand the magic behind most of it, it's probably due to my lack of python skills.
Some comments on that article also point to more "native" solutions:
http://code.google.com/appengine/docs/python/tools/webapp/utilmodule.html

Categories