william
william

Reputation: 309

werkzeug Local got unexpected value

I may have a misunderstood with werkzeug.local

Here is my simplified test code:

from flask import Flask, request
from werkzeug.local import Local
import threading

app = Flask(__name__)

local_data = Local()

@app.route('/')
def index():
    if local_data.data:
         # I don't know why new request without token will get token and return here.
         return local_data.data
    local_data.data = request.headers.get('token')
    return local_data.data

if __name__ == "__main__":
    app.run()

In fact, my logic is that when a request arrives, it first performs a get. If it doesn't retrieve a value from local_data.data, it sets a token to local_data.data and returns it. However, I noticed that under concurrent conditions, a new request coming in would get content it shouldn't have access to.

I expect that only the first request will carry a token, and other requests should return None because there are nothing in their local thread.

However, in continuous observations, I found that many requests successfully retrieved the value stored in the local_data.data, which means local_data is not working here.

I don't know why, and GPT says my code should have no mistakes...

Upvotes: 0

Views: 44

Answers (0)

Related Questions