ryuuseigun 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ryuuseigun-0.1.0/.github/workflows/test.yml +29 -0
- ryuuseigun-0.1.0/.gitignore +7 -0
- ryuuseigun-0.1.0/CHANGELOG.md +5 -0
- ryuuseigun-0.1.0/LICENSE +201 -0
- ryuuseigun-0.1.0/PKG-INFO +296 -0
- ryuuseigun-0.1.0/README.md +263 -0
- ryuuseigun-0.1.0/pyproject.toml +45 -0
- ryuuseigun-0.1.0/ryuuseigun/__init__.py +2432 -0
- ryuuseigun-0.1.0/ryuuseigun/exceptions.py +44 -0
- ryuuseigun-0.1.0/ryuuseigun/utils.py +225 -0
- ryuuseigun-0.1.0/tests/test_framework.py +1056 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
name: Test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [master, main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [master, main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
python-version: ["3.13", "3.14"]
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
|
|
18
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
19
|
+
uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: ${{ matrix.python-version }}
|
|
22
|
+
|
|
23
|
+
- name: Install dependencies
|
|
24
|
+
run: |
|
|
25
|
+
python -m pip install --upgrade pip
|
|
26
|
+
pip install -e ".[test]"
|
|
27
|
+
|
|
28
|
+
- name: Run tests
|
|
29
|
+
run: python -m pytest tests/ -v
|
ryuuseigun-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ryuuseigun
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight, type-safe, async web framework inspired by Flask
|
|
5
|
+
Project-URL: source, https://github.com/depthbomb/ryuuseigun
|
|
6
|
+
Project-URL: documentation, https://github.com/depthbomb/ryuuseigun
|
|
7
|
+
Project-URL: changelog, https://github.com/depthbomb/ryuuseigun/blob/master/CHANGELOG.md
|
|
8
|
+
Author: depthbomb
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Natural Language :: English
|
|
16
|
+
Classifier: Operating System :: MacOS
|
|
17
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
20
|
+
Classifier: Programming Language :: Python
|
|
21
|
+
Classifier: Programming Language :: Python :: 3
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Software Development
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
27
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
28
|
+
Classifier: Typing :: Typed
|
|
29
|
+
Requires-Python: >=3.13
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest>=9.0; extra == 'test'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# ☄️ Ryūseigun
|
|
35
|
+
|
|
36
|
+
A lightweight, type-safe, async web framework inspired by [Flask.](https://flask.palletsprojects.com)
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
_Ryūseigun_ is deliberately minimal, embracing a “bring-your-own-X” philosophy. It provides just enough to give you
|
|
41
|
+
something that works and leaves plenty of room to do things how you want to.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```shell
|
|
46
|
+
pip install ryuuseigun
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
You will also need an ASGI server like [Uvicorn](https://uvicorn.dev/) or
|
|
50
|
+
[Granian](https://github.com/emmett-framework/granian). These two servers have been tested with
|
|
51
|
+
Ryūseigun, others have not.
|
|
52
|
+
|
|
53
|
+
## Minimal Example
|
|
54
|
+
|
|
55
|
+
```py
|
|
56
|
+
from ryuuseigun import Ryuuseigun
|
|
57
|
+
|
|
58
|
+
app = Ryuuseigun(__name__)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Kitchen Sink Example
|
|
62
|
+
|
|
63
|
+
```py
|
|
64
|
+
from json import loads, dumps
|
|
65
|
+
from ryuuseigun import Context, Response, Ryuuseigun
|
|
66
|
+
|
|
67
|
+
app = Ryuuseigun(
|
|
68
|
+
__name__,
|
|
69
|
+
# Optional. If omitted, `ctx.url_for(..., full_url=True)` derives origin from request headers.
|
|
70
|
+
base_url='http://localhost:8000',
|
|
71
|
+
# A route ending with a slash is treated the same as a route without a slash
|
|
72
|
+
strict_slashes=False,
|
|
73
|
+
# Serve files from this path (e.g. public/favicon.ico -> website.com/favicon.ico)
|
|
74
|
+
public_dir='./public',
|
|
75
|
+
# Reject request bodies over this limit with HTTP 413 (set None to disable)
|
|
76
|
+
max_request_body_size=16 * 1024 * 1024,
|
|
77
|
+
# JSON parser/serializer hooks (swap with orjson.loads/orjson.dumps if desired)
|
|
78
|
+
loads=loads,
|
|
79
|
+
dumps=dumps,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# -------------- #
|
|
83
|
+
# Error handlers #
|
|
84
|
+
# -------------- #
|
|
85
|
+
@app.error_handler(Exception) # More specific exception classes will be prioritized
|
|
86
|
+
async def handle_exceptions(ctx: Context, e: Exception) -> Response:
|
|
87
|
+
return Response(str(e), status=500)
|
|
88
|
+
|
|
89
|
+
# ---------- #
|
|
90
|
+
# Blueprints #
|
|
91
|
+
# ---------- #
|
|
92
|
+
from ryuuseigun import Blueprint
|
|
93
|
+
|
|
94
|
+
api_bp = Blueprint('api', url_prefix='/api')
|
|
95
|
+
|
|
96
|
+
@api_bp.get('/')
|
|
97
|
+
async def api_index() -> str:
|
|
98
|
+
return 'API docs'
|
|
99
|
+
|
|
100
|
+
@api_bp.error_handler(Exception) # Blueprint-specific error handlers
|
|
101
|
+
async def handle_api_errors(ctx: Context, e: Exception) -> dict:
|
|
102
|
+
return {
|
|
103
|
+
'success': True,
|
|
104
|
+
'message': str(e),
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
users_bp = Blueprint('users', url_prefix='/users')
|
|
108
|
+
|
|
109
|
+
@users_bp.get('/<username>')
|
|
110
|
+
async def get_user(ctx: Context) -> str:
|
|
111
|
+
return ctx.request.route_params['username']
|
|
112
|
+
|
|
113
|
+
api_bp.register_blueprint(users_bp)
|
|
114
|
+
app.register_blueprint(api_bp) # GET /api/users/caim -> 'caim'
|
|
115
|
+
|
|
116
|
+
# ------------------------------------ #
|
|
117
|
+
# Request globals & lifecycle handlers #
|
|
118
|
+
# ------------------------------------ #
|
|
119
|
+
from typing import cast
|
|
120
|
+
|
|
121
|
+
@app.before_request
|
|
122
|
+
async def before_all_requests(ctx: Context):
|
|
123
|
+
ctx.g['value'] = 123
|
|
124
|
+
|
|
125
|
+
@ctx.after_this_request # Called after *this* request
|
|
126
|
+
async def after_all_requests(response: Response):
|
|
127
|
+
response.set_header('X-My-Value', str(ctx.g['value']))
|
|
128
|
+
return response
|
|
129
|
+
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
@app.route('/', methods=['GET'])
|
|
133
|
+
async def index(ctx: Context) -> str: # Route handlers can return `str`, `dict`, or `Response` (`Response.stream(...)` for streaming)
|
|
134
|
+
my_value = cast(int, ctx.g['value'])
|
|
135
|
+
return str(my_value)
|
|
136
|
+
|
|
137
|
+
# -------------------- #
|
|
138
|
+
# ASGI lifespan events #
|
|
139
|
+
# -------------------- #
|
|
140
|
+
@app.on_startup
|
|
141
|
+
async def startup() -> None:
|
|
142
|
+
await connect_db()
|
|
143
|
+
|
|
144
|
+
@app.on_shutdown
|
|
145
|
+
async def shutdown() -> None:
|
|
146
|
+
await disconnect_db()
|
|
147
|
+
|
|
148
|
+
# ---------------- #
|
|
149
|
+
# Route parameters #
|
|
150
|
+
# ---------------- #
|
|
151
|
+
@app.post('/multiply/<int:num>/<int:factor>') # HTTP method shortcuts for convenience
|
|
152
|
+
async def index(ctx: Context) -> dict:
|
|
153
|
+
num = ctx.request.route_param('num', as_type=int)
|
|
154
|
+
factor = ctx.request.route_param('factor', as_type=int)
|
|
155
|
+
return {
|
|
156
|
+
'num': num,
|
|
157
|
+
'factor': factor,
|
|
158
|
+
'product': num * factor,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
# ------------------ #
|
|
162
|
+
# Route converters #
|
|
163
|
+
# ------------------ #
|
|
164
|
+
# Built-in converters: `int`, `float`, and `path`.
|
|
165
|
+
# Route matching is specificity-aware: static segments and typed converters win over broader `path` captures.
|
|
166
|
+
# Register custom route converters with parse/format behavior:
|
|
167
|
+
app.register_converter(
|
|
168
|
+
'hex',
|
|
169
|
+
regex=r'[0-9a-fA-F]+',
|
|
170
|
+
parse=lambda raw: int(raw, 16),
|
|
171
|
+
format=lambda value: format(int(value), 'x'),
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
@app.get('/colors/<hex:color>')
|
|
175
|
+
async def show_color(ctx: Context) -> dict:
|
|
176
|
+
color = ctx.request.route_param('color') # int (parsed from hex)
|
|
177
|
+
return {'decimal': color}
|
|
178
|
+
|
|
179
|
+
@app.get('/links/color')
|
|
180
|
+
async def color_link(ctx: Context) -> dict:
|
|
181
|
+
# Uses converter `format`: -> /colors/ff
|
|
182
|
+
return {'url': ctx.url_for('show_color', color=255)}
|
|
183
|
+
|
|
184
|
+
# Converters can also be scoped to blueprints:
|
|
185
|
+
assets_bp = Blueprint('assets', url_prefix='/assets')
|
|
186
|
+
assets_bp.register_converter(
|
|
187
|
+
'slugpath',
|
|
188
|
+
regex=r'.+',
|
|
189
|
+
parse=str,
|
|
190
|
+
format=str,
|
|
191
|
+
allows_slash=True, # allow values like "images/icons/logo.svg"
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
@assets_bp.get('/<slugpath:key>')
|
|
195
|
+
async def get_asset(ctx: Context) -> dict:
|
|
196
|
+
return {'key': ctx.request.route_param('key')}
|
|
197
|
+
|
|
198
|
+
app.register_blueprint(assets_bp)
|
|
199
|
+
|
|
200
|
+
# --------------------- #
|
|
201
|
+
# Request body (async) #
|
|
202
|
+
# --------------------- #
|
|
203
|
+
@app.post('/upload')
|
|
204
|
+
async def upload(ctx: Context) -> dict:
|
|
205
|
+
total = 0
|
|
206
|
+
async for chunk in ctx.request.iter_body():
|
|
207
|
+
total += len(chunk)
|
|
208
|
+
return {'bytes': total}
|
|
209
|
+
|
|
210
|
+
@app.post('/json')
|
|
211
|
+
async def json_endpoint(ctx: Context) -> dict:
|
|
212
|
+
payload = await ctx.request.json_async()
|
|
213
|
+
return {'ok': True, 'payload': payload}
|
|
214
|
+
|
|
215
|
+
# In ASGI request flow, body parsing is stream-first.
|
|
216
|
+
# Use `await request.read()/json_async()/form_async()/payload_async()` for body access.
|
|
217
|
+
|
|
218
|
+
# ------------------------------ #
|
|
219
|
+
# Parsing/coercion customization #
|
|
220
|
+
# ------------------------------ #
|
|
221
|
+
# Register custom request payload parsers by content-type match:
|
|
222
|
+
app.add_request_payload_parser(
|
|
223
|
+
'text/csv',
|
|
224
|
+
lambda request: [row.split(',') for row in request.body.decode('utf-8').splitlines() if row],
|
|
225
|
+
first=True, # check before built-in parsers
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# Register custom response coercers for arbitrary return types:
|
|
229
|
+
class Box:
|
|
230
|
+
def __init__(self, value: str):
|
|
231
|
+
self.value = value
|
|
232
|
+
|
|
233
|
+
app.add_response_coercer(
|
|
234
|
+
lambda result: Response(f'box:{result.value}', status=201) if isinstance(result, Box) else None,
|
|
235
|
+
first=True,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
# ------------------------------ #
|
|
239
|
+
# Conditional caching (optional) #
|
|
240
|
+
# ------------------------------ #
|
|
241
|
+
from datetime import datetime, timezone
|
|
242
|
+
from ryuuseigun.utils import apply_conditional_response, make_etag
|
|
243
|
+
|
|
244
|
+
@app.get('/assets/app.js')
|
|
245
|
+
async def app_js(ctx: Context) -> Response:
|
|
246
|
+
body = b'console.log("hello")\n'
|
|
247
|
+
response = Response(
|
|
248
|
+
body=body,
|
|
249
|
+
headers={'content-type': 'application/javascript'},
|
|
250
|
+
)
|
|
251
|
+
return apply_conditional_response(
|
|
252
|
+
ctx,
|
|
253
|
+
response,
|
|
254
|
+
etag=make_etag(body),
|
|
255
|
+
last_modified=datetime(2026, 2, 20, tzinfo=timezone.utc),
|
|
256
|
+
cache_control='public, max-age=300',
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
# If the client sends matching `If-None-Match` or `If-Modified-Since`,
|
|
260
|
+
# `apply_conditional_response` returns HTTP 304 automatically.
|
|
261
|
+
|
|
262
|
+
#----------#
|
|
263
|
+
# Sessions #
|
|
264
|
+
#----------#
|
|
265
|
+
# Sessions default to an in-memory engine (per process, cookie-identified, not shared across workers).
|
|
266
|
+
# You can tune it with `session_ttl`, `session_purge_interval`, and `session_max_entries`, or fully
|
|
267
|
+
# replace storage by passing a custom `session_engine` object that implements: `load`, `create`,
|
|
268
|
+
# `save`, and `destroy` as async methods.
|
|
269
|
+
# Session access is async-first: use `await ctx.session_async()` when you need to create/load a
|
|
270
|
+
# session.
|
|
271
|
+
@app.get('/login')
|
|
272
|
+
async def login(ctx: Context) -> str:
|
|
273
|
+
session = await ctx.session_async()
|
|
274
|
+
session['user_id'] = 123
|
|
275
|
+
return 'ok'
|
|
276
|
+
|
|
277
|
+
@app.get('/me')
|
|
278
|
+
async def me(ctx: Context) -> str:
|
|
279
|
+
session = await ctx.session_async()
|
|
280
|
+
user_id = session.get('user_id')
|
|
281
|
+
return str(user_id or 'anonymous')
|
|
282
|
+
|
|
283
|
+
@app.get('/logout')
|
|
284
|
+
async def logout(ctx: Context) -> str:
|
|
285
|
+
session = await ctx.session_async()
|
|
286
|
+
session.destroy()
|
|
287
|
+
return 'bye'
|
|
288
|
+
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
## Testing
|
|
292
|
+
|
|
293
|
+
```shell
|
|
294
|
+
pip install -e ".[test]"
|
|
295
|
+
python -m pytest
|
|
296
|
+
```
|