0

我正在使用烧瓶来处理包含指向文档的 URL 的请求。当请求到达时,URL 指向的文档被保存到一个文件中。文件被打开、处理并根据文档中的数据生成一个 json 字符串。json 字符串在响应中发送。

我的问题是关于它们之间的时间很短的请求。当 User1 在他的请求中发送 url_1 时,会保存 url_1 处的文档。User2 在打开来自 User1 的文档之前使用 url_2 发送请求。发送给 User1 的生成的 json 字符串是否基于 url_2 处的文档?这很有可能发生吗?

下图说明了该场景:

事务隔离

这是烧瓶应用程序的外观:

app = Flask(__name__)

@app.route("/process_document", methods=['GET'])
def process_document():
    download_location = "document.txt"
    urllib.request.urlretrieve(request.args.get('document_location'),download_location)
    json = some_module.construct_json(download_location)
    return json
4

1 回答 1

1

如果启用了线程(默认情况下禁用),则可能会发生这种情况。如果您必须使用本地文件系统,那么始终建议将其隔离,例如使用临时目录。tempfile.TemporaryDirectory例如,您可以使用它。

import os
from tempfile import TemporaryDirectory

# ...

@app.route("/process_document", methods=['GET'])
def process_document():
    with TemporaryDirectory() as path:
        download_location = os.path.join(path, "document.txt")
        urllib.request.urlretrieve(
            request.args.get('document_location'),
            download_location
        )
        json = some_module.construct_json(download_location)
        return json

使用临时目录或文件有助于避免您描述的并发问题。但它也可以防止您的函数抛出异常并保留文件的问题(它可能无法防止严重的崩溃)。这样您就不会意外地从以前的运行中拾取文件。

于 2018-10-08T12:32:27.447 回答