python - Flask:如何呈现模板并保存 request.headers 信息?
问题描述
我正在尝试保存request.headers
我的 Flask 应用程序中可用的对象。
我想index.html
在页面加载时呈现我的内容,但我也想获取访问用户的电子邮件,以便将其用于其他功能/流程。
# routes
@app.route('/')
def index():
return render_template('index.html')
def find_aad():
aad_email = request.headers.get('X-MS-CLIENT-PRINCIPAL-NAME') # aad email
return aad_email
如果我试着自己跑find_aad()
,
user_email = find_aad() # cant run
我会得到典型的错误:Working outside of request context.
如何在网站的初始加载时保护这些标头并将它们保存到对象中而不会出现这些错误?
解决方案
你可以这样理解,也许:
在第一次调用 index 时,您可以为“会话”创建一个 UUID 并将其用作用户的标识符,然后将该代码传递回呈现的 UI 元素中以存储在客户端。然后,在每次对后端的后续调用中,您都会将该 UUID 与请求的其余部分一起发送。
在这些后续请求中,您可以通过该 UUID 访问电子邮件值作为您用于在后端存储客户端信息的数据结构的键。
这个概念是具有“会话 id”的“会话”的概念,这在客户端/服务器通信中很常见。为 Flask 使用套接字甚至可能是内置或补充库可能是一个好主意,而不是“自己动手”。对不起,如果我没有帮助或愚蠢 - 我已经很晚了。
编辑:
根据要求,这里有一些简单的伪代码:
from flask import Flask
import uuid
...
uuid_to_email = {}
...
@app.route('/')
def index():
user_id = str(uuid.uuid4())
uuid_to_email[user_id] = request.headers.get('X-MS-CLIENT-PRINCIPAL-NAME')
return render_template('index.html', uuid=user_id) # where it is implied that you would then use the uuid in the client-side code to story it and pass it back to the endpoints you want to do that with
推荐阅读
- vue.js - 无法从父组件验证子组件
- python - Python 中的 __build_class__ >= 3.5
- php - PDO 在数组中插入数组
- xamarin.forms - 如何在我的 xamarin 表单应用程序中使用 lottie 动画?
- python - 如何避免 2 个相等的循环 | 姜戈
- unity3d - unity 3d 我如何以直线方法计算末端和每个玩家之间的距离,然后按距离对它们进行排序,
- ios - 获取未压缩的 CIImage 数据
- python-docx - 使用 python-docx 是否可以设置用于文档的主题
- c# - 如何将列表和字符串传递给具有通用列表参数的通用方法
- mysql - Laravel 页面在 localhost 工作时在主机上过期 419