1

我正在 django1.10 上进行一个宠物项目,尝试使用频道。我有一个中间件,我想将它导入并挂接到 myapp。我希望中间件中的 'ip'、'user_agent'、'session_key' 参数挂接到我的频道/sessions.py。由于我仍在掌握 python 和 django,我感谢任何有关如何将我的中间件类 SessionMiddleware 连接到我的通道/sessions.py 的帮助。

中间件的相关代码是:

class SessionMiddleware(MiddlewareMixin):
    """
    Middleware that provides ip and user_agent to the session store.
    """
    def process_request(self, request):
        engine = import_module(settings.SESSION_ENGINE)
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = engine.SessionStore(
            ip=request.META.get('REMOTE_ADDR', ''),
            user_agent=request.META.get('HTTP_USER_AGENT', ''),
            session_key=session_key
        )

通道/sessions.py 是:

def inner(message, *args, **kwargs):
        # Make sure there's NOT a http_session already
        if hasattr(message, "http_session"):
            return func(message, *args, **kwargs)
        try:
            # We want to parse the WebSocket (or similar HTTP-lite) message
            # to get cookies and GET, but we need to add in a few things that
            # might not have been there.
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)
        except Exception as e:
            raise ValueError("Cannot parse HTTP message - are you sure this is a HTTP consumer? %s" % e)
        # Make sure there's a session key
        session_key = request.GET.get("session_key", None)

        if session_key is None:
            session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        # Make a session storage

        if session_key:
            session_engine = import_module(settings.SESSION_ENGINE)
            session = session_engine.SessionStore(session_key=session_key,user_agent=user_agent,ip=ip)
        else:
            session = None
        message.http_session = session
        # Run the consumer
        result = func(message, *args, **kwargs)
        # Persist session if needed (won't be saved if error happens)
        if session is not None and session.modified:
            session.save()
        return result
    return inner

这个问题可能很简单,需要了解基本的 python 类/函数导入。我能够导入模块和类 SessionMiddleware;我尝试将“ip”、“user_agent”和“session_key”定义为通道中的全局变量/ session.py(可能因为我收到错误而遗漏了一些东西):

NameError:name 'user_agent' 未定义。

` 当我尝试在#Make a session storage in channels/sessions.py 中的 if 语句中分配“会话”时:

会话 =session_engine.SessionStore(session_key=session_key,user_agent=user_agent,ip=ip)

我很难理解以下内容: 1. 将“ip”、“user_agent”和“session_key”参数调用到我的频道/sessions.py 的 Pythonic 方式是什么。2. 如何使这些参数在channels/sessions.py 中具有全局范围。

4

0 回答 0