首页 > 解决方案 > 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.

如何在网站的初始加载时保护这些标头并将它们保存到对象中而不会出现这些错误?

标签: pythonflask

解决方案


你可以这样理解,也许:

在第一次调用 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

推荐阅读