I have an application that uses the requests library to make calls to a web service. On django, I use a table to keep sessions using the standard django_session library.
I've noticed that I have a new record in the database for every time the requests library fires off a call. I find this quite bizarre, since I'm not using request sessions (explicitly) and most of my calls are single GET calls that shouldn't need any kind of persistance.
Has anybody else had this problem?
django.contrib.sessions.middleware.SessionMiddleware will create a new session for each request.
If you want to disable this behavior, consider replacing django.contrib.sessions.middleware.SessionMiddleware with a custom middleware that extends django.contrib.sessions.middleware.SessionMiddleware but prevents sessions from being created in instances where you don't want them.
This answer provides an example of how to do so. It parses request.path_info to determine whether a session should be created, but you could use a number of different techniques, such as adding a custom header to your request, including a post variable, etc.
Turns out I had this setting turned on
SESSION_SAVE_EVERY_REQUEST=True
When I started with sessions I wanted to be safe to make sure nothing falls through the cracks. Turns out this was then writing empty session information to the db.
Related
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.
According to Django's documentation I can set ATOMIC_REQUESTS to make all requests atomic. It also states that I'm able to selectively turn it off on a "per-View" basis, not "per-View-function".
But it isn't clear if the GET method would also be transactional. I understand that the REST definition considers this method as safe and idempotent, thus it shouldn't ever be transactional. Specially when you think about several GET requests unnecessarily overloading the database.
Finally, we're using a ListCreateView then we cannot make the entire view non-transactional and also we cannot create a separated view just for listing because that would hurt our URLs pattern.
Unfortunately it's not possible.
I'm working on a project with Flask and Flask-Restful, trying to get dynamic urls according to input from the user in my Restful API. I created a class with a get method that will be responding to requests, and when the user calls upon another resource, it activates the new one and a url should be created.
The problem comes when I try to add a new resource to my api, which calls the function setupmethod in Flask that checks if the app is in debug and if the first request was already made.
if self.debug and self._got_first_request:
raise AssertionError('A setup function was called after the '
'first request was handled. This usually indicates a bug '
'in the application where a module was not imported '
'and decorators or other functionality was called too late.\n'
'To fix this make sure to import all your view modules, '
'database models and everything related at a central place '
'before the application starts serving requests.')
One simple way to overcome this would be to modify the add_view function in Flask to avoid this behaviour. I first want to understand why would you avoid a setup method like creating a view or in my case a resource after the first request is called?
It is to avoid designs such as the one you just described. Define all your routes before hand. Then use the session or database to store whether a user has gone to one enpoint and is allowed to go to the next.
If you need routes with different parameters, then add a route with a path argument that can dispatch based on value, rather than dynamically adding new routes during runtime.
Another point, you should never modify the code of libraries you installed. If you ever upgrade the library, your changes will get overwritten. In Flask's case, you can subclass the Flask object and override this method instead.
I'm developing a backend in Django and I need to log in to another server backend with a simple POST method. So I would need to create a session object or something like that to handle that login.
Any Ideas on how to do that?
What you are really looking for is a Single Sign On (SSO). You might consider django-openid.
If you're not looking for single sign-on, then likely you want to either do the work in the view, and if you need the session to persist, store it in the (local django) session object; or outsource it to something like celery, and again, keep anything you need to keep track of in the session object.
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.