在Flask中螺纹局部物体是什么意思?

2024-04-25 09:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在看烧瓶的文档我读到了-

One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code and yet they should not limit you. Because of that, Flask has few design choices that some people might find surprising or unorthodox. For example, Flask uses thread-local objects internally so that you don’t have to pass objects around from function to function within a request in order to stay threadsafe. This approach is convenient, but requires a valid request context for dependency injection or when attempting to reuse code which uses a value pegged to the request. The Flask project is honest about thread-locals, does not hide them, and calls out in the code and documentation where they are used.

这是什么意思?特别是以下问题-

  • 什么是线程本地对象?它们是如何和何时使用的?它们的目的是什么?在
  • 如何在内部使用线程本地对象来确保线程安全,以及如何将对象传递给函数会导致线程不安全?在
  • 在这种情况下,有效请求上下文的含义是什么?在

Tags: andoftheto对象inflaskthat
1条回答
网友
1楼 · 发布于 2024-04-25 09:38:47

线程本地对象是一个存储在专用结构中的对象,与当前线程id相关联。如果您向此结构请求对象,它将使用当前线程标识符为您提供当前线程唯一的数据。见^{}。{cd2>你仍然可以通过进入Python解释程序来获得更多的细节。在

这意味着,无论何时使用current_appgrequests时,都会得到一个可以在线程(或进程或eventlet)中安全使用的数据结构,而不必担心锁定和其他并发问题。在

在正常操作中,Flask处理传入的WSGI请求;对于每个这样的请求,都会为您创建一个请求上下文;这由grequest对象表示。如果您试图在没有传入请求的情况下使用任何视图,那么request对象将无法工作并抱怨没有有效的请求上下文。Flask为您提供了在这种情况下根据需要生成这样一个上下文的工具。请参阅Faking Resources and Context documentation,以及Request Context一章。在

相关问题 更多 >