Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion adiuvare/integrations/flask.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import io
import json

from werkzeug.wrappers import Request, Response
Expand All @@ -14,14 +15,18 @@ def __init__(self, app, guard, flask_app=None) -> None:
self._flask = flask_app

def __call__(self, environ, start_response):
content_length = int(environ.get("CONTENT_LENGTH") or 0)
body_bytes = environ["wsgi.input"].read(content_length) if content_length > 0 else b""
environ["wsgi.input"] = io.BytesIO(body_bytes)

req = Request(environ)
raw_ip = req.headers.get("x-forwarded-for", "")
ip = raw_ip.split(",", 1)[0].strip() or req.remote_addr or "127.0.0.1"
route_cfg = self._route_cfg(req)
if route_cfg.get("exempt"):
return self._app(environ, start_response)

body_text = req.get_data(as_text=True)
body_text = body_bytes.decode("utf-8", errors="replace")
query_text = req.query_string.decode("utf-8") if req.query_string else ""
payload = ctx_payload(body_text, query_text)

Expand Down
24 changes: 23 additions & 1 deletion tests/test_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,4 +461,26 @@ def test_threadsafe_items_returns_all_identities():

assert len(result) == 5
for i in range(5):
assert f"user-{i}" in identities
assert f"user-{i}" in identities


def test_flask_request_json_readable_after_middleware_inspection():

app = Flask(__name__)
guard = Guard()
guard.use(app, framework="flask")

@app.post("/notes")
def create_note():
data = request.get_json(silent=True)
assert data is not None
return jsonify(received=data), 201

client = app.test_client()
res = client.post(
"/notes",
json={"title": "Shopping List", "body": "milk, bread"},
headers={"x-user-id": "u1"},
)
assert res.status_code == 201
assert res.get_json() == {"received": {"title": "Shopping List", "body": "milk, bread"}}
Loading