Django:我如何获得用户不在查看请求之外? [英] Django: How can i get the logged user outside of view request?

查看:176
本文介绍了Django:我如何获得用户不在查看请求之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要记录的用户信息的类方法(视图外)。如何在不将请求传递给该方法的情况下,如何检索登录的用户?不幸的是,我找不到一个很好的解决方案,它不合逻辑只是不存在这样做的方式,因为Django应该存储在登录用户的某个地方。否则(我相信)不可能使用 django.contrib.auth.decorators 中的 @login_required 装饰器。对吗?

I have a class method (outside of a view) who needs the logged user's information. How can i retrieve the logged in user without passing the request to the method? Unfortunately i can't find nowhere a nice solution and it's not logical just not exist such a way to do it, because Django should store somewhere the logged in user. Otherwise (i believe) it would be impossible to use @login_required decorator from django.contrib.auth.decorators. Right?

所以如果不可能为什么不这样做?为什么Django这样工作,如果我想要的唯一想法是登录用户,而不是请求中的所有信息

So if it's not possible why it's not? Why Django works like this if the only think i want is the logged in user and not all the informations inside request?

提前感谢

推荐答案

关于装饰器,这是错误的。实际上装饰器用请求参数调用。

About decorators, it is wrong. Actually decorators called with request argument.

我相信更好的办法是将用户或请求对象传递给类的方法。但是还有其他访问请求的方法。

I believe better way is that passing user or request object to class's method. But there are other ways to access request.

这是我们使用的代码。您需要将这个中间件添加到MIDDLEWARES中。进口&调用get_request函数。

Here is the code that we use. You need to add this middleware to MIDDLEWARES. And import & calling get_request function.

from threading import current_thread

from .exceptions import RequestNotFound

_requests = {}


def get_request():
    t = current_thread()
    if t not in _requests:
         raise RequestNotFound('global request error')
    return _requests[t]


class RequestMiddleware(object):
    def process_request(self, request):
        _requests[current_thread()] = request

这篇关于Django:我如何获得用户不在查看请求之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆