开发者

Django: Context processors in views, bad practice?

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开发者_Go百科(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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜