Created
June 14, 2021 12:45
-
-
Save batiste/fbeae77f01b6b8a761e50f8ea73fd71b to your computer and use it in GitHub Desktop.
WSGI middleware storing request env. in the thread, it will work with Django, Flask, Fast API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A middlware that stores the envrionement dict inside the current | |
# thread, implement a get_request_id method for easy retrieval | |
from threading import local | |
_threadlocals = local() | |
_threadvariables = set() | |
def set_thread_variable(key, val): | |
_threadvariables.add(key) | |
setattr(_threadlocals, key, val) | |
def get_thread_variable(key, default=None): | |
return getattr(_threadlocals, key, default) | |
def get_request_id(): | |
environ = get_thread_variable('environ') | |
return environ.get('HTTP_X_REQUEST_ID', '-') | |
class thread_environ(): | |
''' | |
WSGI middleware that saves the environnement variable | |
on the thread | |
''' | |
def __init__(self, app): | |
self.app = app | |
def __call__(self, environ, start_response): | |
set_thread_variable('environ', environ) | |
return self.app(environ, start_response) | |
##### later on in the Flask application setup | |
import requests | |
import time | |
from flask import Flask, request | |
import logging | |
import sys | |
from middleware import thread_environ, get_request_id, get_thread_variable | |
app = Flask(__name__) | |
# SETUP the WSGI middlware here | |
app.wsgi_app = thread_environ(app.wsgi_app) | |
@app.route("/") | |
def hello(): | |
print(get_request_id()) | |
print(get_thread_variable('environ').get('HTTP_CACHE_CONTROL')) | |
time.sleep(1) | |
return "<h1 style='color:blue'>Hello There!</h1>" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment