Skip to content

Commit ba68ec8

Browse files
authored
Add public flask.g.request_id when not set (fix #50) (#51)
1 parent d40d708 commit ba68ec8

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

docs/flask.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ Flask based projects that want to follow the Dockerflow specs:
2525

2626
- Hooks to add custom Dockerflow checks.
2727

28+
- Adds ``request_id`` to the `flask.g`_ application namespace when it isn't already set
29+
30+
.. _`flask.g`: https://flask.palletsprojects.com/en/1.1.x/api/#flask.g
2831
.. _`mozlog`: https://github.com/mozilla-services/Dockerflow/blob/master/docs/mozlog.md
2932
.. _`request.summary`: https://github.com/mozilla-services/Dockerflow/blob/master/docs/mozlog.md#application-request-summary-type-requestsummary
3033

src/dockerflow/flask/app.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,8 @@ def _before_request(self):
204204
The before_request callback.
205205
"""
206206
g._request_id = str(uuid.uuid4())
207+
if not hasattr(g, "request_id"):
208+
g.request_id = g._request_id
207209
g._start_timestamp = time.time()
208210

209211
def _after_request(self, response):

tests/flask/test_flask.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ def test_request_summary(caplog, dockerflow, app):
225225
with app.test_client() as test_client:
226226
test_client.get("/", headers=headers)
227227
assert getattr(g, "_request_id") is not None
228+
assert getattr(g, "request_id") is not None
228229
assert isinstance(getattr(g, "_start_timestamp"), float)
229230

230231
assert len(caplog.records) == 1
@@ -233,6 +234,19 @@ def test_request_summary(caplog, dockerflow, app):
233234
assert getattr(request, "uid", None) is None
234235

235236

237+
def test_preserves_existing_request_id(dockerflow, app):
238+
with app.test_client() as test_client:
239+
240+
def set_dummy_request_id():
241+
g.request_id = "predefined-request-id"
242+
243+
app.before_request(set_dummy_request_id)
244+
245+
test_client.get("/", headers=headers)
246+
assert getattr(g, "_request_id") is not None
247+
assert getattr(g, "request_id") != getattr(g, "_request_id")
248+
249+
236250
def assert_user(app, caplog, user, callback):
237251
with app.test_request_context("/", headers=headers):
238252
assert has_request_context()

0 commit comments

Comments
 (0)