The problem is that the middleware and synchronization interface are not in the same thread #11482
-
First Check
Commit to Help
Example Codemy_fast_api.py
import uuid
import asyncio
import threading
from hypercorn.config import Config
from hypercorn.asyncio import serve
from fastapi import FastAPI, Request
from log_new import logger, g
app = FastAPI()
config = Config()
config.bind = ["127.0.0.1:9999"]
@app.middleware("http")
async def cal_time(req: Request, call_next):
g.transaction_id = str(uuid.uuid4()).replace('-', '')
logger.warn("threading id = %s, func=%s ", threading.current_thread(), "middleware")
response = await call_next(req)
return response
@app.get("/test1")
def test1():
print("test1 logger=", logger) # test1 logger= <LoggerPrinter log_test_p2956 (NOTSET)>
logger.warn("threading id = %s, func=%s ", threading.current_thread(), "test1")
return "test1"
@app.get("/test2")
async def test2():
print("test2 logger=", logger) # test2 logger= <LoggerPrinter log_test_p2956 (NOTSET)>
logger.warn("threading id = %s, func=%s ", threading.current_thread(), "test2")
return "test2"
async def run_server():
await serve(app, config)
if __name__ == '__main__':
asyncio.run(run_server(), debug=True) log_new.py
|
Beta Was this translation helpful? Give feedback.
Answered by
hanzhenbjm
Apr 25, 2024
Replies: 1 comment
-
The contextvars library works |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
tiangolo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The contextvars library works