python - 用户认证 : prepare vs get_current_user in tornado

标签 python python-3.x tornado coroutine python-asyncio

我需要通过 Tornado 上运行的应用程序中的 cookie 对用户进行身份验证。我需要解析 cookie 并使用 cookie 内容从数据库加载用户。查看 Tornado RequestHandler documentation ,有两种方法:

  • 通过覆盖 RequestHandler 类的 prepare() 方法。
  • 通过覆盖 RequestHandler 类的 get_current_user() 方法。

我对以下陈述感到困惑:

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

我不明白其中的两件事:

  1. 文档中说 get_current_user() 可能不是协程是什么意思? 可能不在这里是什么意思?它可以是协程,也可以不是。

  2. 如果需要异步操作,为什么需要后一种形式,即get_current_user()?如果prepare() 可以一个协程而get_current_user() 可能不,那么不应该 prepare() 用于异步操作?

我真的很感激任何帮助。

最佳答案

  1. 这里的“may not be a coroutine”是指“不允许是协程”或者“一定不能是协程”。使用的语言令人困惑,可能应该改为“不得”。

  2. 同样,文档令人困惑:在这句话中首先提到了 prepare(),但在这句话之前是两个示例,而 get_current_user 是第一个。 “后者”指的是第二个例子,它使用了prepare()

所以总而言之,无论您是否需要协程,覆盖prepare() 并设置self.current_user 总是有效的。如果您不需要协程来获取当前用户,您可以改写 get_current_user(),它将在第一次访问 self.current_user 时自动调用。选择哪一个并不重要。您可以使用您觉得更自然的任何一种。 (我们有两种不同方法的原因是 get_current_user() 较旧,但我们不得不对协程使用不同的方法)

关于python - 用户认证 : prepare vs get_current_user in tornado,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36739681/

相关文章:

python - 创建一个无限循环

python - 为什么来自 librosa 库的频谱图与实际音轨的持续时间不同?

python - 从 Python 中调用 Robot Framework 文件

google-chrome - ipython 笔记本内核运行,但没有连接

python - 为什么聊天应用程序必须是异步的?

python - 从 PIL 中绘制点线或虚线矩形

python - python 'dict'类型的源代码在哪里?

python - PIP fatal error

python - 通过代理连接发送带有 header 的 aiohttp post 请求

python http服务器,多个同时请求