Last active
October 13, 2017 05:26
-
-
Save wonderbeyond/ae7c27be9536d65966f5d94464df0d96 to your computer and use it in GitHub Desktop.
flask request id for both server and client
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
from flask import request, g | |
from xid import Xid | |
def _init_request_id(): | |
""" | |
See also: | |
http://blog.mcpolemic.com/2016/01/18/adding-request-ids-to-flask.html | |
""" | |
# See: https://www.nginx.com/blog/application-tracing-nginx-plus/ | |
request_id = request.headers.get('X-Request-ID') | |
if not request_id: | |
request_id = Xid().string() | |
g.request_id = request_id | |
def _set_resp_header(resp): | |
resp.headers.add('X-Request-ID', g.request_id) | |
return resp | |
class RequestID(object): | |
""" | |
app = Flask(__name__) | |
RequestID(app) | |
@app.route('/req-id') | |
def req_id(): | |
return "{0} is the unique ID for the request, " | |
"which is also in response headers".format(g.request_id) | |
""" | |
def __init__(self, app): | |
self.app = app | |
self.init_app(app) | |
def init_app(self, app): | |
app.before_request(_init_request_id) | |
app.after_request(_set_resp_header) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment