我需要存储来自一些非 Django 应用程序的特殊 cookie。我可以在 View 中做到这一点
request.session[special_cookies'] = special_cookies
但是在非 View py 文件中,我需要访问这个特殊的 cookie。
根据docs , 我可以做这个
>>> from django.contrib.sessions.backends.db import SessionStore
>>> import datetime
>>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
>>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
>>> s['last_login']
datetime.datetime(2005, 8, 20, 13, 35, 0)
>>> s.save()
如果我不提供 session key ,Django 将为我生成一个。
我担心获得许多新 session key 的影响。 (当你有多个用户时,我不认为这很好,对吧......?)
我希望用户将此特殊 cookie 绑定(bind)到用户的 session 。 然而 ,出于安全原因,我不想将其保存在用户配置文件中。这个 cookie 在我们登录时生成(我们的应用程序将发送这个特殊的 cookie)。我们希望在整个浏览 session 期间来回发送此 cookie。
我应该如何解决这个问题?
非常感谢你!
#views.py
request.session['special_cookies'] = library.get_special(user, pwd)
#library.py
def get_special_cookies(user, pwd):
res = get_special_cookies("http://foobar.com/api/get_special_cookies", user, pwd)
#foobar.py (also non-views)
def do_this(user, special_cookies)
我很确定这很好......
#views_2.py
def dummy_views(request):
foobar.do_this(request.user, request.session['special_cookies'])
但是在某些情况下,我不想通过 View /调用 get_sepcial_cookies 来获取我的特殊 cookie。我希望它一直持续下去。还是我想多了..?
最佳答案
为了解释为什么你处于危险的道路上,我们必须记住为什么首先发明了服务器端 session :
HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests. For example, when a web server is required to customize the content of a web page for a user, the web application may have to track the user's progress from page to page. A common solution is the use of HTTP cookies. Other methods include server side sessions, hidden variables (when the current page contains a form), and URL-rewriting using URI-encoded parameters.
Django是一个非常成熟的框架;如果某些目标在 Django 中似乎难以实现,那么您可能采用了错误的方法来解决问题。即使您可以将服务器端 session 信息直接存储在 session 后端,这对我来说似乎也是糟糕的设计,因为 session 数据与外部请求无关。
恕我直言,如果您需要在应用程序之间共享身份验证/授权数据,您真的应该考虑类似 OAuth ,否则你最终会得到一些不安全、脆弱、丑陋和难以支撑的东西。
(对不起,如果我听起来居高临下,英语不是我的母语)。
[更新]
Hi Paulo. Thank you very much. I believe my team doesn't want to introduce OAuth or any sort of extra layer of authetication mechaicism. But are you against inserting this special cookies into HttpResponse.COOKIES?
如果您真的想这样做,请注意几点:
Is that a better solution than request.session?
有一些机制可以在更高的层次上处理这类问题。例如:
如果没有关于您的目标的更多详细信息,我无法提供更具体的解决方案,但是使用这些 Hook 可以避免重复代码来测试每个 View 中的外部 cookie - 但是请注意,有关 cookie 的所有内容都与请求/响应上下文和在它之外没有任何意义。
关于django - 在 Django 中的 View 之外访问 session /请求信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9220484/