我正在研究django1.10的宠物项目,尝试使用频道。我有一个中间件,我想导入并挂钩到myapp.I想要' ip',' user_agent' ' session_key可以'从中间件挂钩到我的channel / sessions.py的参数。由于我还在掌握python和django,我非常感谢有关如何将我的中间件类SessionMiddleware挂钩到我的channels / 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
)
channels / 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类/函数import.I能够导入模块和类SessionMiddleware;我试图定义' ip',' user_agent&#39 ;和' session_key'作为channels / sessions.py中的全局变量(可能因为我收到错误而遗漏了一些东西):
NameError:name' user_agent'没有定义。
`当我尝试在#Make中的if语句中分配' session'在channels / sessions.py中的会话存储:
session = session_engine.SessionStore(session_key = session_key,user_agent = user_agent,ip = ip)
我很难理解以下内容: 1.什么是pythonic方式来呼叫' ip',' user_agent'和' session_key'我的channels / sessions.py的参数。 2.如何使这些参数在channels / sessions.py中具有全局范围。