Skip to content

when use copy_current_request_context and ThreadPoolExecutor, I got error. #5252

@Alvin4567

Description

@Alvin4567

I want to use the main thread's request context in the sub-thread. So I use the decorator copy_current_request_context. But I got an error that <Token var=<ContextVar name='flask.request_ctx' at 0x1067aef90> at 0x106c71280> was created in a different Context.

The weirdest thing is when I debug the code one by one, I will get the expected results sometimes.

This is a simple code.

import random
import string
import requests

from flask import Flask, copy_current_request_context
from concurrent.futures import ThreadPoolExecutor

app = Flask(__name__)

def get_trace_id(number):
    trace_id =  "".join(random.sample(string.ascii_letters, number))
    print(requests.get("https://www.google.com").text)
    return trace_id


@app.route("/")
def hello():
    @copy_current_request_context
    def inner_func(number):
        return get_trace_id(number)

    with ThreadPoolExecutor(20) as executor:
        res_iter = executor.map(inner_func, [1, 2, 3, 4, 5])
    return list(res_iter)


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

Environment:

  • Python version: 3.8.17
  • Flask version: 2.3.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions