有没有办法在中间件中使用 Flask 会话?(烧瓶1.1.1)
我需要在应用程序请求之前访问会话以获取“user_id”。
from flask import session
class Middleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
1)
print(session['user_id']) # RuntimeError: Working outside of request context.
2)
with self.app.app_context(): # AttributeError: 'function' object has no attribute 'app_context'
print(session['user_id'])
3)
with self.app(environ, start_response).app_context():
# AttributeError: 'ClosingIterator' object has no attribute 'app_context'
Run Code Online (Sandbox Code Playgroud)
提前致谢。
我正在使用Sqlite作为我的项目数据库.我需要在我的模型中使用日期和时间,所以我正在使用这个字段.
date = models.DateTimeField()
Run Code Online (Sandbox Code Playgroud)
在结果模板(results.html)上,时间是正确的(我的settings.py中的localtime或TIME_ZONE)问题是,当我检查Django管理页面和sqlite db文件上的数据库时,似乎我的时区设置不是应用.(所以,也许是UTC)
有什么问题,我怎么能解决这个问题?
我认为模板的参数来自视图,因此timezone.now()是正确的并且传递了正确的时间.所以我的猜测是'date = timezone.now()'传递给sqlite,如下所示:
insert into table values (date=datetime('now'))'
Run Code Online (Sandbox Code Playgroud)
并且sqlite的时区可能设置为UTC默认值.
这就是我猜的.我对吗?另外我不知道如何设置sqlite数据库时区...
ps另一方面,我也认为当我们设置settings.py TIME_ZONE时,django会管理所有这些事情.所以不知道在哪里接近.在这个问题上花了差不多2天......