-
Notifications
You must be signed in to change notification settings - Fork 0
POST requests #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| from dataclasses import dataclass, field | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class HttpRequestContext: | ||
| method: str = "GET" | ||
| query: dict[str, str] = field(default_factory=dict) | ||
| postvars: dict[str, str] = field(default_factory=dict) | ||
| headers: dict[str, str] = field(default_factory=dict) |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,25 +1,101 @@ | ||
| import json | ||
| from urllib.parse import parse_qsl | ||
|
|
||
| from starlette.applications import Starlette | ||
| from starlette.datastructures import UploadFile | ||
| from starlette.requests import Request | ||
| from starlette.responses import Response | ||
| from starlette.routing import Route | ||
|
|
||
| from httk.web.engine.site_engine import SiteEngine | ||
| from httk.web.model.errors import WebError | ||
| from httk.web.model.request import HttpRequestContext | ||
|
|
||
| MAX_POST_BODY_BYTES = 1_000_000 | ||
|
|
||
|
|
||
| async def _handle_request(request: Request) -> Response: | ||
| engine: SiteEngine = request.app.state.engine | ||
| route = request.path_params.get("path", "") | ||
| query = dict(request.query_params) | ||
| try: | ||
| result = engine.render(route, query=query) | ||
| request_context = HttpRequestContext( | ||
| method=request.method, | ||
| query=dict(request.query_params), | ||
| postvars=await _extract_postvars(request), | ||
| headers={k.lower(): v for k, v in request.headers.items()}, | ||
| ) | ||
| result = engine.render(route, request=request_context) | ||
| except WebError as exc: | ||
| return Response(content=str(exc), status_code=exc.status_code, media_type="text/plain") | ||
|
|
||
| return Response(content=result.body, status_code=result.status_code, media_type=result.content_type) | ||
|
|
||
|
|
||
| def create_app(*, engine: SiteEngine, debug: bool = False) -> Starlette: | ||
| app = Starlette(debug=debug, routes=[Route("/{path:path}", _handle_request, methods=["GET"])]) | ||
| app = Starlette(debug=debug, routes=[Route("/{path:path}", _handle_request, methods=["GET", "POST"])]) | ||
| app.state.engine = engine | ||
| return app | ||
|
|
||
|
|
||
| async def _extract_postvars(request: Request) -> dict[str, str]: | ||
| if request.method.upper() != "POST": | ||
| return {} | ||
|
|
||
| content_type = request.headers.get("content-type", "").lower() | ||
| content_length = request.headers.get("content-length") | ||
| if content_length is not None: | ||
| try: | ||
| if int(content_length) > MAX_POST_BODY_BYTES: | ||
| raise WebError( | ||
| f"POST body too large (>{MAX_POST_BODY_BYTES} bytes).", | ||
| status_code=413, | ||
| ) | ||
| except ValueError: | ||
| # Ignore invalid content-length values and attempt best-effort parsing. | ||
| pass | ||
|
|
||
| if "application/x-www-form-urlencoded" in content_type: | ||
| raw = await request.body() | ||
| if len(raw) > MAX_POST_BODY_BYTES: | ||
| raise WebError( | ||
| f"POST body too large (>{MAX_POST_BODY_BYTES} bytes).", | ||
| status_code=413, | ||
| ) | ||
| body = raw.decode("utf-8", errors="replace") | ||
| return {k: v for k, v in parse_qsl(body, keep_blank_values=True)} | ||
|
|
||
| if "application/json" in content_type: | ||
| raw = await request.body() | ||
| if len(raw) > MAX_POST_BODY_BYTES: | ||
| raise WebError( | ||
| f"POST body too large (>{MAX_POST_BODY_BYTES} bytes).", | ||
| status_code=413, | ||
| ) | ||
| try: | ||
| payload = json.loads(raw.decode("utf-8", errors="replace")) | ||
| except json.JSONDecodeError: | ||
| return {} | ||
| if isinstance(payload, dict): | ||
| out_json: dict[str, str] = {} | ||
| for key, value in payload.items(): | ||
| if isinstance(value, (str, int, float, bool)) or value is None: | ||
| out_json[str(key)] = "" if value is None else str(value) | ||
| return out_json | ||
| return {} | ||
|
|
||
| if "multipart/form-data" in content_type: | ||
| try: | ||
| form = await request.form() | ||
| except Exception: | ||
| return {} | ||
| out_form: dict[str, str] = {} | ||
| for key, value in form.multi_items(): | ||
| normalized_key = str(key) | ||
| if isinstance(value, UploadFile): | ||
| # Keep uploads explicit and compact in postvars. | ||
| out_form[normalized_key] = value.filename or "" | ||
| else: | ||
| out_form[normalized_key] = str(value) | ||
| return out_form | ||
|
rartino marked this conversation as resolved.
|
||
|
|
||
| return {} | ||
|
rartino marked this conversation as resolved.
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.