I see that the request parameters can be obtained in a viewset function using request variable.
eg:
#detail_route(methods=['get'])
def mysampleviewsetfunction(self, request):
print request
But, I want to be able to access request from some common variable. The purpose of that is to write a common function that can be called from all viewsets. This common function should be able to access request parameters depending upon the viewset that called it. But for some reason, I don't want to send the request parameter to this common function.
My code should look like this:
#detail_route(methods=['get'])
def mysampleviewsetfunction(self, request):
commonfunction()
def commonfunction():
print xxxx.request
This 'xxxx' should be some global django variable that stores the current viewset's request. Is there any global variable that stores current viewset's request?
it'd save me the trouble of modifying all the functions.
You wouldn't have to if you provide a default.
def commonfunction(request=None):
This of course means that any existing function calls won't be able to use the request until you update them so you'll need a check to make sure the request isn't none in this function.
There isn't any way you could use a global variable since that won't work asyncronously
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.
I need to get the value from querystring which is passing through ajax source. I have class named as xxxx. While loading the class i want to get the value from that querystring. I can able to get the value inside the method using request.GET.get('xxxx') syntax. But i want to get the value while loading the class.
sAjaxSource: "/api/helpdesk/?format=json&xxxx=10",
I have mentioned the ajax url above.
My api.py file:
class helpdesk(ModelResource):
class Meta:
""" Here i would like to get the xxxx value"""
Inside the method i can easily get it using request.GET.get("xxxx").Plz anyone help me to do this.Thanks in advance.
I don't think that's possible.
django-tastypie and similar packages for creating REST APIs leverage the functionality Class-Based Views (CBV) allow, which means that each of those URLs have been assigned the instance method they will use as its view when a request is made to such URL which, in turn, means that the class has been initialized before the request object is passed to any methods of the class.
At that point, the class does not know anything about your requests.
I'm using django rest framework and trying to save some data so it will be accessible by GET, PUT, DELETE.
So when user send GET request server send some information (a random number, for example) and that information is needed after user sends PUT request on the same url. How would one save such information? I'm using class-based views.
So i want to save that information on GET method.
I tried saving that information to class variable self.information, but the problem is self.information is empty when PUT method is getting called.
I also tried saving it to session, but like class variable, session is also empty when PUT method is being executed.
class SampleClass(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView):
serializer_class = SampleSerializer
def get(self, request):
random_number = random.randint(0, 10)
request.session['number'] = random_number;
content = {'random_number': random_number}
return Response(content)
def put(self, request):
number = request.session['number'] # key doesn't exists
process_number(number)
# ...
Before I begin, it's important to note that HTTP is a stateless protocol, and you are looking to add state into the mix. If you can rework what you are doing to not depend on previous requests, that will probably be better in the long run.
I tried saving that information to class variable self.information, but the problem is self.information is empty when PUT method is getting called.
This is because the class is re-initialized for each request. Because of that, the class variables don't persist across requests. Even if they did, that would mean everyone would get access to the persisted value, and it isn't made clear if that is what you are looking for.
I also tried saving it to session, but like class variable, session is also empty when PUT method is being executed
This doesn't work because Django sessions are persisted through the use of cookies. While this might work for SessionAuthentication, it won't work for any authentication that happens outside of the browser. This is because the session cookies won't be included, so Django will think the new requests are under a different session.
Now, just because HTTP is mostly stateless and doing this might lead to future trouble, that doesn't mean that you should never do it. The Django sessions wouldn't exist if there wasn't a need for it, and there are ways to save state without Django sessions.
Create a new model for the state - This is usually the best way to save state per-user and ensure that it doesn't fade away. The model needs a user field along with the fields that the state will be stored in, and all you need to do is have a query that retrieves the state object for the user.
Use the Django cache - This is the way I would recommend it for the case that you specified in your question. When you don't need to store much state, the state is shared among everyone, or you can live with it not existing (expiring), storing the data in a simple cache environment will probably work the best. You have much more control over what is stored, but at the expense of having to do more work.
Another question like this one was asked, but I don't 'like' the answer (in reality it didn't really answer the question in the first place): Can any one explain how can i pass arg or kwargs from redirect to another view?)
I have a view and need to redirect to another view (in another application) and still send an argument along. Currently I have:
return redirect('/projects/', login_error=error)
Which doesn't work (the redirect happens but the argument doesn't go through). Is it even possible to do this using redirect()? The documentation doesn't have anything on it.
However, I also tried referring to the view without using a URL:
return redirect('projects.views.list_all', login_error=error)
But that doesn't work either.
redirect returns an HTTP redirect to the supplied URL - that is, the browser receives a
30x response and initiates a new request.
To preserve state between the two requests, you either need to set a session variable (as per the other answer) or provide a query parameter, eg:
return redirect('/projects/?login_error=error')
You will then need to process the incoming request.GET parameter in the other view.
In my Django project, I have a context processor which returns a FacebookUser object based on the cookies present in the request (using Facebook's Python SDK). This means that when the user is logged in, their corresponding FacebookUser object is always available in my templates.
However, what should I do when I want to access this in views too?
Option 1: In each view where I want to access this FacebookUser object, call the context processor method, or a method that does exactly the same thing.
Option 2: Again, in each view, call RequestContext(request) in order to get access to the existing object added to the context by the context processor.
Which is better practice, and are there any recommended ways of working here?
If you need your FacebookUser object a lot then use middleware. Documentation is here
For a sample middleware class:
class FacebookApiIntegrator(object):
def process_request(self, request):
if request.user.is_authenticated():# check if user has logged in
request.facebook = <your profile func or obj..>
and in any view you can just use:
request.facebook
But do not forget, that your middeleware will run for every request and add your facebook profile object to request for every request of a logged in user. So using middleware for an object that do not used often is not a good idea.
Option 1. Delegate the context processor's work to another function, and call that function.
You're already using middleware.
https://docs.djangoproject.com/en/1.3/topics/http/middleware/#middleware
You just need to implement process_request and it's done in every request.
https://docs.djangoproject.com/en/1.3/topics/http/middleware/#process_request