Compare commits
126 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10e740da2b | ||
|
|
ba6893ca0f | ||
|
|
a99b658c3f | ||
|
|
aeffcf82ba | ||
|
|
a862a3353b | ||
|
|
fb7aeac2ac | ||
|
|
baf02ae781 | ||
|
|
0bae4c9477 | ||
|
|
053b8a8138 | ||
|
|
220d4cd92a | ||
|
|
1c7020ca1a | ||
|
|
3b77e5d6a1 | ||
|
|
f128b3ded4 | ||
|
|
ae9f237ce6 | ||
|
|
4c2d2896c3 | ||
|
|
38f5a27b33 | ||
|
|
d0808efa6b | ||
|
|
ce9de6e37a | ||
|
|
d61785b2e8 | ||
|
|
680cbefc19 | ||
|
|
2d4189100a | ||
|
|
27fc03f100 | ||
|
|
f70c524fb0 | ||
|
|
79897e7980 | ||
|
|
7edc7c3a38 | ||
|
|
84361045a3 | ||
|
|
e9c9937b41 | ||
|
|
7addcf4bb5 | ||
|
|
6045390cef | ||
|
|
c12d465809 | ||
|
|
cca0b0f693 | ||
|
|
7071358b1f | ||
|
|
d7fcd1a247 | ||
|
|
eb5e249e34 | ||
|
|
9bc3dced6c | ||
|
|
786e5e5337 | ||
|
|
1d419ce59b | ||
|
|
7c98c4589d | ||
|
|
0f219fd494 | ||
|
|
e146e2d08d | ||
|
|
dc61470fa9 | ||
|
|
d7a9c53563 | ||
|
|
4ddb09ceb3 | ||
|
|
3dffa05ffb | ||
|
|
b93a55c9f2 | ||
|
|
f5d3d931ed | ||
|
|
654a85f46b | ||
|
|
3c936a82e0 | ||
|
|
4c0ace1b01 | ||
|
|
d9d7ff0825 | ||
|
|
7c42a18436 | ||
|
|
ea84fcb435 | ||
|
|
f30c4733f0 | ||
|
|
cd0b3234dd | ||
|
|
1f64478957 | ||
|
|
815594fc8b | ||
|
|
086f2af3de | ||
|
|
f317b15bdb | ||
|
|
b6f232db11 | ||
|
|
e7ee74d6bb | ||
|
|
847dfd1321 | ||
|
|
1aa035378e | ||
|
|
1edfb8daa7 | ||
|
|
9337a2ec9b | ||
|
|
11a91a6035 | ||
|
|
99f65c0198 | ||
|
|
4cc2e95338 | ||
|
|
d203df75fe | ||
|
|
00bf535821 | ||
|
|
3bc31f10b2 | ||
|
|
aa76e6378b | ||
|
|
c6b99b6d81 | ||
|
|
953dd94321 | ||
|
|
68a53a7ae7 | ||
|
|
c92b5ae282 | ||
|
|
48ce31e699 | ||
|
|
6a33e817a2 | ||
|
|
265009ecd6 | ||
|
|
2efbd67878 | ||
|
|
d807011ad0 | ||
|
|
675c978797 | ||
|
|
cd87abba30 | ||
|
|
fd7931e1ae | ||
|
|
d487a73c1e | ||
|
|
d864b81b65 | ||
|
|
d7459f23b2 | ||
|
|
32f5e415e7 | ||
|
|
c46e429106 | ||
|
|
4eac013087 | ||
|
|
496a288064 | ||
|
|
bcd876fcae | ||
|
|
5e5fc5e93e | ||
|
|
8895af3737 | ||
|
|
0a021462e0 | ||
|
|
482ab6d5ca | ||
|
|
5fe06f6bd5 | ||
|
|
c170e840ec | ||
|
|
3a39b47ea8 | ||
|
|
53287217ae | ||
|
|
6ffb8a8fe9 | ||
|
|
0151611fc8 | ||
|
|
4204db61e5 | ||
|
|
12438743a8 | ||
|
|
7cbb1edf59 | ||
|
|
dac6df7a7a | ||
|
|
5d6e838f3c | ||
|
|
563bfdc8f5 | ||
|
|
679d8e63b8 | ||
|
|
4cb155ee41 | ||
|
|
dea79c5ce2 | ||
|
|
6b1fd61917 | ||
|
|
f6876c0d15 | ||
|
|
904d5fcaa2 | ||
|
|
a0ea439def | ||
|
|
a1801d9a53 | ||
|
|
14f2c9d345 | ||
|
|
d0a4cf8fa7 | ||
|
|
901f4e55b8 | ||
|
|
53b28f9938 | ||
|
|
f6cba2c0f7 | ||
|
|
38262c56d3 | ||
|
|
a3363c7b8c | ||
|
|
e44c271bae | ||
|
|
bf519478cb | ||
|
|
8d1ca808cb | ||
|
|
1f804f869c |
3
.github/FUNDING.yml
vendored
3
.github/FUNDING.yml
vendored
@@ -1,3 +0,0 @@
|
||||
github: miguelgrinberg
|
||||
patreon: miguelgrinberg
|
||||
custom: https://paypal.me/miguelgrinberg
|
||||
12
.github/workflows/tests.yml
vendored
12
.github/workflows/tests.yml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
python: ['3.8', '3.9', '3.10', '3.11', '3.12']
|
||||
python: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13', '3.14']
|
||||
fail-fast: false
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
@@ -42,6 +42,15 @@ jobs:
|
||||
- run: python -m pip install --upgrade pip wheel
|
||||
- run: pip install tox tox-gh-actions
|
||||
- run: tox -eupy
|
||||
tests-circuitpython:
|
||||
name: tests-circuitpython
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v3
|
||||
- run: python -m pip install --upgrade pip wheel
|
||||
- run: pip install tox tox-gh-actions
|
||||
- run: tox -ecpy
|
||||
coverage:
|
||||
name: coverage
|
||||
runs-on: ubuntu-latest
|
||||
@@ -55,6 +64,7 @@ jobs:
|
||||
with:
|
||||
files: ./coverage.xml
|
||||
fail_ci_if_error: true
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
benchmark:
|
||||
name: benchmark
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -25,6 +25,8 @@ wheels/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
requirements.txt
|
||||
requirements-dev.txt
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
@@ -90,6 +92,8 @@ venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
.direnv
|
||||
.envrc
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
|
||||
107
CHANGES.md
107
CHANGES.md
@@ -1,5 +1,112 @@
|
||||
# Microdot change log
|
||||
|
||||
**Release 2.5.1** - 2025-12-21
|
||||
|
||||
- CSRF: accept cross-site request if origin is in the CORS allowed origin list ([commit](https://github.com/miguelgrinberg/microdot/commit/ba6893ca0fb3c3dd18cf934f8eee893cc2a10daa))
|
||||
|
||||
**Release 2.5.0** - 2025-12-21
|
||||
|
||||
- CSRF protection [#335](https://github.com/miguelgrinberg/microdot/issues/335) ([commit](https://github.com/miguelgrinberg/microdot/commit/0bae4c9477e9fdb231d1979cc6ed26c31e12b1aa))
|
||||
- Added support for ASGI lifespan events [#322](https://github.com/miguelgrinberg/microdot/issues/322) ([commit](https://github.com/miguelgrinberg/microdot/commit/f128b3ded45ccd418a00d199769240342a613b5e))
|
||||
- Added `scheme` and `route` attributes to the request object ([commit](https://github.com/miguelgrinberg/microdot/commit/1c7020ca1a3e5a6a1549dc52de38a0b7fd0a439a))
|
||||
- Added `Login.get_current_user()` helper method ([commit](https://github.com/miguelgrinberg/microdot/commit/053b8a81380fcdf285592a32e6b590ee50b7d048))
|
||||
|
||||
**Release 2.4.0** - 2025-11-08
|
||||
|
||||
- SSE: Add support for the retry command and keepalive comments ([commit](https://github.com/miguelgrinberg/microdot/commit/d0808efa6b32e00992596f1bb3d4c3a372df2168))
|
||||
- Ignore `expires` and `max_age` arguments if passed to `Response.delete_cookie` [#323](https://github.com/miguelgrinberg/microdot/issues/323) ([commit](https://github.com/miguelgrinberg/microdot/commit/d61785b2e8d18438e5031de9c49e61642e5cfb3f))
|
||||
- Ignore "muted" errors during request creation ([commit](https://github.com/miguelgrinberg/microdot/commit/ce9de6e37a6323664eb7666b817932f371f1e099))
|
||||
- Add package version to `microdot/__init__.py` file [#312](https://github.com/miguelgrinberg/microdot/issues/312) ([commit](https://github.com/miguelgrinberg/microdot/commit/38f5a27b33c7968fc7414b67742e034e2b9a09ca))
|
||||
|
||||
**Release 2.3.5** - 2025-10-18
|
||||
|
||||
- Always encode ASGI response bodies to bytes ([commit](https://github.com/miguelgrinberg/microdot/commit/f70c524fb0bdc8c5fef2223c82f5e339445bc5fa))
|
||||
- Remove unused instance variable in `Microdot` class ([commit](https://github.com/miguelgrinberg/microdot/commit/27fc03f10047e4483f8d19559025d728b14a27c8))
|
||||
|
||||
**Release 2.3.4** - 2025-10-16
|
||||
|
||||
- Prevent reading past EOF in multipart parser [#309](https://github.com/miguelgrinberg/microdot/issues/309) ([commit](https://github.com/miguelgrinberg/microdot/commit/6045390cef8735cbbc9f5f7eee7a3912f00e284d))
|
||||
- Generate a valid CORS response when the request is badly formatted [#305](https://github.com/miguelgrinberg/microdot/issues/305) ([commit](https://github.com/miguelgrinberg/microdot/commit/cca0b0f693c909134bc19eb41dfb5a86226e032b))
|
||||
- Faster HTTP streaming when using ASGI [#318](https://github.com/miguelgrinberg/microdot/issues/318) ([commit](https://github.com/miguelgrinberg/microdot/commit/7addcf4bb51f1caf57663c5bb4d8cc16ee6391e1))
|
||||
- Parse empty cookies [#308](https://github.com/miguelgrinberg/microdot/issues/308) ([commit](https://github.com/miguelgrinberg/microdot/commit/c12d4658091ff7eec1ac67c83bcd51eb38af9db7))
|
||||
- Add weather dashboard example [#303](https://github.com/miguelgrinberg/microdot/issues/303) ([commit](https://github.com/miguelgrinberg/microdot/commit/7071358b1f95892b1342226b43411e036be67d3a))
|
||||
- Add Python 3.13 and 3.14 to the CI builds ([commit](https://github.com/miguelgrinberg/microdot/commit/e9c9937b41e652876241307307f3e855f4f07379))
|
||||
|
||||
**Release 2.3.3** - 2025-07-01
|
||||
|
||||
- Handle partial reads in WebSocket class [#294](https://github.com/miguelgrinberg/microdot/issues/294) ([commit](https://github.com/miguelgrinberg/microdot/commit/9bc3dced6c1f582dde0496961d25170b448ad8d7))
|
||||
- Add SVG to supported mimetypes [#302](https://github.com/miguelgrinberg/microdot/issues/302) ([commit](https://github.com/miguelgrinberg/microdot/commit/1d419ce59bf7006617109c05dc2d6fc6d1dc8235)) (thanks **Ozuba**!)
|
||||
- Do not silence exceptions that occur in the SSE task ([commit](https://github.com/miguelgrinberg/microdot/commit/654a85f46b7dd7a1e94f81193c4a78a8a1e99936))
|
||||
- Add Support for SSE responses in the test client ([commit](https://github.com/miguelgrinberg/microdot/commit/f5d3d931edfbacedebf5fdf938ef77c5ee910380))
|
||||
- Documentation improvements for the `Request` class ([commit](https://github.com/miguelgrinberg/microdot/commit/3dffa05ffb229813156b71e10a85283bdaa26d5e))
|
||||
- Additional documentation for the `URLPattern` class ([commit](https://github.com/miguelgrinberg/microdot/commit/786e5e533748e1343612c97123773aec9a1a99fc))
|
||||
- More detailed documentation for route responses ([commit](https://github.com/miguelgrinberg/microdot/commit/dc61470fa959549bb43313906ba6ed9f686babc2))
|
||||
- Additional documentation on WebSocket and SSE disconnections ([commit](https://github.com/miguelgrinberg/microdot/commit/7c98c4589de4774a88381b393444c75094532550))
|
||||
- More detailed documentation for `current_user` ([commit](https://github.com/miguelgrinberg/microdot/commit/e146e2d08deddf9b924c7657f04db28d71f34221))
|
||||
- Add a sub-application example ([commit](https://github.com/miguelgrinberg/microdot/commit/d7a9c535639268e415714b12ac898ae38e516308))
|
||||
|
||||
**Release 2.3.2** - 2025-05-08
|
||||
|
||||
- Use async error handlers in auth module [#298](https://github.com/miguelgrinberg/microdot/issues/298) ([commit](https://github.com/miguelgrinberg/microdot/commit/d9d7ff0825e4c5fbed6564d3684374bf3937df11))
|
||||
|
||||
**Release 2.3.1** - 2025-04-13
|
||||
|
||||
- Additional support needed when using `orjson` ([commit](https://github.com/miguelgrinberg/microdot/commit/cd0b3234ddb0c8ff4861d369836ec2aed77494db))
|
||||
|
||||
**Release 2.3.0** - 2025-04-12
|
||||
|
||||
- Support optional authentication methods ([commit](https://github.com/miguelgrinberg/microdot/commit/f317b15bdbf924007e5e3414e0c626baccc3ede6))
|
||||
- Catch SSL exceptions while writing the response [#206](https://github.com/miguelgrinberg/microdot/issues/206) ([commit](https://github.com/miguelgrinberg/microdot/commit/e7ee74d6bba74cfd89b9ddc38f28e02514eb1791))
|
||||
- Use `orjson` instead of `json` if available ([commit](https://github.com/miguelgrinberg/microdot/commit/086f2af3deab86d4340f3f1feb9e019de59f351d))
|
||||
- Addressed typing warnings from pyright ([commit](https://github.com/miguelgrinberg/microdot/commit/b6f232db1125045d79c444c736a2ae59c5501fdd))
|
||||
|
||||
**Release 2.2.0** - 2025-03-22
|
||||
|
||||
- Support for `multipart/form-data` requests [#287](https://github.com/miguelgrinberg/microdot/issues/287) ([commit](https://github.com/miguelgrinberg/microdot/commit/11a91a60350518e426b557fae8dffe75912f8823))
|
||||
- Support custom path components in URLs ([commit #1](https://github.com/miguelgrinberg/microdot/commit/c92b5ae28222af5a1094f5d2f70a45d4d17653d5) [commit #2](https://github.com/miguelgrinberg/microdot/commit/aa76e6378b37faab52008a8aab8db75f81b29323))
|
||||
- Expose the Jinja environment as `Template.jinja_env` ([commit](https://github.com/miguelgrinberg/microdot/commit/953dd9432122defe943f0637bbe7e01f2fc7743f))
|
||||
- Simplified urldecode logic ([commit #1](https://github.com/miguelgrinberg/microdot/commit/3bc31f10b2b2d4460c62366013278d87665f0f97) [commit #2](https://github.com/miguelgrinberg/microdot/commit/d203df75fef32c7cc0fe7cc6525e77522b37a289))
|
||||
- Additional urldecode tests ([commit](https://github.com/miguelgrinberg/microdot/commit/99f65c0198590c0dfb402c24685b6f8dfba1935d))
|
||||
- Documentation improvements ([commit](https://github.com/miguelgrinberg/microdot/commit/c6b99b6d8117d4e40e16d5b953dbf4deb023d24d))
|
||||
- Update micropython version used in tests to 1.24.1 ([commit](https://github.com/miguelgrinberg/microdot/commit/4cc2e95338a7de3b03742389004147ee21285621))
|
||||
|
||||
**Release 2.1.0** - 2025-02-04
|
||||
|
||||
- User login support ([commit](https://github.com/miguelgrinberg/microdot/commit/d807011ad006e53e70c4594d7eac04d03bb08681))
|
||||
- Basic and token authentication support ([commit](https://github.com/miguelgrinberg/microdot/commit/675c9787974da926af446974cd96ef224e0ee27f))
|
||||
- Added `local` argument to the `app.mount()` method, to define sub-application specific before and after request handlers ([commit](https://github.com/miguelgrinberg/microdot/commit/fd7931e1aec173c60f81dad18c1a102ed8f0e081))
|
||||
- Added `Request.url_prefix`, `Request.subapp` and local mounts ([commit](https://github.com/miguelgrinberg/microdot/commit/fd7931e1aec173c60f81dad18c1a102ed8f0e081))
|
||||
- Added a front end to the SSE example [#281](https://github.com/miguelgrinberg/microdot/issues/281) ([commit](https://github.com/miguelgrinberg/microdot/commit/d487a73c1ea5b3467e23907618b348ca52e0235c)) (thanks **Maxi**!)
|
||||
- Additional ``app.mount()`` unit tests ([commit](https://github.com/miguelgrinberg/microdot/commit/cd87abba30206ec6d3928e0aabacb2fccf7baf70))
|
||||
|
||||
**Release 2.0.7** - 2024-11-10
|
||||
|
||||
- Accept responses with just a status code [#263](https://github.com/miguelgrinberg/microdot/issues/263) ([commit #1](https://github.com/miguelgrinberg/microdot/commit/4eac013087f807cafa244b8a6b7b0ed4c82ff150) [commit #2](https://github.com/miguelgrinberg/microdot/commit/c46e4291061046f1be13f300dd08645b71c16635))
|
||||
- Fixed compressed file content-type assignment [#251](https://github.com/miguelgrinberg/microdot/issues/251) ([commit](https://github.com/miguelgrinberg/microdot/commit/482ab6d5ca068d71ea6301f45918946161e9fcc1)) (thanks **Lukas Kremla**!)
|
||||
- Better documentation for start_server[#252](https://github.com/miguelgrinberg/microdot/issues/252) ([commit](https://github.com/miguelgrinberg/microdot/commit/0a021462e0c42c249d587a2d600f5a21a408adfc))
|
||||
- Fix URLs in documentation [#253](https://github.com/miguelgrinberg/microdot/issues/253) ([commit](https://github.com/miguelgrinberg/microdot/commit/5e5fc5e93e11cbf6e3dc8036494e8732d1815d3e)) (thanks **Stanislav Garanzha**!)
|
||||
|
||||
**Release 2.0.6** - 2024-06-18
|
||||
|
||||
- Add event ID to the SSE implementation [#213](https://github.com/miguelgrinberg/microdot/issues/213) ([commit](https://github.com/miguelgrinberg/microdot/commit/904d5fcaa2d19d939a719b8e68c4dee3eb470739)) (thanks **Hamsanger**!)
|
||||
- Configurable session cookie options [#242](https://github.com/miguelgrinberg/microdot/issues/242) ([commit](https://github.com/miguelgrinberg/microdot/commit/0151611fc84fec450820d673f4c4d70c32c990a7))
|
||||
- Improved cookie support in the test client ([commit](https://github.com/miguelgrinberg/microdot/commit/4cb155ee411dc2d9c9f15714cb32b25ba79b156a))
|
||||
- Cookie path support in session extension and test client ([commit](https://github.com/miguelgrinberg/microdot/commit/6ffb8a8fe920111c4d8c16e98715a0d5ee2d1da3))
|
||||
- Refactor `Session` class to make it more reusable ([commit](https://github.com/miguelgrinberg/microdot/commit/dea79c5ce224dec7858ffef45a42bed442fd3a5a))
|
||||
- Use `@functools.wraps` on decorated functions ([commit](https://github.com/miguelgrinberg/microdot/commit/f6876c0d154adcae96098405fb6a1fdf1ea4ec28))
|
||||
- Removed outdated import from documentation [#216](https://github.com/miguelgrinberg/microdot/issues/216) ([commit](https://github.com/miguelgrinberg/microdot/commit/6b1fd6191702e7a9ad934fddfcdd0a3cebea7c94)) (thanks **Carlo Colombo**!)
|
||||
- Add roadmap details to readme ([commit](https://github.com/miguelgrinberg/microdot/commit/a0ea439def238084c4d68309c0992b66ffd28ad6))
|
||||
|
||||
**Release 2.0.5** - 2024-03-09
|
||||
|
||||
- Correct handling of 0 as an integer argument (regression from #207) [#212](https://github.com/miguelgrinberg/microdot/issues/212) ([commit](https://github.com/miguelgrinberg/microdot/commit/d0a4cf8fa7dfb1da7466157b18d3329a8cf9a5df))
|
||||
|
||||
**Release 2.0.4** - 2024-02-20
|
||||
|
||||
- Do not use regexes for parsing simple URLs [#207](https://github.com/miguelgrinberg/microdot/issues/207) ([commit #1](https://github.com/miguelgrinberg/microdot/commit/38262c56d34784401659639b482a4a1224e1e59a) [commit #2](https://github.com/miguelgrinberg/microdot/commit/f6cba2c0f7e18e2f32b5adb779fb037b6c473eab))
|
||||
- Added documentation on using alternative uTemplate loaders ([commit](https://github.com/miguelgrinberg/microdot/commit/bf519478cbc6e296785241cd7d01edb23c317cd3))
|
||||
- Added CircuitPython builds ([commit](https://github.com/miguelgrinberg/microdot/commit/e44c271bae88f4327d3eda16d8780ac264d1ebab))
|
||||
|
||||
**Release 2.0.3** - 2024-01-07
|
||||
|
||||
- Add a limit to WebSocket message size [#193](https://github.com/miguelgrinberg/microdot/issues/193) ([commit](https://github.com/miguelgrinberg/microdot/commit/5d188e8c0ddef6ce633ca702dbdd4a90f2799597))
|
||||
|
||||
30
README.md
30
README.md
@@ -19,23 +19,25 @@ async def index(request):
|
||||
app.run()
|
||||
```
|
||||
|
||||
## Migrating to Microdot 2
|
||||
|
||||
Version 2 of Microdot incorporates feedback received from users of earlier
|
||||
releases, and attempts to improve and correct some design decisions that have
|
||||
proven to be problematic.
|
||||
|
||||
For this reason most applications built for earlier versions will need to be
|
||||
updated to work correctly with Microdot 2. The
|
||||
[Migration Guide](https://microdot.readthedocs.io/en/stable/migrating.html)
|
||||
describes the backwards incompatible changes that were made.
|
||||
|
||||
## Resources
|
||||
|
||||
- [Change Log](https://github.com/miguelgrinberg/microdot/blob/main/CHANGES.md)
|
||||
- Documentation
|
||||
- [Stable](https://microdot.readthedocs.io/en/stable/)
|
||||
- [Latest](https://microdot.readthedocs.io/en/latest/)
|
||||
- Still using version 1?
|
||||
- [Stable (v2)](https://microdot.readthedocs.io/en/stable/)
|
||||
- Legacy (v1)
|
||||
- [Code](https://github.com/miguelgrinberg/microdot/tree/v1)
|
||||
- [Documentation](https://microdot.readthedocs.io/en/v1/)
|
||||
- [Change Log](https://github.com/miguelgrinberg/microdot/blob/main/CHANGES.md)
|
||||
|
||||
## Roadmap
|
||||
|
||||
The following features are planned for future releases of Microdot, both for
|
||||
MicroPython and CPython:
|
||||
|
||||
- Authentication support, similar to [Flask-Login](https://github.com/maxcountryman/flask-login) for Flask (**Added in version 2.1**)
|
||||
- Support for forms encoded in `multipart/form-data` format (**Added in version 2.2**)
|
||||
- CSRF protection extension (**Added in version 2.5**)
|
||||
- Pub/sub mini-framework for WebSocket and SSE
|
||||
- OpenAPI integration, similar to [APIFairy](https://github.com/miguelgrinberg/apifairy) for Flask
|
||||
|
||||
Do you have other ideas to propose? Let's [discuss them](https://github.com/:miguelgrinberg/microdot/discussions/new?category=ideas)!
|
||||
|
||||
BIN
bin/circuitpython
Executable file
BIN
bin/circuitpython
Executable file
Binary file not shown.
BIN
bin/micropython
BIN
bin/micropython
Binary file not shown.
71
docs/api.rst
71
docs/api.rst
@@ -1,71 +0,0 @@
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Core API
|
||||
--------
|
||||
|
||||
.. autoclass:: microdot.Microdot
|
||||
:members:
|
||||
|
||||
.. autoclass:: microdot.Request
|
||||
:members:
|
||||
|
||||
.. autoclass:: microdot.Response
|
||||
:members:
|
||||
|
||||
|
||||
WebSocket
|
||||
---------
|
||||
|
||||
.. automodule:: microdot.websocket
|
||||
:members:
|
||||
|
||||
Server-Sent Events (SSE)
|
||||
------------------------
|
||||
|
||||
.. automodule:: microdot.sse
|
||||
:members:
|
||||
|
||||
Templates (uTemplate)
|
||||
---------------------
|
||||
|
||||
.. automodule:: microdot.utemplate
|
||||
:members:
|
||||
|
||||
Templates (Jinja)
|
||||
-----------------
|
||||
|
||||
.. automodule:: microdot.jinja
|
||||
:members:
|
||||
|
||||
User Sessions
|
||||
-------------
|
||||
|
||||
.. automodule:: microdot.session
|
||||
:members:
|
||||
|
||||
Cross-Origin Resource Sharing (CORS)
|
||||
------------------------------------
|
||||
|
||||
.. automodule:: microdot.cors
|
||||
:members:
|
||||
|
||||
Test Client
|
||||
-----------
|
||||
|
||||
.. automodule:: microdot.test_client
|
||||
:members:
|
||||
|
||||
ASGI
|
||||
----
|
||||
|
||||
.. autoclass:: microdot.asgi.Microdot
|
||||
:members:
|
||||
:exclude-members: shutdown, run
|
||||
|
||||
WSGI
|
||||
----
|
||||
|
||||
.. autoclass:: microdot.wsgi.Microdot
|
||||
:members:
|
||||
:exclude-members: shutdown, run
|
||||
6
docs/api/asgi.rst
Normal file
6
docs/api/asgi.rst
Normal file
@@ -0,0 +1,6 @@
|
||||
ASGI
|
||||
----
|
||||
|
||||
.. autoclass:: microdot.asgi.Microdot
|
||||
:members:
|
||||
:exclude-members: shutdown, run
|
||||
7
docs/api/auth.rst
Normal file
7
docs/api/auth.rst
Normal file
@@ -0,0 +1,7 @@
|
||||
Authentication
|
||||
--------------
|
||||
|
||||
.. automodule:: microdot.auth
|
||||
:inherited-members:
|
||||
:special-members: __call__
|
||||
:members:
|
||||
5
docs/api/cors.rst
Normal file
5
docs/api/cors.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Cross-Origin Resource Sharing (CORS)
|
||||
------------------------------------
|
||||
|
||||
.. automodule:: microdot.cors
|
||||
:members:
|
||||
5
docs/api/csrf.rst
Normal file
5
docs/api/csrf.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Cross-Site Request Forgery (CSRF) Protection
|
||||
--------------------------------------------
|
||||
|
||||
.. automodule:: microdot.csrf
|
||||
:members:
|
||||
21
docs/api/index.rst
Normal file
21
docs/api/index.rst
Normal file
@@ -0,0 +1,21 @@
|
||||
API Reference
|
||||
=============
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
microdot
|
||||
multipart
|
||||
websocket
|
||||
sse
|
||||
utemplate
|
||||
jinja
|
||||
sessions
|
||||
auth
|
||||
login
|
||||
cors
|
||||
csrf
|
||||
test_client
|
||||
asgi
|
||||
wsgi
|
||||
|
||||
5
docs/api/jinja.rst
Normal file
5
docs/api/jinja.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Templates (Jinja)
|
||||
-----------------
|
||||
|
||||
.. automodule:: microdot.jinja
|
||||
:members:
|
||||
7
docs/api/login.rst
Normal file
7
docs/api/login.rst
Normal file
@@ -0,0 +1,7 @@
|
||||
User Logins
|
||||
-----------
|
||||
|
||||
.. automodule:: microdot.login
|
||||
:inherited-members:
|
||||
:special-members: __call__
|
||||
:members:
|
||||
14
docs/api/microdot.rst
Normal file
14
docs/api/microdot.rst
Normal file
@@ -0,0 +1,14 @@
|
||||
Core API
|
||||
--------
|
||||
|
||||
.. autoclass:: microdot.Microdot
|
||||
:members:
|
||||
|
||||
.. autoclass:: microdot.Request
|
||||
:members:
|
||||
|
||||
.. autoclass:: microdot.Response
|
||||
:members:
|
||||
|
||||
.. autoclass:: microdot.URLPattern
|
||||
:members:
|
||||
5
docs/api/multipart.rst
Normal file
5
docs/api/multipart.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Multipart Forms
|
||||
---------------
|
||||
|
||||
.. automodule:: microdot.multipart
|
||||
:members:
|
||||
5
docs/api/sessions.rst
Normal file
5
docs/api/sessions.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
User Sessions
|
||||
-------------
|
||||
|
||||
.. automodule:: microdot.session
|
||||
:members:
|
||||
5
docs/api/sse.rst
Normal file
5
docs/api/sse.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Server-Sent Events (SSE)
|
||||
------------------------
|
||||
|
||||
.. automodule:: microdot.sse
|
||||
:members:
|
||||
5
docs/api/test_client.rst
Normal file
5
docs/api/test_client.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Test Client
|
||||
-----------
|
||||
|
||||
.. automodule:: microdot.test_client
|
||||
:members:
|
||||
5
docs/api/utemplate.rst
Normal file
5
docs/api/utemplate.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
Templates (uTemplate)
|
||||
---------------------
|
||||
|
||||
.. automodule:: microdot.utemplate
|
||||
:members:
|
||||
5
docs/api/websocket.rst
Normal file
5
docs/api/websocket.rst
Normal file
@@ -0,0 +1,5 @@
|
||||
WebSocket
|
||||
---------
|
||||
|
||||
.. automodule:: microdot.websocket
|
||||
:members:
|
||||
6
docs/api/wsgi.rst
Normal file
6
docs/api/wsgi.rst
Normal file
@@ -0,0 +1,6 @@
|
||||
WSGI
|
||||
----
|
||||
|
||||
.. autoclass:: microdot.wsgi.Microdot
|
||||
:members:
|
||||
:exclude-members: shutdown, run
|
||||
@@ -46,7 +46,8 @@ exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
#
|
||||
html_theme = 'alabaster'
|
||||
html_theme = 'furo'
|
||||
html_title = 'Microdot'
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
@@ -58,12 +59,6 @@ html_css_files = [
|
||||
]
|
||||
|
||||
html_theme_options = {
|
||||
'github_user': 'miguelgrinberg',
|
||||
'github_repo': 'microdot',
|
||||
'github_banner': True,
|
||||
'github_button': True,
|
||||
'github_type': 'star',
|
||||
'fixed_sidebar': True,
|
||||
}
|
||||
|
||||
autodoc_default_options = {
|
||||
|
||||
7
docs/contributing.rst
Normal file
7
docs/contributing.rst
Normal file
@@ -0,0 +1,7 @@
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Thank you for your interest in Microdot!
|
||||
|
||||
Please visit the `GitHub repository <https://github.com/miguelgrinberg/microdot>`_
|
||||
to learn about the project and find open issues and pull requests.
|
||||
@@ -1,437 +0,0 @@
|
||||
Core Extensions
|
||||
---------------
|
||||
|
||||
Microdot is a highly extensible web application framework. The extensions
|
||||
described in this section are maintained as part of the Microdot project in
|
||||
the same source code repository.
|
||||
|
||||
WebSocket Support
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `websocket.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/websocket.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `echo.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo.py>`_
|
||||
|
||||
The WebSocket extension gives the application the ability to handle WebSocket
|
||||
requests. The :func:`with_websocket <microdot.websocket.with_websocket>`
|
||||
decorator is used to mark a route handler as a WebSocket handler. Decorated
|
||||
routes receive a WebSocket object as a second argument. The WebSocket object
|
||||
provides ``send()`` and ``receive()`` asynchronous methods to send and receive
|
||||
messages respectively.
|
||||
|
||||
Example::
|
||||
|
||||
@app.route('/echo')
|
||||
@with_websocket
|
||||
async def echo(request, ws):
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
|
||||
Server-Sent Events Support
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `sse.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/sse.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `counter.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/sse/counter.py>`_
|
||||
|
||||
The Server-Sent Events (SSE) extension simplifies the creation of a streaming
|
||||
endpoint that follows the SSE web standard. The :func:`with_sse <microdot.sse.with_sse>`
|
||||
decorator is used to mark a route as an SSE handler. Decorated routes receive
|
||||
an SSE object as second argument. The SSE object provides a ``send()``
|
||||
asynchronous method to send an event to the client.
|
||||
|
||||
Example::
|
||||
|
||||
@app.route('/events')
|
||||
@with_sse
|
||||
async def events(request, sse):
|
||||
for i in range(10):
|
||||
await asyncio.sleep(1)
|
||||
await sse.send({'counter': i}) # unnamed event
|
||||
await sse.send('end', event='comment') # named event
|
||||
|
||||
.. note::
|
||||
The SSE protocol is unidirectional, so there is no ``receive()`` method in
|
||||
the SSE object. For bidirectional communication with the client, use the
|
||||
WebSocket extension.
|
||||
|
||||
Rendering Templates
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Many web applications use HTML templates for rendering content to clients.
|
||||
Microdot includes extensions to render templates with the
|
||||
`utemplate <https://github.com/pfalcon/utemplate>`_ package on CPython and
|
||||
MicroPython, and with `Jinja <https://jinja.palletsprojects.com/>`_ only on
|
||||
CPython.
|
||||
|
||||
Using the uTemplate Engine
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `utemplate.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/utemplate.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | `utemplate <https://github.com/pfalcon/utemplate/tree/master/utemplate>`_
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello.py>`_
|
||||
|
||||
The :class:`Template <microdot.utemplate.Template>` class is used to load a
|
||||
template. The argument is the template filename, relative to the templates
|
||||
directory, which is *templates* by default.
|
||||
|
||||
The ``Template`` object has a :func:`render() <microdot.utemplate.Template.render>`
|
||||
method that renders the template to a string. This method receives any
|
||||
arguments that are used by the template.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.utemplate import Template
|
||||
|
||||
@app.get('/')
|
||||
async def index(req):
|
||||
return Template('index.html').render()
|
||||
|
||||
The ``Template`` object also has a :func:`generate() <microdot.utemplate.Template.generate>`
|
||||
method, which returns a generator instead of a string. The
|
||||
:func:`render_async() <microdot.utemplate.Template.render_async>` and
|
||||
:func:`generate_async() <microdot.utemplate.Template.generate_async>` methods
|
||||
are the asynchronous versions of these two methods.
|
||||
|
||||
The default location from where templates are loaded is the *templates*
|
||||
subdirectory. This location can be changed with the
|
||||
:func:`Template.initialize <microdot.utemplate.Template.initialize>` class
|
||||
method::
|
||||
|
||||
Template.initialize('my_templates')
|
||||
|
||||
Using the Jinja Engine
|
||||
^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython only
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `jinja.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/jinja.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | `Jinja2 <https://jinja.palletsprojects.com/>`_
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello.py>`_
|
||||
|
||||
The :class:`Template <microdot.jinja.Template>` class is used to load a
|
||||
template. The argument is the template filename, relative to the templates
|
||||
directory, which is *templates* by default.
|
||||
|
||||
The ``Template`` object has a :func:`render() <microdot.jinja.Template.render>`
|
||||
method that renders the template to a string. This method receives any
|
||||
arguments that are used by the template.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.jinja import Template
|
||||
|
||||
@app.get('/')
|
||||
async def index(req):
|
||||
return Template('index.html').render()
|
||||
|
||||
The ``Template`` object also has a :func:`generate() <microdot.jinja.Template.generate>`
|
||||
method, which returns a generator instead of a string.
|
||||
|
||||
The default location from where templates are loaded is the *templates*
|
||||
subdirectory. This location can be changed with the
|
||||
:func:`Template.initialize <microdot.jinja.Template.initialize>` class method::
|
||||
|
||||
Template.initialize('my_templates')
|
||||
|
||||
The ``initialize()`` method also accepts ``enable_async`` argument, which
|
||||
can be set to ``True`` if asynchronous rendering of templates is desired. If
|
||||
this option is enabled, then the
|
||||
:func:`render_async() <microdot.jinja.Template.render_async>` and
|
||||
:func:`generate_async() <microdot.jinja.Template.generate_async>` methods
|
||||
must be used.
|
||||
|
||||
.. note::
|
||||
The Jinja extension is not compatible with MicroPython.
|
||||
|
||||
Maintaining Secure User Sessions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `session.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/session.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | CPython: `PyJWT <https://pyjwt.readthedocs.io/>`_
|
||||
| MicroPython: `jwt.py <https://github.com/micropython/micropython-lib/blob/master/python-ecosys/pyjwt/jwt.py>`_,
|
||||
`hmac.py <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/hmac/hmac.py>`_
|
||||
|
||||
* - Examples
|
||||
- | `login.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/sessions/login.py>`_
|
||||
|
||||
The session extension provides a secure way for the application to maintain
|
||||
user sessions. The session data is stored as a signed cookie in the client's
|
||||
browser, in `JSON Web Token (JWT) <https://en.wikipedia.org/wiki/JSON_Web_Token>`_
|
||||
format.
|
||||
|
||||
To work with user sessions, the application first must configure a secret key
|
||||
that will be used to sign the session cookies. It is very important that this
|
||||
key is kept secret, as its name implies. An attacker who is in possession of
|
||||
this key can generate valid user session cookies with any contents.
|
||||
|
||||
To initialize the session extension and configure the secret key, create a
|
||||
:class:`Session <microdot.session.Session>` object::
|
||||
|
||||
Session(app, secret_key='top-secret')
|
||||
|
||||
The :func:`with_session <microdot.session.with_session>` decorator is the
|
||||
most convenient way to retrieve the session at the start of a request::
|
||||
|
||||
from microdot import Microdot, redirect
|
||||
from microdot.session import Session, with_session
|
||||
|
||||
app = Microdot()
|
||||
Session(app, secret_key='top-secret')
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
@with_session
|
||||
async def index(req, session):
|
||||
username = session.get('username')
|
||||
if req.method == 'POST':
|
||||
username = req.form.get('username')
|
||||
session['username'] = username
|
||||
session.save()
|
||||
return redirect('/')
|
||||
if username is None:
|
||||
return 'Not logged in'
|
||||
else:
|
||||
return 'Logged in as ' + username
|
||||
|
||||
@app.post('/logout')
|
||||
@with_session
|
||||
async def logout(req, session):
|
||||
session.delete()
|
||||
return redirect('/')
|
||||
|
||||
The :func:`save() <microdot.session.SessionDict.save>` and
|
||||
:func:`delete() <microdot.session.SessionDict.delete>` methods are used to update
|
||||
and destroy the user session respectively.
|
||||
|
||||
Cross-Origin Resource Sharing (CORS)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `cors.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/cors.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `cors.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/cors/cors.py>`_
|
||||
|
||||
The CORS extension provides support for `Cross-Origin Resource Sharing
|
||||
(CORS) <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_. CORS is a
|
||||
mechanism that allows web applications running on different origins to access
|
||||
resources from each other. For example, a web application running on
|
||||
``https://example.com`` can access resources from ``https://api.example.com``.
|
||||
|
||||
To enable CORS support, create an instance of the
|
||||
:class:`CORS <microdot.cors.CORS>` class and configure the desired options.
|
||||
Example::
|
||||
|
||||
from microdot import Microdot
|
||||
from microdot.cors import CORS
|
||||
|
||||
app = Microdot()
|
||||
cors = CORS(app, allowed_origins=['https://example.com'],
|
||||
allow_credentials=True)
|
||||
|
||||
Testing with the Test Client
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `test_client.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/test_client.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
The Microdot Test Client is a utility class that can be used in tests to send
|
||||
requests into the application without having to start a web server.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot import Microdot
|
||||
from microdot.test_client import TestClient
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
def index(req):
|
||||
return 'Hello, World!'
|
||||
|
||||
async def test_app():
|
||||
client = TestClient(app)
|
||||
response = await client.get('/')
|
||||
assert response.text == 'Hello, World!'
|
||||
|
||||
See the documentation for the :class:`TestClient <microdot.test_client.TestClient>`
|
||||
class for more details.
|
||||
|
||||
Deploying on a Production Web Server
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``Microdot`` class creates its own simple web server. This is enough for an
|
||||
application deployed with MicroPython, but when using CPython it may be useful
|
||||
to use a separate, battle-tested web server. To address this need, Microdot
|
||||
provides extensions that implement the ASGI and WSGI protocols.
|
||||
|
||||
Using an ASGI Web Server
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython only
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `asgi.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/asgi.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | An ASGI web server, such as `Uvicorn <https://uvicorn.org/>`_.
|
||||
|
||||
* - Examples
|
||||
- | `hello_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_asgi.py>`_
|
||||
| `hello_asgi.py (uTemplate) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello_asgi.py>`_
|
||||
| `hello_asgi.py (Jinja) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello_asgi.py>`_
|
||||
| `echo_asgi.py (WebSocket) <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_asgi.py>`_
|
||||
|
||||
The ``asgi`` module provides an extended ``Microdot`` class that
|
||||
implements the ASGI protocol and can be used with a compliant ASGI server such
|
||||
as `Uvicorn <https://www.uvicorn.org/>`_.
|
||||
|
||||
To use an ASGI web server, the application must import the
|
||||
:class:`Microdot <microdot.asgi.Microdot>` class from the ``asgi`` module::
|
||||
|
||||
from microdot.asgi import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
async def index(req):
|
||||
return 'Hello, World!'
|
||||
|
||||
The ``app`` application instance created from this class can be used as the
|
||||
ASGI callable with any complaint ASGI web server. If the above example
|
||||
application was stored in a file called *test.py*, then the following command
|
||||
runs the web application using the Uvicorn web server::
|
||||
|
||||
uvicorn test:app
|
||||
|
||||
When using the ASGI support, the ``scope`` dictionary provided by the web
|
||||
server is available to request handlers as ``request.asgi_scope``.
|
||||
|
||||
Using a WSGI Web Server
|
||||
^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython only
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `wsgi.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/wsgi.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | A WSGI web server, such as `Gunicorn <https://gunicorn.org/>`_.
|
||||
|
||||
* - Examples
|
||||
- | `hello_wsgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_wsgi.py>`_
|
||||
| `hello_wsgi.py (uTemplate) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello_wsgi.py>`_
|
||||
| `hello_wsgi.py (Jinja) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello_wsgi.py>`_
|
||||
| `echo_wsgi.py (WebSocket) <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_wsgi.py>`_
|
||||
|
||||
|
||||
The ``wsgi`` module provides an extended ``Microdot`` class that implements the
|
||||
WSGI protocol and can be used with a compliant WSGI web server such as
|
||||
`Gunicorn <https://gunicorn.org/>`_ or
|
||||
`uWSGI <https://uwsgi-docs.readthedocs.io/en/latest/>`_.
|
||||
|
||||
To use a WSGI web server, the application must import the
|
||||
:class:`Microdot <microdot.wsgi.Microdot>` class from the ``wsgi`` module::
|
||||
|
||||
from microdot.wsgi import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
def index(req):
|
||||
return 'Hello, World!'
|
||||
|
||||
The ``app`` application instance created from this class can be used as a WSGI
|
||||
callbable with any complaint WSGI web server. If the above application
|
||||
was stored in a file called *test.py*, then the following command runs the
|
||||
web application using the Gunicorn web server::
|
||||
|
||||
gunicorn test:app
|
||||
|
||||
When using the WSGI support, the ``environ`` dictionary provided by the web
|
||||
server is available to request handlers as ``request.environ``.
|
||||
|
||||
.. note::
|
||||
In spite of WSGI being a synchronous protocol, the Microdot application
|
||||
internally runs under an asyncio event loop. For that reason, the
|
||||
recommendation to prefer ``async def`` handlers over ``def`` still applies
|
||||
under WSGI. Consult the :ref:`Concurrency` section for a discussion of how
|
||||
the two types of functions are handled by Microdot.
|
||||
112
docs/extensions/auth.rst
Normal file
112
docs/extensions/auth.rst
Normal file
@@ -0,0 +1,112 @@
|
||||
Authentication
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `auth.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/auth.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `basic_auth.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/auth/basic_auth.py>`_
|
||||
| `token_auth.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/auth/token_auth.py>`_
|
||||
|
||||
The authentication extension provides helper classes for two commonly used
|
||||
authentication patterns, described below.
|
||||
|
||||
Basic Authentication
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
`Basic Authentication <https://en.wikipedia.org/wiki/Basic_access_authentication>`_
|
||||
is a method of authentication that is part of the HTTP specification. It allows
|
||||
clients to authenticate to a server using a username and a password. Web
|
||||
browsers have native support for Basic Authentication and will automatically
|
||||
prompt the user for a username and a password when a protected resource is
|
||||
accessed.
|
||||
|
||||
To use Basic Authentication, create an instance of the :class:`BasicAuth <microdot.auth.BasicAuth>`
|
||||
class::
|
||||
|
||||
from microdot.auth import BasicAuth
|
||||
|
||||
auth = BasicAuth(app)
|
||||
|
||||
Next, create an authentication function. The function must accept a request
|
||||
object and a username and password pair provided by the user. If the
|
||||
credentials are valid, the function must return an object that represents the
|
||||
user. If the authentication function cannot validate the user provided
|
||||
credentials it must return ``None``. Decorate the function with
|
||||
``@auth.authenticate``::
|
||||
|
||||
@auth.authenticate
|
||||
async def verify_user(request, username, password):
|
||||
user = await load_user_from_database(username)
|
||||
if user and user.verify_password(password):
|
||||
return user
|
||||
|
||||
To protect a route with authentication, add the ``auth`` instance as a
|
||||
decorator::
|
||||
|
||||
@app.route('/')
|
||||
@auth
|
||||
async def index(request):
|
||||
return f'Hello, {request.g.current_user}!'
|
||||
|
||||
While running an authenticated request, the user object returned by the
|
||||
authenticaction function is accessible as ``request.g.current_user``.
|
||||
|
||||
If an endpoint is intended to work with or without authentication, then it can
|
||||
be protected with the ``auth.optional`` decorator::
|
||||
|
||||
@app.route('/')
|
||||
@auth.optional
|
||||
async def index(request):
|
||||
if request.g.current_user:
|
||||
return f'Hello, {request.g.current_user}!'
|
||||
else:
|
||||
return 'Hello, anonymous user!'
|
||||
|
||||
As shown in the example, a route can check ``request.g.current_user`` to
|
||||
determine if the user is authenticated or not.
|
||||
|
||||
Token Authentication
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
To set up token authentication, create an instance of
|
||||
:class:`TokenAuth <microdot.auth.TokenAuth>`::
|
||||
|
||||
from microdot.auth import TokenAuth
|
||||
|
||||
auth = TokenAuth()
|
||||
|
||||
Then add a function that verifies the token and returns the user it belongs to,
|
||||
or ``None`` if the token is invalid or expired::
|
||||
|
||||
@auth.authenticate
|
||||
async def verify_token(request, token):
|
||||
return load_user_from_token(token)
|
||||
|
||||
As with Basic authentication, the ``auth`` instance is used as a decorator to
|
||||
protect your routes, and the authenticated user is accessible from the request
|
||||
object as ``request.g.current_user``::
|
||||
|
||||
@app.route('/')
|
||||
@auth
|
||||
async def index(request):
|
||||
return f'Hello, {request.g.current_user}!'
|
||||
|
||||
Optional authentication can also be used with tokens::
|
||||
|
||||
@app.route('/')
|
||||
@auth.optional
|
||||
async def index(request):
|
||||
if request.g.current_user:
|
||||
return f'Hello, {request.g.current_user}!'
|
||||
else:
|
||||
return 'Hello, anonymous user!'
|
||||
34
docs/extensions/cors.rst
Normal file
34
docs/extensions/cors.rst
Normal file
@@ -0,0 +1,34 @@
|
||||
Cross-Origin Resource Sharing (CORS)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `cors.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/cors.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `app.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/cors/app.py>`_
|
||||
|
||||
The CORS extension provides support for `Cross-Origin Resource Sharing
|
||||
(CORS) <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_. CORS is a
|
||||
mechanism that allows web applications running on different origins to access
|
||||
resources from each other. For example, a web application running on
|
||||
``https://example.com`` can access resources from ``https://api.example.com``.
|
||||
|
||||
To enable CORS support, create an instance of the
|
||||
:class:`CORS <microdot.cors.CORS>` class and configure the desired options.
|
||||
Example::
|
||||
|
||||
from microdot import Microdot
|
||||
from microdot.cors import CORS
|
||||
|
||||
app = Microdot()
|
||||
cors = CORS(app, allowed_origins=['https://example.com'],
|
||||
allow_credentials=True)
|
||||
94
docs/extensions/csrf.rst
Normal file
94
docs/extensions/csrf.rst
Normal file
@@ -0,0 +1,94 @@
|
||||
Cross-Site Request Forgery (CSRF) Protection
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `csrf.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/csrf.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `app.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/csrf/app.py>`_
|
||||
|
||||
The CSRF extension provides protection against `Cross-Site Request Forgery
|
||||
(CSRF) <https://owasp.org/www-community/attacks/csrf>`_ attacks. This
|
||||
protection defends against attackers attempting to submit forms or other
|
||||
state-changing requests from their own site on behalf of unsuspecting victims,
|
||||
while taking advantage of the victims previously established sessions or
|
||||
cookies to impersonate them.
|
||||
|
||||
This extension checks the ``Sec-Fetch-Site`` header sent by all modern web
|
||||
browsers to achieve this protection. As a fallback mechanism for older browsers
|
||||
that do not support this header, this extension can be linked to the CORS
|
||||
extension to validate the ``Origin`` header. If you are interested in the
|
||||
details of this protection mechanism, it is described in the
|
||||
`OWASP CSRF Prevention Cheat Sheet <https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headers>`_
|
||||
page.
|
||||
|
||||
.. note::
|
||||
As of December 2025, OWASP considers the use of Fetch Metadata Headers for
|
||||
CSRF protection a
|
||||
`defense in depth <https://en.wikipedia.org/wiki/Defence_in_depth>`_
|
||||
technique that is insufficient on its own.
|
||||
|
||||
There is an interesting
|
||||
`discussion <https://github.com/OWASP/CheatSheetSeries/issues/1803>`_ on
|
||||
this topic in the OWASP GitHub repository where it appears to be agreement
|
||||
that this technique provides complete protection for the vast majority of
|
||||
use cases. If you are unsure if this method works for your use case, please
|
||||
read this discussion to have more context and make the right decision.
|
||||
|
||||
To enable CSRF protection, create an instance of the
|
||||
:class:`CSRF <microdot.csrf.CSRF>` class and configure the desired options.
|
||||
Example::
|
||||
|
||||
from microdot import Microdot
|
||||
from microdot.cors import CORS
|
||||
from microdot.csrf import CSRF
|
||||
|
||||
app = Microdot()
|
||||
cors = CORS(app, allowed_origins=['https://example.com'])
|
||||
csrf = CSRF(app, cors)
|
||||
|
||||
This will protect all routes that use a state-changing method (``POST``,
|
||||
``PUT``, ``PATCH`` or ``DELETE``) and will return a 403 status code response to
|
||||
any requests that fail the CSRF check.
|
||||
|
||||
If there are routes that need to be exempted from the CSRF check, they can be
|
||||
decorated with the :meth:`csrf.exempt <microdot.csrf.CSRF.exempt>` decorator::
|
||||
|
||||
@app.post('/webhook')
|
||||
@csrf.exempt
|
||||
async def webhook(request):
|
||||
# ...
|
||||
|
||||
For some applications it may be more convenient to have CSRF checks turned off
|
||||
by default, and only apply them to explicitly selected routes. In this case,
|
||||
pass ``protect_all=False`` when you construct the ``CSRF`` instance and use the
|
||||
:meth:`csrf.protect <microdot.csrf.CSRF.protect>` decorator::
|
||||
|
||||
csrf = CSRF(app, cors, protect_all=False)
|
||||
|
||||
@app.post('/submit-form')
|
||||
@csrf.protect
|
||||
async def submit_form(request):
|
||||
# ...
|
||||
|
||||
By default, requests coming from different subdomains are considered to be
|
||||
cross-site, and as such they will not pass the CSRF check. If you'd like
|
||||
subdomain requests to be considered safe, then set the
|
||||
``allow_subdomains=True`` option when you create the ``CSRF`` class.
|
||||
|
||||
.. note::
|
||||
This extension is designed to block requests issued by web browsers when
|
||||
they are found to be unsafe or unauthorized by the application owner. The
|
||||
method used to determine if a request should be allowed or not is based on
|
||||
the value of headers that are only sent by web browsers. Clients other than
|
||||
web browsers are not affected by this extension and can send requests
|
||||
freely.
|
||||
21
docs/extensions/index.rst
Normal file
21
docs/extensions/index.rst
Normal file
@@ -0,0 +1,21 @@
|
||||
Core Extensions
|
||||
---------------
|
||||
|
||||
Microdot is a highly extensible web application framework. The extensions
|
||||
described in this section are maintained as part of the Microdot project in
|
||||
the same source code repository.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
multipart
|
||||
websocket
|
||||
sse
|
||||
templates
|
||||
sessions
|
||||
auth
|
||||
login
|
||||
cors
|
||||
csrf
|
||||
test_client
|
||||
production
|
||||
85
docs/extensions/login.rst
Normal file
85
docs/extensions/login.rst
Normal file
@@ -0,0 +1,85 @@
|
||||
User Logins
|
||||
~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `login.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/auth.py>`_
|
||||
| `session.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/session.py>`_
|
||||
| `helpers.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/helpers.py>`_
|
||||
* - Required external dependencies
|
||||
- | CPython: `PyJWT <https://pyjwt.readthedocs.io/>`_
|
||||
| MicroPython: `jwt.py <https://github.com/micropython/micropython-lib/blob/master/python-ecosys/pyjwt/jwt.py>`_,
|
||||
`hmac.py <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/hmac/hmac.py>`_
|
||||
* - Examples
|
||||
- | `login.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/login/login.py>`_
|
||||
|
||||
The login extension provides user login functionality. The logged in state of
|
||||
the user is stored in the user session cookie, and an optional "remember me"
|
||||
cookie can also be added to keep the user logged in across browser sessions.
|
||||
|
||||
To use this extension, create instances of the
|
||||
:class:`Session <microdot.session.Session>` and :class:`Login <microdot.login.Login>`
|
||||
class::
|
||||
|
||||
Session(app, secret_key='top-secret!')
|
||||
login = Login()
|
||||
|
||||
The ``Login`` class accept an optional argument with the URL of the login page.
|
||||
The default for this URL is */login*.
|
||||
|
||||
The application must represent users as objects with an ``id`` attribute. A
|
||||
function decorated with ``@login.user_loader`` is used to load a user object::
|
||||
|
||||
@login.user_loader
|
||||
async def get_user(user_id):
|
||||
return database.get_user(user_id)
|
||||
|
||||
The application must implement the login form. At the point in which the user
|
||||
credentials have been received and verified, a call to the
|
||||
:func:`login_user() <microdot.login.Login.login_user>` function must be made to
|
||||
record the user in the user session::
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
async def login(request):
|
||||
# ...
|
||||
if user.check_password(password):
|
||||
return await login.login_user(request, user, remember=remember_me)
|
||||
return redirect('/login')
|
||||
|
||||
The optional ``remember`` argument is used to add a remember me cookie that
|
||||
will log the user in automatically in future sessions. A value of ``True`` will
|
||||
keep the log in active for 30 days. Alternatively, an integer number of days
|
||||
can be passed in this argument.
|
||||
|
||||
Any routes that require the user to be logged in must be decorated with
|
||||
:func:`@login <microdot.login.Login.__call__>`::
|
||||
|
||||
@app.route('/')
|
||||
@login
|
||||
async def index(request):
|
||||
# ...
|
||||
|
||||
Routes that are of a sensitive nature can be decorated with
|
||||
:func:`@login.fresh <microdot.login.Login.fresh>`
|
||||
instead. This decorator requires that the user has logged in during the current
|
||||
session, and will ask the user to logged in again if the session was
|
||||
authenticated through a remember me cookie::
|
||||
|
||||
@app.get('/fresh')
|
||||
@login.fresh
|
||||
async def fresh(request):
|
||||
# ...
|
||||
|
||||
To log out a user, the :func:`logout_user() <microdot.auth.Login.logout_user>`
|
||||
is used::
|
||||
|
||||
@app.post('/logout')
|
||||
@login
|
||||
async def logout(request):
|
||||
await login.logout_user(request)
|
||||
return redirect('/')
|
||||
73
docs/extensions/multipart.rst
Normal file
73
docs/extensions/multipart.rst
Normal file
@@ -0,0 +1,73 @@
|
||||
Multipart Forms
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `multipart.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/multipart.py>`_
|
||||
| `helpers.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/helpers.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `formdata.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/uploads/formdata.py>`_
|
||||
|
||||
The multipart extension handles multipart forms, including those that have file
|
||||
uploads.
|
||||
|
||||
The :func:`with_form_data <microdot.multipart.with_form_data>` decorator
|
||||
provides the simplest way to work with these forms. With this decorator added
|
||||
to the route, whenever the client sends a multipart request the
|
||||
:attr:`request.form <microdot.Request.form>` and
|
||||
:attr:`request.files <microdot.Request.files>` properties are populated with
|
||||
the submitted data. For form fields the field values are always strings. For
|
||||
files, they are instances of the
|
||||
:class:`FileUpload <microdot.multipart.FileUpload>` class.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.multipart import with_form_data
|
||||
|
||||
@app.post('/upload')
|
||||
@with_form_data
|
||||
async def upload(request):
|
||||
print('form fields:', request.form)
|
||||
print('files:', request.files)
|
||||
|
||||
One disadvantage of the ``@with_form_data`` decorator is that it has to copy
|
||||
any uploaded files to memory or temporary disk files, depending on their size.
|
||||
The :attr:`FileUpload.max_memory_size <microdot.multipart.FileUpload.max_memory_size>`
|
||||
attribute can be used to control the cutoff size above which a file upload
|
||||
is transferred to a temporary file.
|
||||
|
||||
A more performant alternative to the ``@with_form_data`` decorator is the
|
||||
:class:`FormDataIter <microdot.multipart.FormDataIter>` class, which iterates
|
||||
over the form fields sequentially, giving the application the option to parse
|
||||
the form fields on the fly and decide what to copy and what to discard. When
|
||||
using ``FormDataIter`` the ``request.form`` and ``request.files`` attributes
|
||||
are not used.
|
||||
|
||||
Example::
|
||||
|
||||
|
||||
from microdot.multipart import FormDataIter
|
||||
|
||||
@app.post('/upload')
|
||||
async def upload(request):
|
||||
async for name, value in FormDataIter(request):
|
||||
print(name, value)
|
||||
|
||||
For fields that contain an uploaded file, the ``value`` returned by the
|
||||
iterator is the same ``FileUpload`` instance. The application can choose to
|
||||
save the file with the :meth:`save() <microdot.multipart.FileUpload.save>`
|
||||
method, or read it with the :meth:`read() <microdot.multipart.FileUpload.read>`
|
||||
method, optionally passing a size to read it in chunks. The
|
||||
:meth:`copy() <microdot.multipart.FileUpload.copy>` method is also available to
|
||||
apply the copying logic used by the ``@with_form_data`` decorator, which is
|
||||
inefficient but allows the file to be set aside to be processed later, after
|
||||
the remaining form fields.
|
||||
120
docs/extensions/production.rst
Normal file
120
docs/extensions/production.rst
Normal file
@@ -0,0 +1,120 @@
|
||||
Production Deployments
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``Microdot`` class creates its own simple web server. This is enough for an
|
||||
application deployed with MicroPython, but when using CPython it may be useful
|
||||
to use a separate, battle-tested web server. To address this need, Microdot
|
||||
provides extensions that implement the ASGI and WSGI protocols.
|
||||
|
||||
Using an ASGI Web Server
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython only
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `asgi.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/asgi.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | An ASGI web server, such as `Uvicorn <https://www.uvicorn.org/>`_.
|
||||
|
||||
* - Examples
|
||||
- | `hello_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_asgi.py>`_
|
||||
| `hello_asgi.py (uTemplate) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello_asgi.py>`_
|
||||
| `hello_asgi.py (Jinja) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello_asgi.py>`_
|
||||
| `echo_asgi.py (WebSocket) <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_asgi.py>`_
|
||||
|
||||
The ``asgi`` module provides an extended ``Microdot`` class that
|
||||
implements the ASGI protocol and can be used with a compliant ASGI server such
|
||||
as `Uvicorn <https://www.uvicorn.org/>`_.
|
||||
|
||||
To use an ASGI web server, the application must import the
|
||||
:class:`Microdot <microdot.asgi.Microdot>` class from the ``asgi`` module::
|
||||
|
||||
from microdot.asgi import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
async def index(req):
|
||||
return 'Hello, World!'
|
||||
|
||||
The ``app`` application instance created from this class can be used as the
|
||||
ASGI callable with any complaint ASGI web server. If the above example
|
||||
application was stored in a file called *test.py*, then the following command
|
||||
runs the web application using the Uvicorn web server::
|
||||
|
||||
uvicorn test:app
|
||||
|
||||
When using the ASGI support, the ``scope`` dictionary provided by the web
|
||||
server is available to request handlers as ``request.asgi_scope``.
|
||||
|
||||
The application instance can be initialized with ``lifespan_startup`` and
|
||||
``lifespan_shutdown`` arguments, which are invoked when the web server sends
|
||||
the ASGI lifespan signals with the ASGI scope as only argument::
|
||||
|
||||
async def startup(scope):
|
||||
pass
|
||||
|
||||
async def shutdown(scope):
|
||||
pass
|
||||
|
||||
app = Microdot(lifespan_startup=startup, lifespan_shutdown=shutdown)
|
||||
|
||||
Using a WSGI Web Server
|
||||
^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython only
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `wsgi.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/wsgi.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | A WSGI web server, such as `Gunicorn <https://gunicorn.org/>`_.
|
||||
|
||||
* - Examples
|
||||
- | `hello_wsgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_wsgi.py>`_
|
||||
| `hello_wsgi.py (uTemplate) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello_wsgi.py>`_
|
||||
| `hello_wsgi.py (Jinja) <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello_wsgi.py>`_
|
||||
| `echo_wsgi.py (WebSocket) <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_wsgi.py>`_
|
||||
|
||||
|
||||
The ``wsgi`` module provides an extended ``Microdot`` class that implements the
|
||||
WSGI protocol and can be used with a compliant WSGI web server such as
|
||||
`Gunicorn <https://gunicorn.org/>`_ or
|
||||
`uWSGI <https://uwsgi-docs.readthedocs.io/en/latest/>`_.
|
||||
|
||||
To use a WSGI web server, the application must import the
|
||||
:class:`Microdot <microdot.wsgi.Microdot>` class from the ``wsgi`` module::
|
||||
|
||||
from microdot.wsgi import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
def index(req):
|
||||
return 'Hello, World!'
|
||||
|
||||
The ``app`` application instance created from this class can be used as a WSGI
|
||||
callbable with any complaint WSGI web server. If the above application
|
||||
was stored in a file called *test.py*, then the following command runs the
|
||||
web application using the Gunicorn web server::
|
||||
|
||||
gunicorn test:app
|
||||
|
||||
When using the WSGI support, the ``environ`` dictionary provided by the web
|
||||
server is available to request handlers as ``request.environ``.
|
||||
|
||||
.. note::
|
||||
In spite of WSGI being a synchronous protocol, the Microdot application
|
||||
internally runs under an asyncio event loop. For that reason, the
|
||||
recommendation to prefer ``async def`` handlers over ``def`` still applies
|
||||
under WSGI. Consult the :ref:`Concurrency` section for a discussion of how
|
||||
the two types of functions are handled by Microdot.
|
||||
68
docs/extensions/sessions.rst
Normal file
68
docs/extensions/sessions.rst
Normal file
@@ -0,0 +1,68 @@
|
||||
Secure User Sessions
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `session.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/session.py>`_
|
||||
| `helpers.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/helpers.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | CPython: `PyJWT <https://pyjwt.readthedocs.io/>`_
|
||||
| MicroPython: `jwt.py <https://github.com/micropython/micropython-lib/blob/master/python-ecosys/pyjwt/jwt.py>`_,
|
||||
`hmac.py <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/hmac/hmac.py>`_
|
||||
|
||||
* - Examples
|
||||
- | `login.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/sessions/login.py>`_
|
||||
|
||||
The session extension provides a secure way for the application to maintain
|
||||
user sessions. The session data is stored as a signed cookie in the client's
|
||||
browser, in `JSON Web Token (JWT) <https://en.wikipedia.org/wiki/JSON_Web_Token>`_
|
||||
format.
|
||||
|
||||
To work with user sessions, the application first must configure a secret key
|
||||
that will be used to sign the session cookies. It is very important that this
|
||||
key is kept secret, as its name implies. An attacker who is in possession of
|
||||
this key can generate valid user session cookies with any contents.
|
||||
|
||||
To initialize the session extension and configure the secret key, create a
|
||||
:class:`Session <microdot.session.Session>` object::
|
||||
|
||||
Session(app, secret_key='top-secret')
|
||||
|
||||
The :func:`with_session <microdot.session.with_session>` decorator is the
|
||||
most convenient way to retrieve the session at the start of a request::
|
||||
|
||||
from microdot import Microdot, redirect
|
||||
from microdot.session import Session, with_session
|
||||
|
||||
app = Microdot()
|
||||
Session(app, secret_key='top-secret')
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
@with_session
|
||||
async def index(req, session):
|
||||
username = session.get('username')
|
||||
if req.method == 'POST':
|
||||
username = req.form.get('username')
|
||||
session['username'] = username
|
||||
session.save()
|
||||
return redirect('/')
|
||||
if username is None:
|
||||
return 'Not logged in'
|
||||
else:
|
||||
return 'Logged in as ' + username
|
||||
|
||||
@app.post('/logout')
|
||||
@with_session
|
||||
async def logout(req, session):
|
||||
session.delete()
|
||||
return redirect('/')
|
||||
|
||||
The :func:`save() <microdot.session.SessionDict.save>` and
|
||||
:func:`delete() <microdot.session.SessionDict.delete>` methods are used to update
|
||||
and destroy the user session respectively.
|
||||
60
docs/extensions/sse.rst
Normal file
60
docs/extensions/sse.rst
Normal file
@@ -0,0 +1,60 @@
|
||||
Server-Sent Events
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `sse.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/sse.py>`_
|
||||
| `helpers.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/helpers.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `counter.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/sse/counter.py>`_
|
||||
|
||||
The Server-Sent Events (SSE) extension simplifies the creation of a streaming
|
||||
endpoint that follows the SSE web standard. The :func:`with_sse <microdot.sse.with_sse>`
|
||||
decorator is used to mark a route as an SSE handler. Decorated routes receive
|
||||
an SSE object as second argument. The SSE object provides a ``send()``
|
||||
asynchronous method to send an event to the client.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.sse import with_sse
|
||||
|
||||
@app.route('/events')
|
||||
@with_sse
|
||||
async def events(request, sse):
|
||||
for i in range(10):
|
||||
await asyncio.sleep(1)
|
||||
await sse.send({'counter': i}) # unnamed event
|
||||
await sse.send('end', event='comment') # named event
|
||||
|
||||
To end the SSE connection, the route handler can exit, without returning
|
||||
anything, as shown in the above examples.
|
||||
|
||||
If the client ends the SSE connection from their side, the route function is
|
||||
cancelled. The route function can catch the ``CancelledError`` exception from
|
||||
asyncio to perform cleanup tasks::
|
||||
|
||||
@app.route('/events')
|
||||
@with_sse
|
||||
async def events(request, sse):
|
||||
try:
|
||||
i = 0
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
await sse.send({'counter': i})
|
||||
i += 1
|
||||
except asyncio.CancelledError:
|
||||
print('Client disconnected!')
|
||||
|
||||
.. note::
|
||||
The SSE protocol is unidirectional, so there is no ``receive()`` method in
|
||||
the SSE object. For bidirectional communication with the client, use the
|
||||
WebSocket extension.
|
||||
123
docs/extensions/templates.rst
Normal file
123
docs/extensions/templates.rst
Normal file
@@ -0,0 +1,123 @@
|
||||
Templates
|
||||
~~~~~~~~~
|
||||
|
||||
Many web applications use HTML templates for rendering content to clients.
|
||||
Microdot includes extensions to render templates with the
|
||||
`utemplate <https://github.com/pfalcon/utemplate>`_ package on CPython and
|
||||
MicroPython, and with `Jinja <https://jinja.palletsprojects.com/>`_ only on
|
||||
CPython.
|
||||
|
||||
Using the uTemplate Engine
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `utemplate.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/utemplate.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | `utemplate <https://github.com/pfalcon/utemplate/tree/master/utemplate>`_
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello.py>`_
|
||||
|
||||
The :class:`Template <microdot.utemplate.Template>` class is used to load a
|
||||
template. The argument is the template filename, relative to the templates
|
||||
directory, which is *templates* by default.
|
||||
|
||||
The ``Template`` object has a :func:`render() <microdot.utemplate.Template.render>`
|
||||
method that renders the template to a string. This method receives any
|
||||
arguments that are used by the template.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.utemplate import Template
|
||||
|
||||
@app.get('/')
|
||||
async def index(req):
|
||||
return Template('index.html').render()
|
||||
|
||||
The ``Template`` object also has a :func:`generate() <microdot.utemplate.Template.generate>`
|
||||
method, which returns a generator instead of a string. The
|
||||
:func:`render_async() <microdot.utemplate.Template.render_async>` and
|
||||
:func:`generate_async() <microdot.utemplate.Template.generate_async>` methods
|
||||
are the asynchronous versions of these two methods.
|
||||
|
||||
The default location from where templates are loaded is the *templates*
|
||||
subdirectory. This location can be changed with the
|
||||
:func:`Template.initialize <microdot.utemplate.Template.initialize>` class
|
||||
method::
|
||||
|
||||
Template.initialize('my_templates')
|
||||
|
||||
By default templates are automatically compiled the first time they are
|
||||
rendered, or when their last modified timestamp is more recent than the
|
||||
compiledo file's timestamp. This loading behavior can be changed by switching
|
||||
to a different template loader. For example, if the templates are pre-compiled,
|
||||
the timestamp check and compile steps can be removed by switching to the
|
||||
"compiled" template loader::
|
||||
|
||||
from utemplate import compiled
|
||||
from microdot.utemplate import Template
|
||||
|
||||
Template.initialize(loader_class=compiled.Loader)
|
||||
|
||||
Consult the `uTemplate documentation <https://github.com/pfalcon/utemplate>`_
|
||||
for additional information regarding template loaders.
|
||||
|
||||
Using the Jinja Engine
|
||||
^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython only
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `jinja.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/jinja.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | `Jinja2 <https://jinja.palletsprojects.com/>`_
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello.py>`_
|
||||
|
||||
The :class:`Template <microdot.jinja.Template>` class is used to load a
|
||||
template. The argument is the template filename, relative to the templates
|
||||
directory, which is *templates* by default.
|
||||
|
||||
The ``Template`` object has a :func:`render() <microdot.jinja.Template.render>`
|
||||
method that renders the template to a string. This method receives any
|
||||
arguments that are used by the template.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.jinja import Template
|
||||
|
||||
@app.get('/')
|
||||
async def index(req):
|
||||
return Template('index.html').render()
|
||||
|
||||
The ``Template`` object also has a :func:`generate() <microdot.jinja.Template.generate>`
|
||||
method, which returns a generator instead of a string.
|
||||
|
||||
The default location from where templates are loaded is the *templates*
|
||||
subdirectory. This location can be changed with the
|
||||
:func:`Template.initialize <microdot.jinja.Template.initialize>` class method::
|
||||
|
||||
Template.initialize('my_templates')
|
||||
|
||||
The ``initialize()`` method also accepts ``enable_async`` argument, which
|
||||
can be set to ``True`` if asynchronous rendering of templates is desired. If
|
||||
this option is enabled, then the
|
||||
:func:`render_async() <microdot.jinja.Template.render_async>` and
|
||||
:func:`generate_async() <microdot.jinja.Template.generate_async>` methods
|
||||
must be used.
|
||||
|
||||
.. note::
|
||||
The Jinja extension is not compatible with MicroPython.
|
||||
36
docs/extensions/test_client.rst
Normal file
36
docs/extensions/test_client.rst
Normal file
@@ -0,0 +1,36 @@
|
||||
Test Client
|
||||
~~~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `test_client.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/test_client.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
The Microdot Test Client is a utility class that can be used in tests to send
|
||||
requests into the application without having to start a web server.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot import Microdot
|
||||
from microdot.test_client import TestClient
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
def index(req):
|
||||
return 'Hello, World!'
|
||||
|
||||
async def test_app():
|
||||
client = TestClient(app)
|
||||
response = await client.get('/')
|
||||
assert response.text == 'Hello, World!'
|
||||
|
||||
See the documentation for the :class:`TestClient <microdot.test_client.TestClient>`
|
||||
class for more details.
|
||||
63
docs/extensions/websocket.rst
Normal file
63
docs/extensions/websocket.rst
Normal file
@@ -0,0 +1,63 @@
|
||||
WebSocket
|
||||
~~~~~~~~~
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Compatibility
|
||||
- | CPython & MicroPython
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `websocket.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/websocket.py>`_
|
||||
| `helpers.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/helpers.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `echo.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo.py>`_
|
||||
|
||||
The WebSocket extension gives the application the ability to handle WebSocket
|
||||
requests. The :func:`with_websocket <microdot.websocket.with_websocket>`
|
||||
decorator is used to mark a route handler as a WebSocket handler. Decorated
|
||||
routes receive a WebSocket object as a second argument. The WebSocket object
|
||||
provides ``send()`` and ``receive()`` asynchronous methods to send and receive
|
||||
messages respectively.
|
||||
|
||||
Example::
|
||||
|
||||
from microdot.websocket import with_websocket
|
||||
|
||||
@app.route('/echo')
|
||||
@with_websocket
|
||||
async def echo(request, ws):
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
|
||||
To end the WebSocket connection, the route handler can exit, without returning
|
||||
anything::
|
||||
|
||||
@app.route('/echo')
|
||||
@with_websocket
|
||||
async def echo(request, ws):
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
if message == 'exit':
|
||||
break
|
||||
await ws.send(message)
|
||||
await ws.send('goodbye')
|
||||
|
||||
If the client ends the WebSocket connection from their side, the route function
|
||||
is cancelled. The route function can catch the ``CancelledError`` exception
|
||||
from asyncio to perform cleanup tasks::
|
||||
|
||||
@app.route('/echo')
|
||||
@with_websocket
|
||||
async def echo(request, ws):
|
||||
try:
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
except asyncio.CancelledError:
|
||||
print('Client disconnected!')
|
||||
@@ -1,5 +1,8 @@
|
||||
Cross-Compiling and Freezing Microdot (MicroPython Only)
|
||||
--------------------------------------------------------
|
||||
Cross-Compiling and Freezing Microdot
|
||||
-------------------------------------
|
||||
|
||||
.. note::
|
||||
This section only applies when using Microdot on MicroPython.
|
||||
|
||||
Microdot is a fairly small framework, so its size is not something you need to
|
||||
be concerned about unless you are working with MicroPython on hardware with a
|
||||
@@ -36,7 +39,7 @@ Cross-Compiling
|
||||
|
||||
An issue that is common with low-end microcontroller boards is that they do not
|
||||
have enough RAM for the MicroPython compiler to compile the source files, but
|
||||
once the code is compiled they are able to run it without problems.
|
||||
once the code is compiled they are able to run it just fine.
|
||||
|
||||
To address this, MicroPython allows you to cross-compile source files on your
|
||||
desktop or laptop computer and then upload their compiled versions to the
|
||||
@@ -82,8 +85,8 @@ imported directly from the device's ROM, leaving more RAM available for
|
||||
application use.
|
||||
|
||||
The process to create a custom firmware is unfortunately non-trivial and
|
||||
different depending on the device, so you will need to consult the MicroPython
|
||||
documentation that applies to your device to learn how to do this.
|
||||
different for each microcontroller platform, so you will need to consult the
|
||||
MicroPython documentation that applies to your device to learn how to do this.
|
||||
|
||||
The part of the process that is common to all devices is the creation of a
|
||||
`manifest file <https://docs.micropython.org/en/latest/reference/manifest.html>`_
|
||||
11
docs/implementation/index.rst
Normal file
11
docs/implementation/index.rst
Normal file
@@ -0,0 +1,11 @@
|
||||
Implementation notes
|
||||
--------------------
|
||||
|
||||
This section covers some implementation aspects of Microdot.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
migrating
|
||||
freezing
|
||||
|
||||
@@ -14,13 +14,14 @@ systems with limited resources such as microcontrollers. Both standard Python
|
||||
(CPython) and `MicroPython <https://micropython.org>`_ are supported.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
:maxdepth: 2
|
||||
|
||||
intro
|
||||
extensions
|
||||
migrating
|
||||
freezing
|
||||
api
|
||||
users-guide/index
|
||||
extensions/index
|
||||
implementation/index
|
||||
api/index
|
||||
contributing
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`search`
|
||||
|
||||
857
docs/intro.rst
857
docs/intro.rst
@@ -1,13 +1,14 @@
|
||||
Installation
|
||||
------------
|
||||
|
||||
The installation method is different depending on the version of Python.
|
||||
The installation method is different depending on which flavor of Python you
|
||||
are using.
|
||||
|
||||
CPython Installation
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For use with standard Python (CPython) projects, Microdot and all of its core
|
||||
extensions are installed with ``pip``::
|
||||
extensions are installed with ``pip`` or any of its alternatives::
|
||||
|
||||
pip install microdot
|
||||
|
||||
@@ -17,855 +18,27 @@ MicroPython Installation
|
||||
For MicroPython, the recommended approach is to manually copy the necessary
|
||||
source files from the
|
||||
`GitHub repository <https://github.com/miguelgrinberg/microdot/tree/main/src>`_
|
||||
into your device, ideally after
|
||||
`compiling <https://docs.micropython.org/en/latest/reference/mpyfiles.html>`_
|
||||
them to *.mpy* files. These source files can also be
|
||||
`frozen <https://docs.micropython.org/en/latest/develop/optimizations.html?highlight=frozen#frozen-bytecode>`_
|
||||
and incorporated into a custom MicroPython firmware.
|
||||
into your device.
|
||||
|
||||
Use the following guidelines to know what files to copy:
|
||||
|
||||
* For a minimal setup with only the base web server functionality, copy
|
||||
`microdot.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/microdot.py>`_
|
||||
into your project.
|
||||
* For a configuration that includes one or more optional extensions, create a
|
||||
*microdot* directory in your device and copy the following files:
|
||||
to your device.
|
||||
* For a configuration that includes one or more of the optional extensions,
|
||||
create a *microdot* directory in your device and copy the following files:
|
||||
|
||||
* `__init__.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/__init__.py>`_
|
||||
* `microdot.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/microdot.py>`_
|
||||
* any needed `extensions <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot>`_.
|
||||
|
||||
Some of the low end devices are perfectly capable of running Microdot once
|
||||
compiled, but do not have enough RAM for the compiler. For these cases you can
|
||||
`pre-compile <https://docs.micropython.org/en/latest/reference/mpyfiles.html>`_
|
||||
the files to *.mpy* files for the version of MicroPython that you use in your
|
||||
device.
|
||||
|
||||
Getting Started
|
||||
---------------
|
||||
If space in your device is extremely tight, you may also consider
|
||||
`freezing <https://docs.micropython.org/en/latest/develop/optimizations.html?highlight=frozen#frozen-bytecode>`_
|
||||
the Microdot files and incorporating them into a custom MicroPython firmware.
|
||||
|
||||
This section describes the main features of Microdot in an informal manner.
|
||||
|
||||
For detailed reference information, consult the :ref:`API Reference`.
|
||||
|
||||
If you are familiar with releases of Microdot before 2.x, review the
|
||||
:ref:`Migration Guide <Migrating to Microdot 2.x from Older Releases>`.
|
||||
|
||||
A Simple Microdot Web Server
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The following is an example of a simple web server::
|
||||
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
return 'Hello, world!'
|
||||
|
||||
app.run()
|
||||
|
||||
The script imports the :class:`Microdot <microdot.Microdot>` class and creates
|
||||
an application instance from it.
|
||||
|
||||
The application instance provides a :func:`route() <microdot.Microdot.route>`
|
||||
decorator, which is used to define one or more routes, as needed by the
|
||||
application.
|
||||
|
||||
The ``route()`` decorator takes the path portion of the URL as an
|
||||
argument, and maps it to the decorated function, so that the function is called
|
||||
when the client requests the URL.
|
||||
|
||||
When the function is called, it is passed a :class:`Request <microdot.Request>`
|
||||
object as an argument, which provides access to the information passed by the
|
||||
client. The value returned by the function is sent back to the client as the
|
||||
response.
|
||||
|
||||
Microdot is an asynchronous framework that uses the ``asyncio`` package. Route
|
||||
handler functions can be defined as ``async def`` or ``def`` functions, but
|
||||
``async def`` functions are recommended for performance.
|
||||
|
||||
The :func:`run() <microdot.Microdot.run>` method starts the application's web
|
||||
server on port 5000 by default. This method blocks while it waits for
|
||||
connections from clients.
|
||||
|
||||
Running with CPython
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello.py>`_
|
||||
|
||||
When using CPython, you can start the web server by running the script that
|
||||
has the ``app.run()`` call at the bottom::
|
||||
|
||||
python main.py
|
||||
|
||||
After starting the script, open a web browser and navigate to
|
||||
*http://localhost:5000/* to access the application at the default address for
|
||||
the Microdot web server. From other computers in the same network, use the IP
|
||||
address or hostname of the computer running the script instead of
|
||||
``localhost``.
|
||||
|
||||
Running with MicroPython
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello.py>`_
|
||||
| `gpio.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/gpio/gpio.py>`_
|
||||
|
||||
When using MicroPython, you can upload a *main.py* file containing the web
|
||||
server code to your device, along with the required Microdot files, as defined
|
||||
in the :ref:`MicroPython Installation` section.
|
||||
|
||||
MicroPython will automatically run *main.py* when the device is powered on, so
|
||||
the web server will automatically start. The application can be accessed on
|
||||
port 5000 at the device's IP address. As indicated above, the port can be
|
||||
changed by passing the ``port`` argument to the ``run()`` method.
|
||||
|
||||
.. note::
|
||||
Microdot does not configure the network interface of the device in which it
|
||||
is running. If your device requires a network connection to be made in
|
||||
advance, for example to a Wi-Fi access point, this must be configured before
|
||||
the ``run()`` method is invoked.
|
||||
|
||||
Web Server Configuration
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The :func:`run() <microdot.Microdot.run>` method supports a few arguments to
|
||||
configure the web server.
|
||||
|
||||
- ``port``: The port number to listen on. Pass the desired port number in this
|
||||
argument to use a port different than the default of 5000. For example::
|
||||
|
||||
app.run(port=6000)
|
||||
|
||||
- ``host``: The IP address of the network interface to listen on. By default
|
||||
the server listens on all available interfaces. To listen only on the local
|
||||
loopback interface, pass ``'127.0.0.1'`` as value for this argument.
|
||||
- ``debug``: when set to ``True``, the server ouputs logging information to the
|
||||
console. The default is ``False``.
|
||||
- ``ssl``: an ``SSLContext`` instance that configures the server to use TLS
|
||||
encryption, or ``None`` to disable TLS use. The default is ``None``. The
|
||||
following example demonstrates how to configure the server with an SSL
|
||||
certificate stored in *cert.pem* and *key.pem* files::
|
||||
|
||||
import ssl
|
||||
|
||||
# ...
|
||||
|
||||
sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
sslctx.load_cert_chain('cert.pem', 'key.pem')
|
||||
app.run(port=4443, debug=True, ssl=sslctx)
|
||||
|
||||
.. note::
|
||||
When using CPython, the certificate and key files must be given in PEM
|
||||
format. When using MicroPython, these files must be given in DER format.
|
||||
|
||||
Defining Routes
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The :func:`route() <microdot.Microdot.route>` decorator is used to associate an
|
||||
application URL with the function that handles it. The only required argument
|
||||
to the decorator is the path portion of the URL.
|
||||
|
||||
The following example creates a route for the root URL of the application::
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
return 'Hello, world!'
|
||||
|
||||
When a client requests the root URL (for example, *http://localhost:5000/*),
|
||||
Microdot will call the ``index()`` function, passing it a
|
||||
:class:`Request <microdot.Request>` object. The return value of the function
|
||||
is the response that is sent to the client.
|
||||
|
||||
Below is another example, this one with a route for a URL with two components
|
||||
in its path::
|
||||
|
||||
@app.route('/users/active')
|
||||
async def active_users(request):
|
||||
return 'Active users: Susan, Joe, and Bob'
|
||||
|
||||
The complete URL that maps to this route is
|
||||
*http://localhost:5000/users/active*.
|
||||
|
||||
An application can include multiple routes. Microdot uses the path portion of
|
||||
the URL to determine the correct route function to call for each incoming
|
||||
request.
|
||||
|
||||
Choosing the HTTP Method
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
All the example routes shown above are associated with ``GET`` requests, which
|
||||
are the default. Applications often need to define routes for other HTTP
|
||||
methods, such as ``POST``, ``PUT``, ``PATCH`` and ``DELETE``. The ``route()``
|
||||
decorator takes a ``methods`` optional argument, in which the application can
|
||||
provide a list of HTTP methods that the route should be associated with on the
|
||||
given path.
|
||||
|
||||
The following example defines a route that handles ``GET`` and ``POST``
|
||||
requests within the same function::
|
||||
|
||||
@app.route('/invoices', methods=['GET', 'POST'])
|
||||
async def invoices(request):
|
||||
if request.method == 'GET':
|
||||
return 'get invoices'
|
||||
elif request.method == 'POST':
|
||||
return 'create an invoice'
|
||||
|
||||
As an alternative to the example above, in which a single function is used to
|
||||
handle multiple HTTP methods, sometimes it may be desirable to write a separate
|
||||
function for each HTTP method. The above example can be implemented with two
|
||||
routes as follows::
|
||||
|
||||
@app.route('/invoices', methods=['GET'])
|
||||
async def get_invoices(request):
|
||||
return 'get invoices'
|
||||
|
||||
@app.route('/invoices', methods=['POST'])
|
||||
async def create_invoice(request):
|
||||
return 'create an invoice'
|
||||
|
||||
Microdot provides the :func:`get() <microdot.Microdot.get>`,
|
||||
:func:`post() <microdot.Microdot.post>`, :func:`put() <microdot.Microdot.put>`,
|
||||
:func:`patch() <microdot.Microdot.patch>`, and
|
||||
:func:`delete() <microdot.Microdot.delete>` decorators as shortcuts for the
|
||||
corresponding HTTP methods. The two example routes above can be written more
|
||||
concisely with them::
|
||||
|
||||
@app.get('/invoices')
|
||||
async def get_invoices(request):
|
||||
return 'get invoices'
|
||||
|
||||
@app.post('/invoices')
|
||||
async def create_invoice(request):
|
||||
return 'create an invoice'
|
||||
|
||||
Including Dynamic Components in the URL Path
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The examples shown above all use hardcoded URL paths. Microdot also supports
|
||||
the definition of routes that have dynamic components in the path. For example,
|
||||
the following route associates all URLs that have a path following the pattern
|
||||
*http://localhost:5000/users/<username>* with the ``get_user()`` function::
|
||||
|
||||
@app.get('/users/<username>')
|
||||
async def get_user(request, username):
|
||||
return 'User: ' + username
|
||||
|
||||
As shown in the example, a path component that is enclosed in angle brackets
|
||||
is considered a placeholder. Microdot accepts any values for that portion of
|
||||
the URL path, and passes the value received to the function as an argument
|
||||
after the request object.
|
||||
|
||||
Routes are not limited to a single dynamic component. The following route shows
|
||||
how multiple dynamic components can be included in the path::
|
||||
|
||||
@app.get('/users/<firstname>/<lastname>')
|
||||
async def get_user(request, firstname, lastname):
|
||||
return 'User: ' + firstname + ' ' + lastname
|
||||
|
||||
Dynamic path components are considered to be strings by default. An explicit
|
||||
type can be specified as a prefix, separated from the dynamic component name by
|
||||
a colon. The following route has two dynamic components declared as an integer
|
||||
and a string respectively::
|
||||
|
||||
@app.get('/users/<int:id>/<string:username>')
|
||||
async def get_user(request, id, username):
|
||||
return 'User: ' + username + ' (' + str(id) + ')'
|
||||
|
||||
If a dynamic path component is defined as an integer, the value passed to the
|
||||
route function is also an integer. If the client sends a value that is not an
|
||||
integer in the corresponding section of the URL path, then the URL will not
|
||||
match and the route will not be called.
|
||||
|
||||
A special type ``path`` can be used to capture the remainder of the path as a
|
||||
single argument. The difference between an argument of type ``path`` and one of
|
||||
type ``string`` is that the latter stops capturing when a ``/`` appears in the
|
||||
URL::
|
||||
|
||||
@app.get('/tests/<path:path>')
|
||||
async def get_test(request, path):
|
||||
return 'Test: ' + path
|
||||
|
||||
For the most control, the ``re`` type allows the application to provide a
|
||||
custom regular expression for the dynamic component. The next example defines
|
||||
a route that only matches usernames that begin with an upper or lower case
|
||||
letter, followed by a sequence of letters or numbers::
|
||||
|
||||
@app.get('/users/<re:[a-zA-Z][a-zA-Z0-9]*:username>')
|
||||
async def get_user(request, username):
|
||||
return 'User: ' + username
|
||||
|
||||
.. note::
|
||||
Dynamic path components are passed to route functions as keyword arguments,
|
||||
so the names of the function arguments must match the names declared in the
|
||||
path specification.
|
||||
|
||||
Before and After Request Handlers
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
It is common for applications to need to perform one or more actions before a
|
||||
request is handled. Examples include authenticating and/or authorizing the
|
||||
client, opening a connection to a database, or checking if the requested
|
||||
resource can be obtained from a cache. The
|
||||
:func:`before_request() <microdot.Microdot.before_request>` decorator registers
|
||||
a function to be called before the request is dispatched to the route function.
|
||||
|
||||
The following example registers a before-request handler that ensures that the
|
||||
client is authenticated before the request is handled::
|
||||
|
||||
@app.before_request
|
||||
async def authenticate(request):
|
||||
user = authorize(request)
|
||||
if not user:
|
||||
return 'Unauthorized', 401
|
||||
request.g.user = user
|
||||
|
||||
Before-request handlers receive the request object as an argument. If the
|
||||
function returns a value, Microdot sends it to the client as the response, and
|
||||
does not invoke the route function. This gives before-request handlers the
|
||||
power to intercept a request if necessary. The example above uses this
|
||||
technique to prevent an unauthorized user from accessing the requested
|
||||
route.
|
||||
|
||||
After-request handlers registered with the
|
||||
:func:`after_request() <microdot.Microdot.after_request>` decorator are called
|
||||
after the route function returns a response. Their purpose is to perform any
|
||||
common closing or cleanup tasks. The next example shows a combination of
|
||||
before- and after-request handlers that print the time it takes for a request
|
||||
to be handled::
|
||||
|
||||
@app.before_request
|
||||
async def start_timer(request):
|
||||
request.g.start_time = time.time()
|
||||
|
||||
@app.after_request
|
||||
async def end_timer(request, response):
|
||||
duration = time.time() - request.g.start_time
|
||||
print(f'Request took {duration:0.2f} seconds')
|
||||
|
||||
After-request handlers receive the request and response objects as arguments,
|
||||
and they can return a modified response object to replace the original. If
|
||||
no value is returned from an after-request handler, then the original response
|
||||
object is used.
|
||||
|
||||
The after-request handlers are only invoked for successful requests. The
|
||||
:func:`after_error_request() <microdot.Microdot.after_error_request>`
|
||||
decorator can be used to register a function that is called after an error
|
||||
occurs. The function receives the request and the error response and is
|
||||
expected to return an updated response object after performing any necessary
|
||||
cleanup.
|
||||
|
||||
.. note::
|
||||
The :ref:`request.g <The "g" Object>` object used in many of the above
|
||||
examples is a special object that allows the before- and after-request
|
||||
handlers, as well as the route function to share data during the life of the
|
||||
request.
|
||||
|
||||
Error Handlers
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
When an error occurs during the handling of a request, Microdot ensures that
|
||||
the client receives an appropriate error response. Some of the common errors
|
||||
automatically handled by Microdot are:
|
||||
|
||||
- 400 for malformed requests.
|
||||
- 404 for URLs that are unknown.
|
||||
- 405 for URLs that are known, but not implemented for the requested HTTP
|
||||
method.
|
||||
- 413 for requests that are larger than the allowed size.
|
||||
- 500 when the application raises an unhandled exception.
|
||||
|
||||
While the above errors are fully complaint with the HTTP specification, the
|
||||
application might want to provide custom responses for them. The
|
||||
:func:`errorhandler() <microdot.Microdot.errorhandler>` decorator registers
|
||||
functions to respond to specific error codes. The following example shows a
|
||||
custom error handler for 404 errors::
|
||||
|
||||
@app.errorhandler(404)
|
||||
async def not_found(request):
|
||||
return {'error': 'resource not found'}, 404
|
||||
|
||||
The ``errorhandler()`` decorator has a second form, in which it takes an
|
||||
exception class as an argument. Microdot will invoke the handler when an
|
||||
unhandled exception that is an instance of the given class is raised. The next
|
||||
example provides a custom response for division by zero errors::
|
||||
|
||||
@app.errorhandler(ZeroDivisionError)
|
||||
async def division_by_zero(request, exception):
|
||||
return {'error': 'division by zero'}, 500
|
||||
|
||||
When the raised exception class does not have an error handler defined, but
|
||||
one or more of its parent classes do, Microdot makes an attempt to invoke the
|
||||
most specific handler.
|
||||
|
||||
Mounting a Sub-Application
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Small Microdot applications can be written as a single source file, but this
|
||||
is not the best option for applications that past a certain size. To make it
|
||||
simpler to write large applications, Microdot supports the concept of
|
||||
sub-applications that can be "mounted" on a larger application, possibly with
|
||||
a common URL prefix applied to all of its routes. For developers familiar with
|
||||
the Flask framework, this is a similar concept to Flask's blueprints.
|
||||
|
||||
Consider, for example, a *customers.py* sub-application that implements
|
||||
operations on customers::
|
||||
|
||||
from microdot import Microdot
|
||||
|
||||
customers_app = Microdot()
|
||||
|
||||
@customers_app.get('/')
|
||||
async def get_customers(request):
|
||||
# return all customers
|
||||
|
||||
@customers_app.post('/')
|
||||
async def new_customer(request):
|
||||
# create a new customer
|
||||
|
||||
Similar to the above, the *orders.py* sub-application implements operations on
|
||||
customer orders::
|
||||
|
||||
from microdot import Microdot
|
||||
|
||||
orders_app = Microdot()
|
||||
|
||||
@orders_app.get('/')
|
||||
async def get_orders(request):
|
||||
# return all orders
|
||||
|
||||
@orders_app.post('/')
|
||||
async def new_order(request):
|
||||
# create a new order
|
||||
|
||||
Now the main application, which is stored in *main.py*, can import and mount
|
||||
the sub-applications to build the larger combined application::
|
||||
|
||||
from microdot import Microdot
|
||||
from customers import customers_app
|
||||
from orders import orders_app
|
||||
|
||||
def create_app():
|
||||
app = Microdot()
|
||||
app.mount(customers_app, url_prefix='/customers')
|
||||
app.mount(orders_app, url_prefix='/orders')
|
||||
return app
|
||||
|
||||
app = create_app()
|
||||
app.run()
|
||||
|
||||
The resulting application will have the customer endpoints available at
|
||||
*/customers/* and the order endpoints available at */orders/*.
|
||||
|
||||
.. note::
|
||||
Before-request, after-request and error handlers defined in the
|
||||
sub-application are also copied over to the main application at mount time.
|
||||
Once installed in the main application, these handlers will apply to the
|
||||
whole application and not just the sub-application in which they were
|
||||
created.
|
||||
|
||||
Shutting Down the Server
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Web servers are designed to run forever, and are often stopped by sending them
|
||||
an interrupt signal. But having a way to gracefully stop the server is
|
||||
sometimes useful, especially in testing environments. Microdot provides a
|
||||
:func:`shutdown() <microdot.Microdot.shutdown>` method that can be invoked
|
||||
during the handling of a route to gracefully shut down the server when that
|
||||
request completes. The next example shows how to use this feature::
|
||||
|
||||
@app.get('/shutdown')
|
||||
async def shutdown(request):
|
||||
request.app.shutdown()
|
||||
return 'The server is shutting down...'
|
||||
|
||||
The request that invokes the ``shutdown()`` method will complete, and then the
|
||||
server will not accept any new requests and stop once any remaining requests
|
||||
complete. At this point the ``app.run()`` call will return.
|
||||
|
||||
The Request Object
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The :class:`Request <microdot.Request>` object encapsulates all the information
|
||||
passed by the client. It is passed as an argument to route handlers, as well as
|
||||
to before-request, after-request and error handlers.
|
||||
|
||||
Request Attributes
|
||||
^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The request object provides access to the request attributes, including:
|
||||
|
||||
- :attr:`method <microdot.Request.method>`: The HTTP method of the request.
|
||||
- :attr:`path <microdot.Request.path>`: The path of the request.
|
||||
- :attr:`args <microdot.Request.args>`: The query string parameters of the
|
||||
request, as a :class:`MultiDict <microdot.MultiDict>` object.
|
||||
- :attr:`headers <microdot.Request.headers>`: The headers of the request, as a
|
||||
dictionary.
|
||||
- :attr:`cookies <microdot.Request.cookies>`: The cookies that the client sent
|
||||
with the request, as a dictionary.
|
||||
- :attr:`content_type <microdot.Request.content_type>`: The content type
|
||||
specified by the client, or ``None`` if no content type was specified.
|
||||
- :attr:`content_length <microdot.Request.content_length>`: The content
|
||||
length of the request, or 0 if no content length was specified.
|
||||
- :attr:`client_addr <microdot.Request.client_addr>`: The network address of
|
||||
the client, as a tuple (host, port).
|
||||
- :attr:`app <microdot.Request.app>`: The application instance that created the
|
||||
request.
|
||||
- :attr:`g <microdot.Request.g>`: The ``g`` object, where handlers can store
|
||||
request-specific data to be shared among handlers. See :ref:`The "g" Object`
|
||||
for details.
|
||||
|
||||
JSON Payloads
|
||||
^^^^^^^^^^^^^
|
||||
|
||||
When the client sends a request that contains JSON data in the body, the
|
||||
application can access the parsed JSON data using the
|
||||
:attr:`json <microdot.Request.json>` attribute. The following example shows how
|
||||
to use this attribute::
|
||||
|
||||
@app.post('/customers')
|
||||
async def create_customer(request):
|
||||
customer = request.json
|
||||
# do something with customer
|
||||
return {'success': True}
|
||||
|
||||
.. note::
|
||||
The client must set the ``Content-Type`` header to ``application/json`` for
|
||||
the ``json`` attribute of the request object to be populated.
|
||||
|
||||
URLEncoded Form Data
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The request object also supports standard HTML form submissions through the
|
||||
:attr:`form <microdot.Request.form>` attribute, which presents the form data
|
||||
as a :class:`MultiDict <microdot.MultiDict>` object. Example::
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
async def index(req):
|
||||
name = 'Unknown'
|
||||
if req.method == 'POST':
|
||||
name = req.form.get('name')
|
||||
return f'Hello {name}'
|
||||
|
||||
.. note::
|
||||
Form submissions are only parsed when the ``Content-Type`` header is set by
|
||||
the client to ``application/x-www-form-urlencoded``. Form submissions using
|
||||
the ``multipart/form-data`` content type are currently not supported.
|
||||
|
||||
Accessing the Raw Request Body
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
For cases in which neither JSON nor form data is expected, the
|
||||
:attr:`body <microdot.Request.body>` request attribute returns the entire body
|
||||
of the request as a byte sequence.
|
||||
|
||||
If the expected body is too large to fit safely in memory, the application can
|
||||
use the :attr:`stream <microdot.Request.stream>` request attribute to read the
|
||||
body contents as a file-like object. The
|
||||
:attr:`max_body_length <microdot.Request.max_body_length>` attribute of the
|
||||
request object defines the size at which bodies are streamed instead of loaded
|
||||
into memory.
|
||||
|
||||
Cookies
|
||||
^^^^^^^
|
||||
|
||||
Cookies that are sent by the client are made available through the
|
||||
:attr:`cookies <microdot.Request.cookies>` attribute of the request object in
|
||||
dictionary form.
|
||||
|
||||
The "g" Object
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
Sometimes applications need to store data during the lifetime of a request, so
|
||||
that it can be shared between the before- and after-request handlers, the
|
||||
route function and any error handlers. The request object provides the
|
||||
:attr:`g <microdot.Request.g>` attribute for that purpose.
|
||||
|
||||
In the following example, a before request handler authorizes the client and
|
||||
stores the username so that the route function can use it::
|
||||
|
||||
@app.before_request
|
||||
async def authorize(request):
|
||||
username = authenticate_user(request)
|
||||
if not username:
|
||||
return 'Unauthorized', 401
|
||||
request.g.username = username
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return f'Hello, {request.g.username}!'
|
||||
|
||||
Request-Specific After-Request Handlers
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Sometimes applications need to perform operations on the response object
|
||||
before it is sent to the client, for example to set or remove a cookie. A good
|
||||
option to use for this is to define a request-specific after-request handler
|
||||
using the :func:`after_request <microdot.Microdot.after_request>` decorator.
|
||||
Request-specific after-request handlers are called by Microdot after the route
|
||||
function returns and all the application-wide after-request handlers have been
|
||||
called.
|
||||
|
||||
The next example shows how a cookie can be updated using a request-specific
|
||||
after-request handler defined inside a route function::
|
||||
|
||||
@app.post('/logout')
|
||||
async def logout(request):
|
||||
@request.after_request
|
||||
def reset_session(request, response):
|
||||
response.set_cookie('session', '', http_only=True)
|
||||
return response
|
||||
|
||||
return 'Logged out'
|
||||
|
||||
Request Limits
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
To help prevent malicious attacks, Microdot provides some configuration options
|
||||
to limit the amount of information that is accepted:
|
||||
|
||||
- :attr:`max_content_length <microdot.Request.max_content_length>`: The
|
||||
maximum size accepted for the request body, in bytes. When a client sends a
|
||||
request that is larger than this, the server will respond with a 413 error.
|
||||
The default is 16KB.
|
||||
- :attr:`max_body_length <microdot.Request.max_body_length>`: The maximum
|
||||
size that is loaded in the :attr:`body <microdot.Request.body>` attribute, in
|
||||
bytes. Requests that have a body that is larger than this size but smaller
|
||||
than the size set for ``max_content_length`` can only be accessed through the
|
||||
:attr:`stream <microdot.Request.stream>` attribute. The default is also 16KB.
|
||||
- :attr:`max_readline <microdot.Request.max_readline>`: The maximum allowed
|
||||
size for a request line, in bytes. The default is 2KB.
|
||||
|
||||
The following example configures the application to accept requests with
|
||||
payloads up to 1MB in size, but prevents requests that are larger than 8KB from
|
||||
being loaded into memory::
|
||||
|
||||
from microdot import Request
|
||||
|
||||
Request.max_content_length = 1024 * 1024
|
||||
Request.max_body_length = 8 * 1024
|
||||
|
||||
Responses
|
||||
~~~~~~~~~
|
||||
|
||||
The value or values that are returned from the route function are used by
|
||||
Microdot to build the response that is sent to the client. The following
|
||||
sections describe the different types of responses that are supported.
|
||||
|
||||
The Three Parts of a Response
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Route functions can return one, two or three values. The first or only value is
|
||||
always returned to the client in the response body::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return 'Hello, World!'
|
||||
|
||||
In the above example, Microdot issues a standard 200 status code response, and
|
||||
inserts default headers.
|
||||
|
||||
The application can provide its own status code as a second value returned from
|
||||
the route to override the 200 default. The example below returns a 202 status
|
||||
code::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return 'Hello, World!', 202
|
||||
|
||||
The application can also return a third value, a dictionary with additional
|
||||
headers that are added to, or replace the default ones included by Microdot.
|
||||
The next example returns an HTML response, instead of a default text response::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return '<h1>Hello, World!</h1>', 202, {'Content-Type': 'text/html'}
|
||||
|
||||
If the application needs to return custom headers, but does not need to change
|
||||
the default status code, then it can return two values, omitting the status
|
||||
code::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return '<h1>Hello, World!</h1>', {'Content-Type': 'text/html'}
|
||||
|
||||
The application can also return a :class:`Response <microdot.Response>` object
|
||||
containing all the details of the response as a single value.
|
||||
|
||||
JSON Responses
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
If the application needs to return a response with JSON formatted data, it can
|
||||
return a dictionary or a list as the first value, and Microdot will
|
||||
automatically format the response as JSON.
|
||||
|
||||
Example::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return {'hello': 'world'}
|
||||
|
||||
.. note::
|
||||
A ``Content-Type`` header set to ``application/json`` is automatically added
|
||||
to the response.
|
||||
|
||||
Redirects
|
||||
^^^^^^^^^
|
||||
|
||||
The :func:`redirect <microdot.Response.redirect>` function is a helper that
|
||||
creates redirect responses::
|
||||
|
||||
from microdot import redirect
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return redirect('/about')
|
||||
|
||||
File Responses
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
The :func:`send_file <microdot.Response.send_file>` function builds a response
|
||||
object for a file::
|
||||
|
||||
from microdot import send_file
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return send_file('/static/index.html')
|
||||
|
||||
A suggested caching duration can be returned to the client in the ``max_age``
|
||||
argument::
|
||||
|
||||
from microdot import send_file
|
||||
|
||||
@app.get('/')
|
||||
async def image(request):
|
||||
return send_file('/static/image.jpg', max_age=3600) # in seconds
|
||||
|
||||
.. note::
|
||||
Unlike other web frameworks, Microdot does not automatically configure a
|
||||
route to serve static files. The following is an example route that can be
|
||||
added to the application to serve static files from a *static* directory in
|
||||
the project::
|
||||
|
||||
@app.route('/static/<path:path>')
|
||||
async def static(request, path):
|
||||
if '..' in path:
|
||||
# directory traversal is not allowed
|
||||
return 'Not found', 404
|
||||
return send_file('static/' + path, max_age=86400)
|
||||
|
||||
Streaming Responses
|
||||
^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Instead of providing a response as a single value, an application can opt to
|
||||
return a response that is generated in chunks, by returning a Python generator.
|
||||
The example below returns all the numbers in the fibonacci sequence below 100::
|
||||
|
||||
@app.get('/fibonacci')
|
||||
async def fibonacci(request):
|
||||
async def generate_fibonacci():
|
||||
a, b = 0, 1
|
||||
while a < 100:
|
||||
yield str(a) + '\n'
|
||||
a, b = b, a + b
|
||||
|
||||
return generate_fibonacci()
|
||||
|
||||
.. note::
|
||||
Under CPython, the generator function can be a ``def`` or ``async def``
|
||||
function, as well as a class-based generator.
|
||||
|
||||
Under MicroPython, asynchronous generator functions are not supported, so
|
||||
only ``def`` generator functions can be used. Asynchronous class-based
|
||||
generators are supported.
|
||||
|
||||
Changing the Default Response Content Type
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Microdot uses a ``text/plain`` content type by default for responses that do
|
||||
not explicitly include the ``Content-Type`` header. The application can change
|
||||
this default by setting the desired content type in the
|
||||
:attr:`default_content_type <microdot.Response.default_content_type>` attribute
|
||||
of the :class:`Response <microdot.Response>` class.
|
||||
|
||||
The example that follows configures the application to use ``text/html`` as
|
||||
default content type::
|
||||
|
||||
from microdot import Response
|
||||
|
||||
Response.default_content_type = 'text/html'
|
||||
|
||||
Setting Cookies
|
||||
^^^^^^^^^^^^^^^
|
||||
|
||||
Many web applications rely on cookies to maintain client state between
|
||||
requests. Cookies can be set with the ``Set-Cookie`` header in the response,
|
||||
but since this is such a common practice, Microdot provides the
|
||||
:func:`set_cookie() <microdot.Response.set_cookie>` method in the response
|
||||
object to add a properly formatted cookie header to the response.
|
||||
|
||||
Given that route functions do not normally work directly with the response
|
||||
object, the recommended way to set a cookie is to do it in a
|
||||
:ref:`request-specific after-request handler <Request-Specific After-Request Handlers>`.
|
||||
|
||||
Example::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
@request.after_request
|
||||
async def set_cookie(request, response):
|
||||
response.set_cookie('name', 'value')
|
||||
return response
|
||||
|
||||
return 'Hello, World!'
|
||||
|
||||
Another option is to create a response object directly in the route function::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
response = Response('Hello, World!')
|
||||
response.set_cookie('name', 'value')
|
||||
return response
|
||||
|
||||
.. note::
|
||||
Standard cookies do not offer sufficient privacy and security controls, so
|
||||
never store sensitive information in them unless you are adding additional
|
||||
protection mechanisms such as encryption or cryptographic signing. The
|
||||
:ref:`session <Maintaining Secure User Sessions>` extension implements signed
|
||||
cookies that prevent tampering by malicious actors.
|
||||
|
||||
Concurrency
|
||||
~~~~~~~~~~~
|
||||
|
||||
Microdot implements concurrency through the ``asyncio`` package. Applications
|
||||
must ensure their handlers do not block, as this will prevent other concurrent
|
||||
requests from being handled.
|
||||
|
||||
When running under CPython, ``async def`` handler functions run as native
|
||||
asyncio tasks, while ``def`` handler functions are executed in a
|
||||
`thread executor <https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor>`_
|
||||
to prevent them from blocking the asynchronous loop.
|
||||
|
||||
Under MicroPython the situation is different. Most microcontroller boards
|
||||
implementing MicroPython do not have threading support or executors, so ``def``
|
||||
handler functions in this platform can only run in the main and only thread.
|
||||
These functions will block the asynchronous loop when they take too long to
|
||||
complete so ``async def`` handlers properly written to allow other handlers to
|
||||
run in parallel should be preferred.
|
||||
|
||||
36
docs/users-guide/concurrency.rst
Normal file
36
docs/users-guide/concurrency.rst
Normal file
@@ -0,0 +1,36 @@
|
||||
Concurrency
|
||||
~~~~~~~~~~~
|
||||
|
||||
Microdot implements concurrency through the ``asyncio`` package, which means
|
||||
that applications must be careful to prevent blocking in their handlers.
|
||||
|
||||
"async def" handlers
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The recommendation for route handlers in Microdot is to use asynchronous
|
||||
functions, declared as ``async def``. Microdot executes these handler
|
||||
functions as native asynchronous tasks. The standard considerations for writing
|
||||
asynchronous code apply, and in particular blocking calls should be avoided to
|
||||
ensure the application runs smoothly and is always responsive.
|
||||
|
||||
"def" handlers
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
Microdot also supports the use of synchronous route handlers, declared as
|
||||
standard ``def`` functions. These handlers are handled differently under
|
||||
CPython and MicroPython.
|
||||
|
||||
When running on CPython, Microdot executes synchronous handlers in a
|
||||
`thread executor <https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor>`_,
|
||||
which uses a thread pool. The use of blocking or CPU intensive code in these
|
||||
handlers does not have such a negative effect on the application, because
|
||||
handlers do not run on the same thread as the asynchronous loop. On the other
|
||||
hand, the application will be affected by threading issues such as those caused
|
||||
by the Global Interpreter Lock.
|
||||
|
||||
Under MicroPython the situation is different. Most microcontroller boards
|
||||
do not have or have very limited threading support, so Microdot executes
|
||||
synchronous handlers in the main and often only thread available. This means
|
||||
that these functions will block the asynchronous loop when they take too long
|
||||
to complete. The use of properly written asynchronous handlers should be
|
||||
preferred.
|
||||
378
docs/users-guide/defining-routes.rst
Normal file
378
docs/users-guide/defining-routes.rst
Normal file
@@ -0,0 +1,378 @@
|
||||
Defining Routes
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
In Microdot, routes define the logic of the web application.
|
||||
|
||||
The route decorator
|
||||
^^^^^^^^^^^^^^^^^^^
|
||||
The :func:`route() <microdot.Microdot.route>` decorator is used to associate an
|
||||
application URL with the function that handles it. The only required argument
|
||||
to the decorator is the path portion of the URL.
|
||||
|
||||
The following example creates a route for the root URL of the application::
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
return 'Hello, world!'
|
||||
|
||||
When a client requests the root URL (for example, *http://localhost:5000/*),
|
||||
Microdot will call the ``index()`` function, passing it a
|
||||
:class:`Request <microdot.Request>` object. The return value of the function
|
||||
is the response that is sent to the client.
|
||||
|
||||
Below is another example, this one with a route for a URL with two components
|
||||
in its path::
|
||||
|
||||
@app.route('/users/active')
|
||||
async def active_users(request):
|
||||
return 'Active users: Susan, Joe, and Bob'
|
||||
|
||||
The complete URL that maps to this route is
|
||||
*http://localhost:5000/users/active*.
|
||||
|
||||
An application can define multiple routes. Microdot uses the path portion of
|
||||
the URL to determine the correct route function to call for each incoming
|
||||
request.
|
||||
|
||||
Choosing the HTTP Method
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
All the example routes shown above are associated with ``GET`` requests, which
|
||||
are the default. Applications often need to define routes for other HTTP
|
||||
methods, such as ``POST``, ``PUT``, ``PATCH`` and ``DELETE``. The ``route()``
|
||||
decorator takes a ``methods`` optional argument, in which the application can
|
||||
provide a list of HTTP methods that the route should be associated with on the
|
||||
given path.
|
||||
|
||||
The following example defines a route that handles ``GET`` and ``POST``
|
||||
requests within the same function::
|
||||
|
||||
@app.route('/invoices', methods=['GET', 'POST'])
|
||||
async def invoices(request):
|
||||
if request.method == 'GET':
|
||||
return 'get invoices'
|
||||
elif request.method == 'POST':
|
||||
return 'create an invoice'
|
||||
|
||||
As an alternative to the example above, in which a single function is used to
|
||||
handle multiple HTTP methods, sometimes it may be desirable to write a separate
|
||||
function for each HTTP method. The above example can be implemented with two
|
||||
routes as follows::
|
||||
|
||||
@app.route('/invoices', methods=['GET'])
|
||||
async def get_invoices(request):
|
||||
return 'get invoices'
|
||||
|
||||
@app.route('/invoices', methods=['POST'])
|
||||
async def create_invoice(request):
|
||||
return 'create an invoice'
|
||||
|
||||
Microdot provides the :func:`get() <microdot.Microdot.get>`,
|
||||
:func:`post() <microdot.Microdot.post>`, :func:`put() <microdot.Microdot.put>`,
|
||||
:func:`patch() <microdot.Microdot.patch>`, and
|
||||
:func:`delete() <microdot.Microdot.delete>` decorators as shortcuts for the
|
||||
corresponding HTTP methods. The two example routes above can be written more
|
||||
concisely with them::
|
||||
|
||||
@app.get('/invoices')
|
||||
async def get_invoices(request):
|
||||
return 'get invoices'
|
||||
|
||||
@app.post('/invoices')
|
||||
async def create_invoice(request):
|
||||
return 'create an invoice'
|
||||
|
||||
Including Dynamic Components in the URL Path
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The examples shown above all use hardcoded URL paths. Microdot also supports
|
||||
the definition of routes that have dynamic components in the path. For example,
|
||||
the following route associates all URLs that have a path following the pattern
|
||||
*http://localhost:5000/users/<username>* with the ``get_user()`` function::
|
||||
|
||||
@app.get('/users/<username>')
|
||||
async def get_user(request, username):
|
||||
return 'User: ' + username
|
||||
|
||||
As shown in the example, a path component that is enclosed in angle brackets
|
||||
is considered a placeholder. Microdot accepts any values for that portion of
|
||||
the URL path, and passes the value received to the function as an argument
|
||||
after the request object.
|
||||
|
||||
Routes are not limited to a single dynamic component. The following route shows
|
||||
how multiple dynamic components can be included in the path::
|
||||
|
||||
@app.get('/users/<firstname>/<lastname>')
|
||||
async def get_user(request, firstname, lastname):
|
||||
return 'User: ' + firstname + ' ' + lastname
|
||||
|
||||
Dynamic path components are considered to be strings by default. An explicit
|
||||
type can be specified as a prefix, separated from the dynamic component name by
|
||||
a colon. The following route has two dynamic components declared as an integer
|
||||
and a string respectively::
|
||||
|
||||
@app.get('/users/<int:id>/<string:username>')
|
||||
async def get_user(request, id, username):
|
||||
return 'User: ' + username + ' (' + str(id) + ')'
|
||||
|
||||
If a dynamic path component is defined as an integer, the value passed to the
|
||||
route function is also an integer. If the client sends a value that is not an
|
||||
integer in the corresponding section of the URL path, then the URL will not
|
||||
match and the route will not be called.
|
||||
|
||||
A special type ``path`` can be used to capture the remainder of the path as a
|
||||
single argument. The difference between an argument of type ``path`` and one of
|
||||
type ``string`` is that the latter stops capturing when a ``/`` appears in the
|
||||
URL::
|
||||
|
||||
@app.get('/tests/<path:path>')
|
||||
async def get_test(request, path):
|
||||
return 'Test: ' + path
|
||||
|
||||
The ``re`` type allows the application to provide a custom regular expression
|
||||
for the dynamic component. The next example defines a route that only matches
|
||||
usernames that begin with an upper or lower case letter, followed by a sequence
|
||||
of letters or numbers::
|
||||
|
||||
@app.get('/users/<re:[a-zA-Z][a-zA-Z0-9]*:username>')
|
||||
async def get_user(request, username):
|
||||
return 'User: ' + username
|
||||
|
||||
The ``re`` type returns the URL component as a string, which sometimes may not
|
||||
be the most convenient. To convert a path component to something more
|
||||
meaningful than a string, the application can register a custom URL component
|
||||
type and provide a parser function that performs the conversion. In the
|
||||
following example, a ``hex`` custom type is registered to automatically
|
||||
convert hex numbers given in the path to numbers::
|
||||
|
||||
from microdot import URLPattern
|
||||
|
||||
URLPattern.register_type('hex', parser=lambda value: int(value, 16))
|
||||
|
||||
@app.get('/users/<hex:user_id>')
|
||||
async def get_user(request, user_id):
|
||||
user = get_user_by_id(user_id)
|
||||
# ...
|
||||
|
||||
In addition to the parser, the custom URL component can include a pattern,
|
||||
given as a regular expression. When a pattern is provided, the URL component
|
||||
will only match if the regular expression matches the value passed in the URL.
|
||||
The ``hex`` example above can be expanded with a pattern as follows::
|
||||
|
||||
URLPattern.register_type('hex', pattern='[0-9a-fA-F]+',
|
||||
parser=lambda value: int(value, 16))
|
||||
|
||||
In cases where a pattern isn't provided, or when the pattern is unable to
|
||||
filter out all invalid values, the parser function can return ``None`` to
|
||||
indicate a failed match. The next example shows how the parser for the ``hex``
|
||||
type can be expanded to do that::
|
||||
|
||||
def hex_parser(value):
|
||||
try:
|
||||
return int(value, 16)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
URLPattern.register_type('hex', parser=hex_parser)
|
||||
|
||||
.. note::
|
||||
Dynamic path components are passed to route functions as keyword arguments,
|
||||
so the names of the function arguments must match the names declared in the
|
||||
path specification.
|
||||
|
||||
Before and After Request Handlers
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
It is common for applications to need to perform one or more actions before a
|
||||
request is handled. Examples include authenticating and/or authorizing the
|
||||
client, opening a connection to a database, or checking if the requested
|
||||
resource can be obtained from a cache. The
|
||||
:func:`before_request() <microdot.Microdot.before_request>` decorator registers
|
||||
a function to be called before the request is dispatched to the route function.
|
||||
|
||||
The following example registers a before-request handler that ensures that the
|
||||
client is authenticated before the request is handled::
|
||||
|
||||
@app.before_request
|
||||
async def authenticate(request):
|
||||
user = authorize(request)
|
||||
if not user:
|
||||
return 'Unauthorized', 401
|
||||
request.g.user = user
|
||||
|
||||
Before-request handlers receive the request object as an argument. If the
|
||||
function returns a value, Microdot sends it to the client as the response, and
|
||||
does not invoke the route function. This gives before-request handlers the
|
||||
power to intercept a request if necessary. The example above uses this
|
||||
technique to prevent an unauthorized user from accessing the requested
|
||||
route.
|
||||
|
||||
After-request handlers registered with the
|
||||
:func:`after_request() <microdot.Microdot.after_request>` decorator are called
|
||||
after the route function returns a response. Their purpose is to perform any
|
||||
common closing or cleanup tasks. The next example shows a combination of
|
||||
before- and after-request handlers that print the time it takes for a request
|
||||
to be handled::
|
||||
|
||||
@app.before_request
|
||||
async def start_timer(request):
|
||||
request.g.start_time = time.time()
|
||||
|
||||
@app.after_request
|
||||
async def end_timer(request, response):
|
||||
duration = time.time() - request.g.start_time
|
||||
print(f'Request took {duration:0.2f} seconds')
|
||||
|
||||
After-request handlers receive the request and response objects as arguments,
|
||||
and they can return a modified response object to replace the original. If
|
||||
no value is returned from an after-request handler, then the original response
|
||||
object is used.
|
||||
|
||||
The after-request handlers are only invoked for successful requests. The
|
||||
:func:`after_error_request() <microdot.Microdot.after_error_request>`
|
||||
decorator can be used to register a function that is called after an error
|
||||
occurs. The function receives the request and the error response and is
|
||||
expected to return an updated response object after performing any necessary
|
||||
cleanup.
|
||||
|
||||
.. note::
|
||||
The :ref:`request.g <The "g" Object>` object used in many of the above
|
||||
examples is a special object that allows the before- and after-request
|
||||
handlers, as well as the route function to share data during the life of the
|
||||
request.
|
||||
|
||||
Error Handlers
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
When an error occurs during the handling of a request, Microdot ensures that
|
||||
the client receives an appropriate error response. Some of the common errors
|
||||
automatically handled by Microdot are:
|
||||
|
||||
- 400 for malformed requests.
|
||||
- 404 for URLs that are unknown.
|
||||
- 405 for URLs that are known, but not implemented for the requested HTTP
|
||||
method.
|
||||
- 413 for requests that are larger than the allowed size.
|
||||
- 500 when the application raises an unhandled exception.
|
||||
|
||||
While the above errors are fully complaint with the HTTP specification, the
|
||||
application might want to provide custom responses for them. The
|
||||
:func:`errorhandler() <microdot.Microdot.errorhandler>` decorator registers
|
||||
functions to respond to specific error codes. The following example shows a
|
||||
custom error handler for 404 errors::
|
||||
|
||||
@app.errorhandler(404)
|
||||
async def not_found(request):
|
||||
return {'error': 'resource not found'}, 404
|
||||
|
||||
The ``errorhandler()`` decorator has a second form, in which it takes an
|
||||
exception class as an argument. Microdot will invoke the handler when an
|
||||
unhandled exception that is an instance of the given class is raised. The next
|
||||
example provides a custom response for division by zero errors::
|
||||
|
||||
@app.errorhandler(ZeroDivisionError)
|
||||
async def division_by_zero(request, exception):
|
||||
return {'error': 'division by zero'}, 500
|
||||
|
||||
When the raised exception class does not have an error handler defined, but
|
||||
one or more of its parent classes do, Microdot makes an attempt to invoke the
|
||||
most specific handler.
|
||||
|
||||
Mounting a Sub-Application
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Small Microdot applications can be written as a single source file, but this
|
||||
is not the best option for applications that pass a certain size. To make it
|
||||
simpler to write large applications, Microdot supports the concept of
|
||||
sub-applications that can be "mounted" on a larger application, possibly with
|
||||
a common URL prefix applied to all of its routes. For developers familiar with
|
||||
the Flask framework, this is a similar concept to Flask's blueprints.
|
||||
|
||||
Consider, for example, a *customers.py* sub-application that implements
|
||||
operations on customers::
|
||||
|
||||
from microdot import Microdot
|
||||
|
||||
customers_app = Microdot()
|
||||
|
||||
@customers_app.get('/')
|
||||
async def get_customers(request):
|
||||
# return all customers
|
||||
|
||||
@customers_app.post('/')
|
||||
async def new_customer(request):
|
||||
# create a new customer
|
||||
|
||||
Similar to the above, the *orders.py* sub-application implements operations on
|
||||
customer orders::
|
||||
|
||||
from microdot import Microdot
|
||||
|
||||
orders_app = Microdot()
|
||||
|
||||
@orders_app.get('/')
|
||||
async def get_orders(request):
|
||||
# return all orders
|
||||
|
||||
@orders_app.post('/')
|
||||
async def new_order(request):
|
||||
# create a new order
|
||||
|
||||
Now the main application, which is stored in *main.py*, can import and mount
|
||||
the sub-applications to build the larger combined application::
|
||||
|
||||
from microdot import Microdot
|
||||
from customers import customers_app
|
||||
from orders import orders_app
|
||||
|
||||
def create_app():
|
||||
app = Microdot()
|
||||
app.mount(customers_app, url_prefix='/customers')
|
||||
app.mount(orders_app, url_prefix='/orders')
|
||||
return app
|
||||
|
||||
app = create_app()
|
||||
app.run()
|
||||
|
||||
The resulting application will have the customer endpoints available at
|
||||
*/customers/* and the order endpoints available at */orders/*.
|
||||
|
||||
.. note::
|
||||
During the handling of a request, the
|
||||
:attr:`Request.url_prefix <microdot.Microdot.url_prefix>` attribute is
|
||||
set to the URL prefix under which the sub-application was mounted, or an
|
||||
empty string if the endpoint did not come from a sub-application or the
|
||||
sub-application was mounted without a URL prefix. It is possible to issue a
|
||||
redirect that is relative to the sub-application as follows::
|
||||
|
||||
return redirect(request.url_prefix + '/relative-url')
|
||||
|
||||
When mounting an application as shown above, before-request, after-request and
|
||||
error handlers defined in the sub-application are copied over to the main
|
||||
application at mount time. Once installed in the main application, these
|
||||
handlers will apply to the whole application and not just the sub-application
|
||||
in which they were created.
|
||||
|
||||
The :func:`mount() <microdot.Microdot.mount>` method has a ``local`` argument
|
||||
that defaults to ``False``. When this argument is set to ``True``, the
|
||||
before-request, after-request and error handlers defined in the sub-application
|
||||
will only apply to the sub-application.
|
||||
|
||||
Shutting Down the Server
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Web servers are designed to run forever, and are often stopped by sending them
|
||||
an interrupt signal. But having a way to gracefully stop the server is
|
||||
sometimes useful, especially in testing environments. Microdot provides a
|
||||
:func:`shutdown() <microdot.Microdot.shutdown>` method that can be invoked
|
||||
during the handling of a route to gracefully shut down the server when that
|
||||
request completes. The next example shows how to use this feature::
|
||||
|
||||
@app.get('/shutdown')
|
||||
async def shutdown(request):
|
||||
request.app.shutdown()
|
||||
return 'The server is shutting down...'
|
||||
|
||||
The request that invokes the ``shutdown()`` method will complete, and then the
|
||||
server will not accept any new requests and stop once any remaining requests
|
||||
complete. At this point the ``app.run()`` call will return.
|
||||
18
docs/users-guide/index.rst
Normal file
18
docs/users-guide/index.rst
Normal file
@@ -0,0 +1,18 @@
|
||||
User's Guide
|
||||
------------
|
||||
|
||||
This section describes the main features of Microdot.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
intro
|
||||
defining-routes
|
||||
request-object
|
||||
responses
|
||||
concurrency
|
||||
|
||||
For detailed reference information, consult the :ref:`API Reference`.
|
||||
|
||||
If you are familiar with releases of Microdot before 2.x, review the
|
||||
:ref:`Migration Guide <Migrating to Microdot 2.x from Older Releases>`.
|
||||
160
docs/users-guide/intro.rst
Normal file
160
docs/users-guide/intro.rst
Normal file
@@ -0,0 +1,160 @@
|
||||
Introduction
|
||||
~~~~~~~~~~~~
|
||||
|
||||
This section covers how to create and run a basic Microdot web application.
|
||||
|
||||
A simple web server
|
||||
^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The following is an example of a simple web server::
|
||||
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
return 'Hello, world!'
|
||||
|
||||
app.run()
|
||||
|
||||
The script imports the :class:`Microdot <microdot.Microdot>` class and creates
|
||||
an application instance from it.
|
||||
|
||||
The application instance provides a :func:`route() <microdot.Microdot.route>`
|
||||
decorator, which is used to define one or more routes, as needed by the
|
||||
application.
|
||||
|
||||
The ``route()`` decorator takes the path portion of the URL as an
|
||||
argument, and maps it to the decorated function, so that the function is called
|
||||
when the client requests the URL.
|
||||
|
||||
When the function is called, it is passed a :class:`Request <microdot.Request>`
|
||||
object as an argument, which provides access to the information passed by the
|
||||
client. The value returned by the function is sent back to the client as the
|
||||
response.
|
||||
|
||||
Microdot is an asynchronous framework that uses the ``asyncio`` package. Route
|
||||
handler functions can be defined as ``async def`` or ``def`` functions, but
|
||||
``async def`` functions are recommended for performance.
|
||||
|
||||
The :func:`run() <microdot.Microdot.run>` method starts the application's web
|
||||
server on port 5000 by default, and creates its own asynchronous loop. This
|
||||
method blocks while it waits for connections from clients.
|
||||
|
||||
For some applications it may be necessary to run the web server alongside other
|
||||
asynchronous tasks, on an already running loop. In that case, instead of
|
||||
``app.run()`` the web server can be started by invoking the
|
||||
:func:`start_server() <microdot.Microdot.start_server>` coroutine as shown in
|
||||
the following example::
|
||||
|
||||
import asyncio
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
return 'Hello, world!'
|
||||
|
||||
async def main():
|
||||
# start the server in a background task
|
||||
server = asyncio.create_task(app.start_server())
|
||||
|
||||
# ... do other asynchronous work here ...
|
||||
|
||||
# cleanup before ending the application
|
||||
await server
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
Running with CPython
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `microdot.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/microdot.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello.py>`_
|
||||
|
||||
When using CPython, you can start the web server by running the script that
|
||||
has the ``app.run()`` call at the bottom::
|
||||
|
||||
python main.py
|
||||
|
||||
After starting the script, open a web browser and navigate to
|
||||
*http://localhost:5000/* to access the application at the default address for
|
||||
the Microdot web server. From other computers in the same network, use the IP
|
||||
address or hostname of the computer running the script instead of
|
||||
``localhost``.
|
||||
|
||||
Running with MicroPython
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. list-table::
|
||||
:align: left
|
||||
|
||||
* - Required Microdot source files
|
||||
- | `microdot.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/microdot.py>`_
|
||||
|
||||
* - Required external dependencies
|
||||
- | None
|
||||
|
||||
* - Examples
|
||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello.py>`_
|
||||
| `gpio.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/gpio/gpio.py>`_
|
||||
|
||||
When using MicroPython, you can upload a *main.py* file containing the web
|
||||
server code to your device, along with the required Microdot files, as defined
|
||||
in the :ref:`MicroPython Installation` section.
|
||||
|
||||
MicroPython will automatically run *main.py* when the device is powered on, so
|
||||
the web server will automatically start. The application can be accessed on
|
||||
port 5000 at the device's IP address. As indicated above, the port can be
|
||||
changed by passing the ``port`` argument to the ``run()`` method.
|
||||
|
||||
.. note::
|
||||
Microdot does not configure the network interface of the device in which it
|
||||
is running. If your device requires a network connection to be made in
|
||||
advance, for example to a Wi-Fi access point, this must be configured before
|
||||
the ``run()`` method is invoked.
|
||||
|
||||
Web Server Configuration
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The :func:`run() <microdot.Microdot.run>` and
|
||||
:func:`start_server() <microdot.Microdot.start_server>` methods support a few
|
||||
arguments to configure the web server.
|
||||
|
||||
- ``port``: The port number to listen on. Pass the desired port number in this
|
||||
argument to use a port different than the default of 5000. For example::
|
||||
|
||||
app.run(port=6000)
|
||||
|
||||
- ``host``: The IP address of the network interface to listen on. By default
|
||||
the server listens on all available interfaces. To listen only on the local
|
||||
loopback interface, pass ``'127.0.0.1'`` as value for this argument.
|
||||
- ``debug``: when set to ``True``, the server ouputs logging information to the
|
||||
console. The default is ``False``.
|
||||
- ``ssl``: an ``SSLContext`` instance that configures the server to use TLS
|
||||
encryption, or ``None`` to disable TLS use. The default is ``None``. The
|
||||
following example demonstrates how to configure the server with an SSL
|
||||
certificate stored in *cert.pem* and *key.pem* files::
|
||||
|
||||
import ssl
|
||||
|
||||
# ...
|
||||
|
||||
sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
sslctx.load_cert_chain('cert.pem', 'key.pem')
|
||||
app.run(port=4443, debug=True, ssl=sslctx)
|
||||
|
||||
.. note::
|
||||
When using CPython, the certificate and key files must be given in PEM
|
||||
format. When using MicroPython, these files must be given in DER format.
|
||||
169
docs/users-guide/request-object.rst
Normal file
169
docs/users-guide/request-object.rst
Normal file
@@ -0,0 +1,169 @@
|
||||
The Request Object
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The :class:`Request <microdot.Request>` object encapsulates all the information
|
||||
passed by the client. It is passed as an argument to route handlers, as well as
|
||||
to before-request, after-request and error handlers.
|
||||
|
||||
Request Attributes
|
||||
^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The request object provides access to the request attributes, including:
|
||||
|
||||
- :attr:`method <microdot.Request.method>`: The HTTP method of the request.
|
||||
- :attr:`path <microdot.Request.path>`: The path of the request.
|
||||
- :attr:`args <microdot.Request.args>`: The query string parameters of the
|
||||
request, as a :class:`MultiDict <microdot.MultiDict>` object.
|
||||
- :attr:`headers <microdot.Request.headers>`: The headers of the request, as a
|
||||
dictionary.
|
||||
- :attr:`cookies <microdot.Request.cookies>`: The cookies that the client sent
|
||||
with the request, as a dictionary.
|
||||
- :attr:`content_type <microdot.Request.content_type>`: The content type
|
||||
specified by the client, or ``None`` if no content type was specified.
|
||||
- :attr:`content_length <microdot.Request.content_length>`: The content
|
||||
length of the request, or 0 if no content length was specified.
|
||||
- :attr:`json <microdot.Request.json>`: The parsed JSON data in the request
|
||||
body. See :ref:`below <JSON Payloads>` for additional details.
|
||||
- :attr:`form <microdot.Request.form>`: The parsed form data in the request
|
||||
body, as a dictionary. See :ref:`below <Form Data>` for additional details.
|
||||
- :attr:`files <microdot.Request.files>`: A dictionary with the file uploads
|
||||
included in the request body. Note that file uploads are only supported when
|
||||
the :ref:`Multipart Forms` extension is used.
|
||||
- :attr:`client_addr <microdot.Request.client_addr>`: The network address of
|
||||
the client, as a tuple (host, port).
|
||||
- :attr:`app <microdot.Request.app>`: The application instance that created the
|
||||
request.
|
||||
- :attr:`g <microdot.Request.g>`: The ``g`` object, where handlers can store
|
||||
request-specific data to be shared among handlers. See :ref:`The "g" Object`
|
||||
for details.
|
||||
|
||||
JSON Payloads
|
||||
^^^^^^^^^^^^^
|
||||
|
||||
When the client sends a request that contains JSON data in the body, the
|
||||
application can access the parsed JSON data using the
|
||||
:attr:`json <microdot.Request.json>` attribute. The following example shows how
|
||||
to use this attribute::
|
||||
|
||||
@app.post('/customers')
|
||||
async def create_customer(request):
|
||||
customer = request.json
|
||||
# do something with customer
|
||||
return {'success': True}
|
||||
|
||||
.. note::
|
||||
The client must set the ``Content-Type`` header to ``application/json`` for
|
||||
the ``json`` attribute of the request object to be populated.
|
||||
|
||||
Form Data
|
||||
^^^^^^^^^
|
||||
|
||||
The request object also supports standard HTML form submissions through the
|
||||
:attr:`form <microdot.Request.form>` attribute, which presents the form data
|
||||
as a :class:`MultiDict <microdot.MultiDict>` object. Example::
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
async def index(req):
|
||||
name = 'Unknown'
|
||||
if req.method == 'POST':
|
||||
name = req.form.get('name')
|
||||
return f'Hello {name}'
|
||||
|
||||
.. note::
|
||||
Form submissions automatically parsed when the ``Content-Type`` header is
|
||||
set by the client to ``application/x-www-form-urlencoded``. For form
|
||||
submissions that use the ``multipart/form-data`` content type the
|
||||
:ref:`Multipart Forms` extension must be used.
|
||||
|
||||
Accessing the Raw Request Body
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
For cases in which neither JSON nor form data is expected, the
|
||||
:attr:`body <microdot.Request.body>` request attribute returns the entire body
|
||||
of the request as a byte sequence.
|
||||
|
||||
If the expected body is too large to fit safely in memory, the application can
|
||||
use the :attr:`stream <microdot.Request.stream>` request attribute to read the
|
||||
body contents as a file-like object. The
|
||||
:attr:`max_body_length <microdot.Request.max_body_length>` attribute of the
|
||||
request object defines the size at which bodies are streamed instead of loaded
|
||||
into memory.
|
||||
|
||||
Cookies
|
||||
^^^^^^^
|
||||
|
||||
Cookies that are sent by the client are made available through the
|
||||
:attr:`cookies <microdot.Request.cookies>` attribute of the request object in
|
||||
dictionary form.
|
||||
|
||||
The "g" Object
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
Sometimes applications need to store data during the lifetime of a request, so
|
||||
that it can be shared between the before- and after-request handlers, the
|
||||
route function and any error handlers. The request object provides the
|
||||
:attr:`g <microdot.Request.g>` attribute for that purpose.
|
||||
|
||||
In the following example, a before request handler authorizes the client and
|
||||
stores the username so that the route function can use it::
|
||||
|
||||
@app.before_request
|
||||
async def authorize(request):
|
||||
username = authenticate_user(request)
|
||||
if not username:
|
||||
return 'Unauthorized', 401
|
||||
request.g.username = username
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return f'Hello, {request.g.username}!'
|
||||
|
||||
Request-Specific After-Request Handlers
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Sometimes applications need to perform operations on the response object
|
||||
before it is sent to the client, for example to set or remove a cookie. A good
|
||||
option to use for this is to define a request-specific after-request handler
|
||||
using the :func:`after_request <microdot.Microdot.after_request>` decorator.
|
||||
Request-specific after-request handlers are called by Microdot after the route
|
||||
function returns and all the application-wide after-request handlers have been
|
||||
called.
|
||||
|
||||
The next example shows how a cookie can be updated using a request-specific
|
||||
after-request handler defined inside a route function::
|
||||
|
||||
@app.post('/logout')
|
||||
async def logout(request):
|
||||
@request.after_request
|
||||
def reset_session(request, response):
|
||||
response.set_cookie('session', '', http_only=True)
|
||||
return response
|
||||
|
||||
return 'Logged out'
|
||||
|
||||
Request Limits
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
To help prevent malicious attacks, Microdot provides some configuration options
|
||||
to limit the amount of information that is accepted:
|
||||
|
||||
- :attr:`max_content_length <microdot.Request.max_content_length>`: The
|
||||
maximum size accepted for the request body, in bytes. When a client sends a
|
||||
request that is larger than this, the server will respond with a 413 error.
|
||||
The default is 16KB.
|
||||
- :attr:`max_body_length <microdot.Request.max_body_length>`: The maximum
|
||||
size that is loaded in the :attr:`body <microdot.Request.body>` attribute, in
|
||||
bytes. Requests that have a body that is larger than this size but smaller
|
||||
than the size set for ``max_content_length`` can only be accessed through the
|
||||
:attr:`stream <microdot.Request.stream>` attribute. The default is also 16KB.
|
||||
- :attr:`max_readline <microdot.Request.max_readline>`: The maximum allowed
|
||||
size for a request line, in bytes. The default is 2KB.
|
||||
|
||||
The following example configures the application to accept requests with
|
||||
payloads up to 1MB in size, but prevents requests that are larger than 8KB from
|
||||
being loaded into memory::
|
||||
|
||||
from microdot import Request
|
||||
|
||||
Request.max_content_length = 1024 * 1024
|
||||
Request.max_body_length = 8 * 1024
|
||||
200
docs/users-guide/responses.rst
Normal file
200
docs/users-guide/responses.rst
Normal file
@@ -0,0 +1,200 @@
|
||||
Responses
|
||||
~~~~~~~~~
|
||||
|
||||
The value or values that are returned from the route function are used by
|
||||
Microdot to build the response that is sent to the client. The following
|
||||
sections describe the different types of responses that are supported.
|
||||
|
||||
The Three Parts of a Response
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Route functions can return one, two or three values. The first and most
|
||||
important value is the response body::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return 'Hello, World!'
|
||||
|
||||
In the above example, Microdot issues a standard 200 status code response
|
||||
indicating a successful request. The body of the response is the
|
||||
``'Hello, World!'`` string returned by the function. Microdot includes default
|
||||
headers with this response, including the ``Content-Type`` header set to
|
||||
``text/plain`` to indicate a response in plain text.
|
||||
|
||||
The application can provide its own status code as a second value returned from
|
||||
the route to override the 200 default. The example below returns a 202 status
|
||||
code::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return 'Hello, World!', 202
|
||||
|
||||
The application can also return a third value, a dictionary with additional
|
||||
headers that are added to, or replace the default ones included by Microdot.
|
||||
The next example returns an HTML response, instead of the default plain text
|
||||
response::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return '<h1>Hello, World!</h1>', 202, {'Content-Type': 'text/html'}
|
||||
|
||||
If the application does not need to return a body, then it can omit it and
|
||||
have the status code as the first or only returned value::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return 204
|
||||
|
||||
Likewise, if the application needs to return a body and custom headers, but
|
||||
does not need to change the default status code, then it can return two values,
|
||||
omitting the status code::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return '<h1>Hello, World!</h1>', {'Content-Type': 'text/html'}
|
||||
|
||||
Lastly, the application can also return a :class:`Response <microdot.Response>`
|
||||
object containing all the details of the response as a single value.
|
||||
|
||||
JSON Responses
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
If the application needs to return a response with JSON formatted data, it can
|
||||
return a dictionary or a list as the first value, and Microdot will
|
||||
automatically format the response as JSON.
|
||||
|
||||
Example::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return {'hello': 'world'}
|
||||
|
||||
.. note::
|
||||
A ``Content-Type`` header set to ``application/json`` is automatically added
|
||||
to the response.
|
||||
|
||||
Redirects
|
||||
^^^^^^^^^
|
||||
|
||||
The :func:`redirect <microdot.Response.redirect>` function is a helper that
|
||||
creates redirect responses::
|
||||
|
||||
from microdot import redirect
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return redirect('/about')
|
||||
|
||||
File Responses
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
The :func:`send_file <microdot.Response.send_file>` function builds a response
|
||||
object for a file::
|
||||
|
||||
from microdot import send_file
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return send_file('/static/index.html')
|
||||
|
||||
A suggested caching duration can be returned to the client in the ``max_age``
|
||||
argument::
|
||||
|
||||
from microdot import send_file
|
||||
|
||||
@app.get('/')
|
||||
async def image(request):
|
||||
return send_file('/static/image.jpg', max_age=3600) # in seconds
|
||||
|
||||
.. note::
|
||||
Unlike other web frameworks, Microdot does not automatically configure a
|
||||
route to serve static files. The following is an example route that can be
|
||||
added to the application to serve static files from a *static* directory in
|
||||
the project::
|
||||
|
||||
@app.route('/static/<path:path>')
|
||||
async def static(request, path):
|
||||
if '..' in path:
|
||||
# directory traversal is not allowed
|
||||
return 'Not found', 404
|
||||
return send_file('static/' + path, max_age=86400)
|
||||
|
||||
Streaming Responses
|
||||
^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Instead of providing a response as a single value, an application can opt to
|
||||
return a response that is generated in chunks, by returning a Python generator.
|
||||
The example below returns all the numbers in the fibonacci sequence below 100::
|
||||
|
||||
@app.get('/fibonacci')
|
||||
async def fibonacci(request):
|
||||
async def generate_fibonacci():
|
||||
a, b = 0, 1
|
||||
while a < 100:
|
||||
yield str(a) + '\n'
|
||||
a, b = b, a + b
|
||||
|
||||
return generate_fibonacci()
|
||||
|
||||
.. note::
|
||||
Under CPython, the generator function can be a ``def`` or ``async def``
|
||||
function, as well as a class-based generator.
|
||||
|
||||
Under MicroPython, asynchronous generator functions are not supported, so
|
||||
only ``def`` generator functions can be used. Asynchronous class-based
|
||||
generators are supported.
|
||||
|
||||
Changing the Default Response Content Type
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Microdot uses a ``text/plain`` content type by default for responses that do
|
||||
not explicitly include the ``Content-Type`` header. The application can change
|
||||
this default by setting the desired content type in the
|
||||
:attr:`default_content_type <microdot.Response.default_content_type>` attribute
|
||||
of the :class:`Response <microdot.Response>` class.
|
||||
|
||||
The example that follows configures the application to use ``text/html`` as
|
||||
default content type::
|
||||
|
||||
from microdot import Response
|
||||
|
||||
Response.default_content_type = 'text/html'
|
||||
|
||||
Setting Cookies
|
||||
^^^^^^^^^^^^^^^
|
||||
|
||||
Many web applications rely on cookies to maintain client state between
|
||||
requests. Cookies can be set with the ``Set-Cookie`` header in the response,
|
||||
but since this is such a common practice, Microdot provides the
|
||||
:func:`set_cookie() <microdot.Response.set_cookie>` method in the response
|
||||
object to add a properly formatted cookie header to the response.
|
||||
|
||||
Given that route functions do not normally work directly with the response
|
||||
object, the recommended way to set a cookie is to do it in a
|
||||
:ref:`request-specific after-request handler <Request-Specific After-Request Handlers>`.
|
||||
|
||||
Example::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
@request.after_request
|
||||
async def set_cookie(request, response):
|
||||
response.set_cookie('name', 'value')
|
||||
return response
|
||||
|
||||
return 'Hello, World!'
|
||||
|
||||
Another option is to create a response object directly in the route function::
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
response = Response('Hello, World!')
|
||||
response.set_cookie('name', 'value')
|
||||
return response
|
||||
|
||||
.. note::
|
||||
Standard cookies do not offer sufficient privacy and security controls, so
|
||||
never store sensitive information in them unless you are adding additional
|
||||
protection mechanisms such as encryption or cryptographic signing. The
|
||||
:ref:`session <Maintaining Secure User Sessions>` extension implements signed
|
||||
cookies that prevent tampering by malicious actors.
|
||||
1
examples/auth/README.md
Normal file
1
examples/auth/README.md
Normal file
@@ -0,0 +1 @@
|
||||
This directory contains examples that demonstrate basic and token authentication.
|
||||
31
examples/auth/basic_auth.py
Normal file
31
examples/auth/basic_auth.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from microdot import Microdot
|
||||
from microdot.auth import BasicAuth
|
||||
from pbkdf2 import generate_password_hash, check_password_hash
|
||||
|
||||
|
||||
# this example provides an implementation of the generate_password_hash and
|
||||
# check_password_hash functions that can be used in MicroPython. On CPython
|
||||
# there are many other options for password hashisng so there is no need to use
|
||||
# this custom solution.
|
||||
USERS = {
|
||||
'susan': generate_password_hash('hello'),
|
||||
'david': generate_password_hash('bye'),
|
||||
}
|
||||
app = Microdot()
|
||||
auth = BasicAuth()
|
||||
|
||||
|
||||
@auth.authenticate
|
||||
async def check_credentials(request, username, password):
|
||||
if username in USERS and check_password_hash(USERS[username], password):
|
||||
return username
|
||||
|
||||
|
||||
@app.route('/')
|
||||
@auth
|
||||
async def index(request):
|
||||
return f'Hello, {request.g.current_user}!'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
47
examples/auth/pbkdf2.py
Normal file
47
examples/auth/pbkdf2.py
Normal file
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
import hashlib
|
||||
|
||||
# PBKDF2 secure password hashing algorithm obtained from:
|
||||
# https://codeandlife.com/2023/01/06/how-to-calculate-pbkdf2-hmac-sha256-with-
|
||||
# python,-example-code/
|
||||
|
||||
|
||||
def sha256(b):
|
||||
return hashlib.sha256(b).digest()
|
||||
|
||||
|
||||
def ljust(b, n, f):
|
||||
return b + f * (n - len(b))
|
||||
|
||||
|
||||
def gethmac(key, content):
|
||||
okeypad = bytes(v ^ 0x5c for v in ljust(key, 64, b'\0'))
|
||||
ikeypad = bytes(v ^ 0x36 for v in ljust(key, 64, b'\0'))
|
||||
return sha256(okeypad + sha256(ikeypad + content))
|
||||
|
||||
|
||||
def pbkdf2(pwd, salt, iterations=1000):
|
||||
U = salt + b'\x00\x00\x00\x01'
|
||||
T = bytes(64)
|
||||
for _ in range(iterations):
|
||||
U = gethmac(pwd, U)
|
||||
T = bytes(a ^ b for a, b in zip(U, T))
|
||||
return T
|
||||
|
||||
|
||||
# The number of iterations may need to be adjusted depending on the hardware.
|
||||
# Lower numbers make the password hashing algorithm faster but less secure, so
|
||||
# the largest number that can be tolerated should be used.
|
||||
def generate_password_hash(password, salt=None, iterations=100000):
|
||||
salt = salt or os.urandom(16)
|
||||
dk = pbkdf2(password.encode(), salt, iterations)
|
||||
return f'pbkdf2-hmac-sha256:{salt.hex()}:{iterations}:{dk.hex()}'
|
||||
|
||||
|
||||
def check_password_hash(password_hash, password):
|
||||
algorithm, salt, iterations, dk = password_hash.split(':')
|
||||
iterations = int(iterations)
|
||||
if algorithm != 'pbkdf2-hmac-sha256':
|
||||
return False
|
||||
return pbkdf2(password.encode(), salt=bytes.fromhex(salt),
|
||||
iterations=iterations) == bytes.fromhex(dk)
|
||||
26
examples/auth/token_auth.py
Normal file
26
examples/auth/token_auth.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from microdot import Microdot
|
||||
from microdot.auth import TokenAuth
|
||||
|
||||
app = Microdot()
|
||||
auth = TokenAuth()
|
||||
|
||||
TOKENS = {
|
||||
'susan-token': 'susan',
|
||||
'david-token': 'david',
|
||||
}
|
||||
|
||||
|
||||
@auth.authenticate
|
||||
async def check_token(request, token):
|
||||
if token in TOKENS:
|
||||
return TOKENS[token]
|
||||
|
||||
|
||||
@app.route('/')
|
||||
@auth
|
||||
async def index(request):
|
||||
return f'Hello, {request.g.current_user}!'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
@@ -9,16 +9,14 @@ aiofiles==23.2.1
|
||||
annotated-types==0.6.0
|
||||
# via pydantic
|
||||
anyio==3.7.1
|
||||
# via
|
||||
# fastapi
|
||||
# starlette
|
||||
# via starlette
|
||||
blinker==1.7.0
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
build==1.0.3
|
||||
# via pip-tools
|
||||
certifi==2023.11.17
|
||||
certifi==2024.7.4
|
||||
# via requests
|
||||
charset-normalizer==3.3.2
|
||||
# via requests
|
||||
@@ -28,30 +26,30 @@ click==8.1.7
|
||||
# pip-tools
|
||||
# quart
|
||||
# uvicorn
|
||||
fastapi==0.104.1
|
||||
fastapi==0.109.1
|
||||
# via -r requirements.in
|
||||
flask==3.0.0
|
||||
# via
|
||||
# -r requirements.in
|
||||
# quart
|
||||
gunicorn==21.2.0
|
||||
gunicorn==23.0.0
|
||||
# via -r requirements.in
|
||||
h11==0.14.0
|
||||
h11==0.16.0
|
||||
# via
|
||||
# hypercorn
|
||||
# uvicorn
|
||||
# wsproto
|
||||
h2==4.1.0
|
||||
h2==4.3.0
|
||||
# via hypercorn
|
||||
hpack==4.0.0
|
||||
hpack==4.1.0
|
||||
# via h2
|
||||
humanize==4.9.0
|
||||
# via -r requirements.in
|
||||
hypercorn==0.15.0
|
||||
# via quart
|
||||
hyperframe==6.0.1
|
||||
hyperframe==6.1.0
|
||||
# via h2
|
||||
idna==3.6
|
||||
idna==3.7
|
||||
# via
|
||||
# anyio
|
||||
# requests
|
||||
@@ -59,7 +57,7 @@ itsdangerous==2.1.2
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
jinja2==3.1.2
|
||||
jinja2==3.1.6
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
@@ -84,24 +82,24 @@ pydantic-core==2.14.5
|
||||
# via pydantic
|
||||
pyproject-hooks==1.0.0
|
||||
# via build
|
||||
quart==0.19.4
|
||||
quart==0.20.0
|
||||
# via -r requirements.in
|
||||
requests==2.31.0
|
||||
requests==2.32.4
|
||||
# via -r requirements.in
|
||||
sniffio==1.3.0
|
||||
# via anyio
|
||||
starlette==0.27.0
|
||||
starlette==0.35.1
|
||||
# via fastapi
|
||||
typing-extensions==4.9.0
|
||||
# via
|
||||
# fastapi
|
||||
# pydantic
|
||||
# pydantic-core
|
||||
urllib3==2.1.0
|
||||
urllib3==2.6.0
|
||||
# via requests
|
||||
uvicorn==0.24.0.post1
|
||||
# via -r requirements.in
|
||||
werkzeug==3.0.1
|
||||
werkzeug==3.0.6
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
|
||||
41
examples/csrf/README.md
Normal file
41
examples/csrf/README.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# CSRF Example
|
||||
|
||||
This is a small example that demonstrates how the CSRF protection in Microdot
|
||||
works.
|
||||
|
||||
## Running the example
|
||||
|
||||
Start by cloning the repostory or copying the two example files *app.py* and
|
||||
*evil.py* to your computer. The only dependency these examples need to run is `microdot`, so create a virtual environment and run:
|
||||
|
||||
pip install microdot
|
||||
|
||||
You need two terminals. On the first one, run:
|
||||
|
||||
python app.py
|
||||
|
||||
To see the application open *http://localhost:5000* on your web browser. The
|
||||
application allows you to make payments through a web form. Each payment that
|
||||
you make reduces the balance in your account. Type an amount in the form field and press the "Issue Payment" button to see how the balance decreases.
|
||||
|
||||
Leave the application running. On the second terminal run:
|
||||
|
||||
python evil.py
|
||||
|
||||
Open a second browser tab and navigate to *http://localhost:5001*. This
|
||||
application simulates a malicious web site that tries to steal money from your
|
||||
account. It does this by sending a cross-site form submission to the above
|
||||
application.
|
||||
|
||||
The application presents a form that fools you into thinking you can win some
|
||||
money. Clicking the button triggers the cross-site request to the form in the
|
||||
first application, with the payment amount set to $100.
|
||||
|
||||
Because the application has CSRF protection enabled, the cross-site request
|
||||
fails.
|
||||
|
||||
If you want to see how the attack can succeed, open *app.py* in your editor and
|
||||
comment out the line that creates the ``csrf`` object. Restart *app.py* in your
|
||||
first terminal, then go back to the second browser tab and click the
|
||||
"Win $100!" button again. You will now see that the form is submitted
|
||||
successfully and your balance in the first application is decremented by $100.
|
||||
40
examples/csrf/app.py
Normal file
40
examples/csrf/app.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from microdot import Microdot, redirect
|
||||
from microdot.cors import CORS
|
||||
from microdot.csrf import CSRF
|
||||
|
||||
app = Microdot()
|
||||
cors = CORS(app, allowed_origins=['http://localhost:5000'])
|
||||
csrf = CSRF(app, cors)
|
||||
|
||||
balance = 1000
|
||||
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
def index(request):
|
||||
global balance
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
balance -= float(request.form['amount'])
|
||||
except ValueError:
|
||||
pass
|
||||
return redirect('/')
|
||||
|
||||
page = f'''<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>CSRF Example</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>CSRF Example</h1>
|
||||
<p>You have ${balance:.02f}</p>
|
||||
<form method="POST" action="">
|
||||
Pay $<input type="text" name="amount" size="10" />
|
||||
<input type="submit" value="Issue Payment" />
|
||||
</form>
|
||||
</body>
|
||||
</html>'''
|
||||
return page, {'Content-Type': 'text/html'}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
25
examples/csrf/evil.py
Normal file
25
examples/csrf/evil.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
def index(request):
|
||||
page = '''<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>CSRF Example</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Evil Site</h1>
|
||||
<form method="POST" action="http://localhost:5000">
|
||||
<input type="hidden" name="amount" value="100" />
|
||||
<input type="submit" value="Win $100!" />
|
||||
</form>
|
||||
</body>
|
||||
</html>'''
|
||||
return page, {'Content-Type': 'text/html'}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(port=5001, debug=True)
|
||||
104
examples/gpio/weather/README.md
Normal file
104
examples/gpio/weather/README.md
Normal file
@@ -0,0 +1,104 @@
|
||||
# Microdot Weather Dashboard
|
||||
|
||||
This example reports the temperature and humidity, both as a web application
|
||||
and as a JSON API.
|
||||
|
||||

|
||||
|
||||
## Requirements
|
||||
|
||||
- A microcontroller that supports MicroPython (e.g. ESP8266, ESP32, Raspberry
|
||||
Pi Pico W, etc.)
|
||||
- A DHT22 temperature and humidity sensor
|
||||
- A breadboard and some jumper wires to create the circuit
|
||||
|
||||
## Circuit
|
||||
|
||||
Install the microconller and the DHT22 sensor on different parts of the
|
||||
breadboard. Make the following connections with jumper wires:
|
||||
|
||||
- from a microcontroller power pin (3.3V or 5V) to the left pin of the DHT22
|
||||
sensor.
|
||||
- from a microcontroller `GND` pin to the right pin of the DHT22 sensor.
|
||||
- from any available microcontroller GPIO pin to the middle pin of the DHT22
|
||||
sensor. If the DHT22 sensor has 4 pins instead of 3, use the one on the left,
|
||||
next to the pin receiving power.
|
||||
|
||||
The following diagram shows a possible wiring for this circuit using an ESP8266
|
||||
microcontroller and the 4-pin variant of the DHT22. In this diagram the data
|
||||
pin of the DHT22 sensor is connected to pin `D2` of the ESP8266, which is
|
||||
assigned to GPIO #4. Note that the location of the pins in the microcontroller
|
||||
board will vary depending on which microcontroller you use.
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
Edit *config.py* as follows:
|
||||
|
||||
- Set the `DHT22_PIN` variable to the GPIO pin number connected to the sensor's
|
||||
data pin. Make sure you consult the documentation for your microcontroller to
|
||||
learn what number you should use for your chosen GPIO pin. In the example
|
||||
diagram above, the value should be 4.
|
||||
- Enter your Wi-Fi SSID name and password in this file.
|
||||
|
||||
Install MicroPython on your microcontroller board following instructions on the
|
||||
MicroPython website. Then use a tool such as
|
||||
[rshell](https://github.com/dhylands/rshell) to upload the following files to
|
||||
the board:
|
||||
|
||||
- *main.py*
|
||||
- *config.py*
|
||||
- *index.html*
|
||||
- *microdot.py*
|
||||
|
||||
You can find *microdot.py* in the *src/microdot* directory of this repository.
|
||||
|
||||
If you are using a low end microcontroller such as the ESP8266, it is quite
|
||||
possible that the *microdot.py* file will fail to compile due to the
|
||||
MicroPython compiler needing more RAM than available in the device. In that
|
||||
case, you can install the `mpy-cross` Python package in your computer (same
|
||||
version as your MicroPython firmware) and precompile this file. The precompiled
|
||||
file will have the name *microdot.mpy*. Upload this file and remove
|
||||
*microdot.py* from the device.
|
||||
|
||||
When the device is restarted after the files were uploaded, it will connect to
|
||||
Wi-Fi and then start a web server on port 8000. One way to find out which IP
|
||||
address was assigned to your device is to check your Wi-Fi's router
|
||||
administration panel. Another option is to connect to the MicroPython REPL with
|
||||
`rshell` or any other tool that you like, and then press Ctrl-D at the
|
||||
MicroPython prompt to soft boot the device. The IP address is printed to the
|
||||
terminal on startup.
|
||||
|
||||
You should not upload other *.py* files that exist in this directory to your
|
||||
device. These files are used when running with emulated hardware.
|
||||
|
||||
## Trying out the application
|
||||
|
||||
Once the device is running the server, you can connect to it using a web
|
||||
browser. For example, if your device's Wi-Fi connection was assigned the IP
|
||||
address 192.168.0.145, type *http://192.168.0.45:8000/* in your browser's
|
||||
address bar. Note it is *http://* and not *https://*. This example does not use
|
||||
the TLS/SSL protocol.
|
||||
|
||||
To test the JSON API, you can use `curl` or your favorite HTTP client. The API
|
||||
endpoint uses the */api* path, with the same URL as the main website. Here is
|
||||
an example using `curl`:
|
||||
|
||||
```bash
|
||||
$ curl http://192.168.0.145:8000/api
|
||||
{"temperature": 21.6, "humidity": 58.9, "time": 1752444652}
|
||||
```
|
||||
|
||||
The `temperature` value is given in degrees Celsius. The `humidity` value is
|
||||
given as a percentage. The `time` value is a UNIX timestamp.
|
||||
|
||||
## Running in Emulation mode
|
||||
|
||||
You can run this application on your computer, directly from this directory.
|
||||
When used in this way, the DHT22 hardware is emulated, and the temperature and
|
||||
humidity values are randomly generated.
|
||||
|
||||
The only dependency that is needed for this application to run in emulation
|
||||
mode is `microdot`, so make sure that is installed, or else add a copy of the
|
||||
*microdot.py* from the *src/microdot* directory in this folder.
|
||||
BIN
examples/gpio/weather/circuit.png
Normal file
BIN
examples/gpio/weather/circuit.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 116 KiB |
3
examples/gpio/weather/config.py
Normal file
3
examples/gpio/weather/config.py
Normal file
@@ -0,0 +1,3 @@
|
||||
DHT22_PIN = 4 # GPIO pin for DHT22 sensor
|
||||
WIFI_ESSID = 'your_wifi_ssid'
|
||||
WIFI_PASSWORD = 'your_wifi_password'
|
||||
26
examples/gpio/weather/dht.py
Normal file
26
examples/gpio/weather/dht.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
DO NOT UPLOAD THIS FILE TO YOUR MICROPYTHON DEVICE
|
||||
|
||||
This module emulates MicroPython's DHT22 driver. It can be used when running
|
||||
on a system without the DHT22 hardware.
|
||||
|
||||
The temperature and humidity values that are returned are random values.
|
||||
"""
|
||||
|
||||
from random import random
|
||||
|
||||
|
||||
class DHT22:
|
||||
def __init__(self, pin):
|
||||
self.pin = pin
|
||||
|
||||
def measure(self):
|
||||
pass
|
||||
|
||||
def temperature(self):
|
||||
"""Return a random temperature between 10 and 30 degrees Celsius."""
|
||||
return random() * 20 + 10
|
||||
|
||||
def humidity(self):
|
||||
"""Return a random humidity between 30 and 70 percent."""
|
||||
return random() * 40 + 30
|
||||
169
examples/gpio/weather/index.html
Normal file
169
examples/gpio/weather/index.html
Normal file
@@ -0,0 +1,169 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Microdot Weather Dashboard</title>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/gauge.js/1.3.9/gauge.min.js" integrity="sha512-/gkYCBz4KVyJb3Shz6Z1kKu9Za5EdInNezzsm2O/DPvAYhCeIOounTzi7yuIF526z3rNZfIDxcx+rJAD07p8aA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
|
||||
<style>
|
||||
html, body {
|
||||
height: 95%;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
#container {
|
||||
position: relative;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
h1 {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
h1, p {
|
||||
text-align: center;
|
||||
}
|
||||
table {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
table h1 {
|
||||
margin-top: 0;
|
||||
}
|
||||
table p {
|
||||
margin: 0;
|
||||
}
|
||||
#temperature, #humidity {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
aspect-ratio: 2;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="container">
|
||||
<h1>Microdot Weather Dashboard</h1>
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tr>
|
||||
<td>
|
||||
<canvas id="temperature" width="400" height="200"></canvas>
|
||||
</td>
|
||||
<td>
|
||||
<canvas id="humidity" width="400" height="200"></canvas>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<p>Temperature</p>
|
||||
<h1><span id="temperature-text">??</span>°C</h1>
|
||||
</td>
|
||||
<td>
|
||||
<p>Humidity</p>
|
||||
<h1><span id="humidity-text">??</span>%</h1>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<p><i>Last updated: <span id="time-text">...</span></i></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
<script>
|
||||
// create the temperature gauge
|
||||
let temperatureGauge = new Gauge(document.getElementById('temperature')).setOptions({
|
||||
angle: 0,
|
||||
lineWidth: 0.3,
|
||||
radiusScale: 1,
|
||||
pointer: {
|
||||
length: 0.6,
|
||||
strokeWidth: 0.035,
|
||||
color: '#000000',
|
||||
},
|
||||
limitMax: false,
|
||||
limitMin: false,
|
||||
highDpiSupport: true,
|
||||
staticLabels: {
|
||||
font: "14px sans-serif",
|
||||
labels: [-30, -20, -10, 0, 10, 20, 30, 40, 50],
|
||||
color: "#000000",
|
||||
fractionDigits: 0,
|
||||
},
|
||||
staticZones: [
|
||||
{strokeStyle: "#85a6e8", min: -30, max: 0},
|
||||
{strokeStyle: "#a5dde8", min: 0, max: 10},
|
||||
{strokeStyle: "#a5e8a6", min: 10, max: 20},
|
||||
{strokeStyle: "#e8d8a5", min: 20, max: 30},
|
||||
{strokeStyle: "#e8a8a5", min: 30, max: 50},
|
||||
],
|
||||
renderTicks: {
|
||||
divisions: 8,
|
||||
divWidth: 1.1,
|
||||
divLength: 0.7,
|
||||
divColor: '#333333',
|
||||
subDivisions: 4,
|
||||
subLength: 0.3,
|
||||
subWidth: 0.6,
|
||||
subColor: '#666666'
|
||||
}
|
||||
});
|
||||
temperatureGauge.maxValue = 50;
|
||||
temperatureGauge.setMinValue(-30);
|
||||
temperatureGauge.animationSpeed = 36;
|
||||
temperatureGauge.set(0);
|
||||
|
||||
let humidityGauge = new Gauge(document.getElementById('humidity')).setOptions({
|
||||
angle: 0,
|
||||
lineWidth: 0.3,
|
||||
radiusScale: 1,
|
||||
pointer: {
|
||||
length: 0.6,
|
||||
strokeWidth: 0.035,
|
||||
color: '#000000',
|
||||
},
|
||||
limitMax: false,
|
||||
limitMin: false,
|
||||
highDpiSupport: true,
|
||||
staticLabels: {
|
||||
font: "14px sans-serif",
|
||||
labels: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
|
||||
color: "#000000",
|
||||
fractionDigits: 0,
|
||||
},
|
||||
staticZones: [
|
||||
{strokeStyle: "#85a6e8", min: 0, max: 40},
|
||||
{strokeStyle: "#a5e8a6", min: 40, max: 70},
|
||||
{strokeStyle: "#e8a8a5", min: 70, max: 100},
|
||||
],
|
||||
renderTicks: {
|
||||
divisions: 10,
|
||||
divWidth: 1.1,
|
||||
divLength: 0.7,
|
||||
divColor: '#333333',
|
||||
subDivisions: 4,
|
||||
subLength: 0.3,
|
||||
subWidth: 0.6,
|
||||
subColor: '#666666'
|
||||
}
|
||||
});
|
||||
humidityGauge.maxValue = 100;
|
||||
humidityGauge.setMinValue(0);
|
||||
humidityGauge.animationSpeed = 36;
|
||||
humidityGauge.set(0);
|
||||
|
||||
async function update() {
|
||||
const response = await fetch('/api');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
temperatureGauge.set(data.temperature);
|
||||
humidityGauge.set(data.humidity);
|
||||
document.getElementById('temperature-text').textContent = data.temperature;
|
||||
document.getElementById('humidity-text').textContent = data.humidity;
|
||||
document.getElementById('time-text').textContent = new Date(data.time * 1000).toLocaleString();
|
||||
}
|
||||
setTimeout(update, 60000); // refresh every minute
|
||||
}
|
||||
update();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
12
examples/gpio/weather/machine.py
Normal file
12
examples/gpio/weather/machine.py
Normal file
@@ -0,0 +1,12 @@
|
||||
"""
|
||||
DO NOT UPLOAD THIS FILE TO YOUR MICROPYTHON DEVICE
|
||||
|
||||
This module emulates parts of MicroPython's `machine` module, to enable to run
|
||||
MicroPython applications on UNIX, Mac or Windows systems without dedicated
|
||||
hardware.
|
||||
"""
|
||||
|
||||
|
||||
class Pin:
|
||||
def __init__(self, pin):
|
||||
self.pin = pin
|
||||
112
examples/gpio/weather/main.py
Normal file
112
examples/gpio/weather/main.py
Normal file
@@ -0,0 +1,112 @@
|
||||
import asyncio
|
||||
import dht
|
||||
import gc
|
||||
import machine
|
||||
import network
|
||||
import socket
|
||||
import time
|
||||
|
||||
import config
|
||||
from microdot import Microdot, send_file
|
||||
|
||||
app = Microdot()
|
||||
current_temperature = None
|
||||
current_humidity = None
|
||||
current_time = None
|
||||
|
||||
|
||||
def wifi_connect():
|
||||
"""Connect to the configured Wi-Fi network.
|
||||
Returns the IP address of the connected interface.
|
||||
"""
|
||||
ap_if = network.WLAN(network.AP_IF)
|
||||
ap_if.active(False)
|
||||
|
||||
sta_if = network.WLAN(network.STA_IF)
|
||||
if not sta_if.isconnected():
|
||||
print('connecting to network...')
|
||||
sta_if.active(True)
|
||||
sta_if.connect(config.WIFI_ESSID, config.WIFI_PASSWORD)
|
||||
for i in range(20):
|
||||
if sta_if.isconnected():
|
||||
break
|
||||
time.sleep(1)
|
||||
if not sta_if.isconnected():
|
||||
raise RuntimeError('Could not connect to network')
|
||||
return sta_if.ifconfig()[0]
|
||||
|
||||
|
||||
def get_current_time():
|
||||
"""Return the current Unix time.
|
||||
Note that because many microcontrollers do not have a clock, this function
|
||||
makes a call to an NTP server to obtain the current time. A Wi-Fi
|
||||
connection needs to be in place before calling this function.
|
||||
"""
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.settimeout(5)
|
||||
s.sendto(b'\x1b' + 47 * b'\0',
|
||||
socket.getaddrinfo('pool.ntp.org', 123)[0][4])
|
||||
msg, _ = s.recvfrom(1024)
|
||||
return ((msg[40] << 24) | (msg[41] << 16) | (msg[42] << 8) | msg[43]) - \
|
||||
2208988800
|
||||
|
||||
|
||||
def get_current_weather():
|
||||
"""Read the temperature and humidity from the DHT22 sensor.
|
||||
Returns them as a tuple. The returned temperature is in degrees Celcius.
|
||||
The humidity is a 0-100 percentage.
|
||||
"""
|
||||
d = dht.DHT22(machine.Pin(config.DHT22_PIN))
|
||||
d.measure()
|
||||
return d.temperature(), d.humidity()
|
||||
|
||||
|
||||
async def refresh_weather():
|
||||
"""Background task that updates the temperature and humidity.
|
||||
This task is designed to run in the background. It connects to the DHT22
|
||||
temperature and humidity sensor once per minute and stores the updated
|
||||
readings in global variables.
|
||||
"""
|
||||
global current_temperature
|
||||
global current_humidity
|
||||
global current_time
|
||||
|
||||
while True:
|
||||
try:
|
||||
t = get_current_time()
|
||||
temp, hum = get_current_weather()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as error:
|
||||
print(f'Could not obtain weather, error: {error}')
|
||||
else:
|
||||
current_time = t
|
||||
current_temperature = int(temp * 10) / 10
|
||||
current_humidity = int(hum * 10) / 10
|
||||
gc.collect()
|
||||
await asyncio.sleep(60)
|
||||
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
return send_file('index.html')
|
||||
|
||||
|
||||
@app.route('/api')
|
||||
async def api(request):
|
||||
return {
|
||||
'temperature': current_temperature,
|
||||
'humidity': current_humidity,
|
||||
'time': current_time,
|
||||
}
|
||||
|
||||
|
||||
async def start():
|
||||
ip = wifi_connect()
|
||||
print(f'Starting server at http://{ip}:8000...')
|
||||
bgtask = asyncio.create_task(refresh_weather())
|
||||
server = asyncio.create_task(app.start_server(port=8000))
|
||||
await asyncio.gather(server, bgtask)
|
||||
|
||||
|
||||
asyncio.run(start())
|
||||
31
examples/gpio/weather/network.py
Normal file
31
examples/gpio/weather/network.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
DO NOT UPLOAD THIS FILE TO YOUR MICROPYTHON DEVICE
|
||||
|
||||
This module emulates parts of MicroPython's `network` module, in particular
|
||||
those related to establishing a Wi-Fi connection. This enables to run
|
||||
MicroPython applications on UNIX, Mac or Windows systems without dedicated
|
||||
hardware.
|
||||
|
||||
Note that no connections are attempted. The assumption is that the system is
|
||||
already connected. The "127.0.0.1" address is always returned.
|
||||
"""
|
||||
|
||||
AP_IF = 1
|
||||
STA_IF = 2
|
||||
|
||||
|
||||
class WLAN:
|
||||
def __init__(self, network):
|
||||
self.network = network
|
||||
|
||||
def isconnected(self):
|
||||
return True
|
||||
|
||||
def ifconfig(self):
|
||||
return ('127.0.0.1', 'n/a', 'n/a', 'n/a')
|
||||
|
||||
def connect(self):
|
||||
pass
|
||||
|
||||
def active(self, active=None):
|
||||
pass
|
||||
BIN
examples/gpio/weather/screenshot.png
Normal file
BIN
examples/gpio/weather/screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
1
examples/login/README.md
Normal file
1
examples/login/README.md
Normal file
@@ -0,0 +1 @@
|
||||
This directory contains examples that demonstrate user logins.
|
||||
123
examples/login/login.py
Normal file
123
examples/login/login.py
Normal file
@@ -0,0 +1,123 @@
|
||||
from microdot import Microdot, redirect
|
||||
from microdot.session import Session
|
||||
from microdot.login import Login
|
||||
from pbkdf2 import generate_password_hash, check_password_hash
|
||||
|
||||
# this example provides an implementation of the generate_password_hash and
|
||||
# check_password_hash functions that can be used in MicroPython. On CPython
|
||||
# there are many other options for password hashisng so there is no need to use
|
||||
# this custom solution.
|
||||
|
||||
|
||||
class User:
|
||||
def __init__(self, id, username, password):
|
||||
self.id = id
|
||||
self.username = username
|
||||
self.password_hash = self.create_hash(password)
|
||||
|
||||
def create_hash(self, password):
|
||||
return generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
|
||||
USERS = {
|
||||
'user001': User('user001', 'susan', 'hello'),
|
||||
'user002': User('user002', 'david', 'bye'),
|
||||
}
|
||||
|
||||
app = Microdot()
|
||||
Session(app, secret_key='top-secret!')
|
||||
login = Login()
|
||||
|
||||
|
||||
@login.user_loader
|
||||
async def get_user(user_id):
|
||||
return USERS.get(user_id)
|
||||
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
async def login_page(request):
|
||||
if request.method == 'GET':
|
||||
return '''
|
||||
<!doctype html>
|
||||
<html>
|
||||
<body>
|
||||
<h1>Please Login</h1>
|
||||
<form method="POST">
|
||||
<p>
|
||||
Username<br>
|
||||
<input name="username" autofocus>
|
||||
</p>
|
||||
<p>
|
||||
Password:<br>
|
||||
<input name="password" type="password">
|
||||
<br>
|
||||
</p>
|
||||
<p>
|
||||
<input name="remember_me" type="checkbox"> Remember me
|
||||
<br>
|
||||
</p>
|
||||
<p>
|
||||
<button type="submit">Login</button>
|
||||
</p>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
''', {'Content-Type': 'text/html'}
|
||||
username = request.form['username']
|
||||
password = request.form['password']
|
||||
remember_me = bool(request.form.get('remember_me'))
|
||||
|
||||
for user in USERS.values():
|
||||
if user.username == username:
|
||||
if user.check_password(password):
|
||||
return await login.login_user(request, user,
|
||||
remember=remember_me)
|
||||
return redirect('/login')
|
||||
|
||||
|
||||
@app.route('/')
|
||||
@login
|
||||
async def index(request):
|
||||
return f'''
|
||||
<!doctype html>
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, {request.g.current_user.username}!</h1>
|
||||
<p>
|
||||
<a href="/fresh">Click here</a> to access the fresh login page.
|
||||
</p>
|
||||
<form method="POST" action="/logout">
|
||||
<button type="submit">Logout</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
''', {'Content-Type': 'text/html'}
|
||||
|
||||
|
||||
@app.get('/fresh')
|
||||
@login.fresh
|
||||
async def fresh(request):
|
||||
return f'''
|
||||
<!doctype html>
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, {request.g.current_user.username}!</h1>
|
||||
<p>This page requires a fresh login session.</p>
|
||||
<p><a href="/">Go back</a> to the main page.</p>
|
||||
</body>
|
||||
</html>
|
||||
''', {'Content-Type': 'text/html'}
|
||||
|
||||
|
||||
@app.post('/logout')
|
||||
@login
|
||||
async def logout(request):
|
||||
await login.logout_user(request)
|
||||
return redirect('/')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
47
examples/login/pbkdf2.py
Normal file
47
examples/login/pbkdf2.py
Normal file
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
import hashlib
|
||||
|
||||
# PBKDF2 secure password hashing algorithm obtained from:
|
||||
# https://codeandlife.com/2023/01/06/how-to-calculate-pbkdf2-hmac-sha256-with-
|
||||
# python,-example-code/
|
||||
|
||||
|
||||
def sha256(b):
|
||||
return hashlib.sha256(b).digest()
|
||||
|
||||
|
||||
def ljust(b, n, f):
|
||||
return b + f * (n - len(b))
|
||||
|
||||
|
||||
def gethmac(key, content):
|
||||
okeypad = bytes(v ^ 0x5c for v in ljust(key, 64, b'\0'))
|
||||
ikeypad = bytes(v ^ 0x36 for v in ljust(key, 64, b'\0'))
|
||||
return sha256(okeypad + sha256(ikeypad + content))
|
||||
|
||||
|
||||
def pbkdf2(pwd, salt, iterations=1000):
|
||||
U = salt + b'\x00\x00\x00\x01'
|
||||
T = bytes(64)
|
||||
for _ in range(iterations):
|
||||
U = gethmac(pwd, U)
|
||||
T = bytes(a ^ b for a, b in zip(U, T))
|
||||
return T
|
||||
|
||||
|
||||
# The number of iterations may need to be adjusted depending on the hardware.
|
||||
# Lower numbers make the password hashing algorithm faster but less secure, so
|
||||
# the largest number that can be tolerated should be used.
|
||||
def generate_password_hash(password, salt=None, iterations=100000):
|
||||
salt = salt or os.urandom(16)
|
||||
dk = pbkdf2(password.encode(), salt, iterations)
|
||||
return f'pbkdf2-hmac-sha256:{salt.hex()}:{iterations}:{dk.hex()}'
|
||||
|
||||
|
||||
def check_password_hash(password_hash, password):
|
||||
algorithm, salt, iterations, dk = password_hash.split(':')
|
||||
iterations = int(iterations)
|
||||
if algorithm != 'pbkdf2-hmac-sha256':
|
||||
return False
|
||||
return pbkdf2(password.encode(), salt=bytes.fromhex(salt),
|
||||
iterations=iterations) == bytes.fromhex(dk)
|
||||
@@ -1,3 +1,6 @@
|
||||
# This is a simple example that demonstrates how to use the user session, but
|
||||
# is not intended as a complete login solution. See the login subdirectory for
|
||||
# a more complete example.
|
||||
from microdot import Microdot, Response, redirect
|
||||
from microdot.session import Session, with_session
|
||||
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import asyncio
|
||||
from microdot import Microdot
|
||||
from microdot import Microdot, send_file
|
||||
from microdot.sse import with_sse
|
||||
|
||||
app = Microdot()
|
||||
|
||||
|
||||
@app.route("/")
|
||||
async def main(request):
|
||||
return send_file('index.html')
|
||||
|
||||
|
||||
@app.route('/events')
|
||||
@with_sse
|
||||
async def events(request, sse):
|
||||
for i in range(10):
|
||||
await asyncio.sleep(1)
|
||||
await sse.send({'counter': i})
|
||||
print('Client connected')
|
||||
try:
|
||||
i = 0
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
i += 1
|
||||
await sse.send({'counter': i})
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
print('Client disconnected')
|
||||
|
||||
|
||||
app.run(debug=True)
|
||||
app.run()
|
||||
|
||||
30
examples/sse/index.html
Normal file
30
examples/sse/index.html
Normal file
@@ -0,0 +1,30 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Microdot SSE Example</title>
|
||||
<meta charset="UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Microdot SSE Example</h1>
|
||||
<div id="log"></div>
|
||||
<script>
|
||||
const log = (text, color) => {
|
||||
document.getElementById('log').innerHTML += `<span style="color: ${color}">${text}</span><br>`;
|
||||
};
|
||||
|
||||
const eventSource = new EventSource('/events');
|
||||
|
||||
eventSource.onopen = () => {
|
||||
log('Connection to server opened.', 'black');
|
||||
};
|
||||
|
||||
eventSource.onmessage = (event) => {
|
||||
log(`Received message: ${event.data}`, 'blue');
|
||||
};
|
||||
|
||||
eventSource.onerror = (event) => {
|
||||
log(`EventSource failed: ${event.type}`, 'red');
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
1
examples/subapps/README.md
Normal file
1
examples/subapps/README.md
Normal file
@@ -0,0 +1 @@
|
||||
This directory contains examples that demonstrate sub-applications.
|
||||
27
examples/subapps/app.py
Normal file
27
examples/subapps/app.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from microdot import Microdot
|
||||
from subapp import subapp
|
||||
|
||||
app = Microdot()
|
||||
app.mount(subapp, url_prefix='/subapp')
|
||||
|
||||
|
||||
@app.route('/')
|
||||
async def hello(request):
|
||||
return '''
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Microdot Sub-App Example</title>
|
||||
<meta charset="UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<h1>Microdot Main Page</h1>
|
||||
<p>Visit the <a href="/subapp">sub-app</a>.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
''', 200, {'Content-Type': 'text/html'}
|
||||
|
||||
|
||||
app.run(debug=True)
|
||||
44
examples/subapps/subapp.py
Normal file
44
examples/subapps/subapp.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from microdot import Microdot
|
||||
|
||||
subapp = Microdot()
|
||||
|
||||
|
||||
@subapp.route('')
|
||||
async def hello(request):
|
||||
# request.url_prefix can be used in links that are relative to this subapp
|
||||
return f'''
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Microdot Sub-App Example</title>
|
||||
<meta charset="UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<h1>Microdot Sub-App Main Page</h1>
|
||||
<p>Visit the sub-app's <a href="{request.url_prefix}/second">secondary page</a>.</p>
|
||||
<p>Go back to the app's <a href="/">main page</a>.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
''', 200, {'Content-Type': 'text/html'} # noqa: E501
|
||||
|
||||
|
||||
@subapp.route('/second')
|
||||
async def second(request):
|
||||
return f'''
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Microdot Sub-App Example</title>
|
||||
<meta charset="UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<h1>Microdot Sub-App Secondary Page</h1>
|
||||
<p>Visit the sub-app's <a href="{request.url_prefix}">main page</a>.</p>
|
||||
<p>Go back to the app's <a href="/">main page</a>.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
''', 200, {'Content-Type': 'text/html'} # noqa: E501
|
||||
@@ -1 +1,4 @@
|
||||
This directory contains file upload examples.
|
||||
|
||||
- `simple_uploads.py` demonstrates how to upload a single file.
|
||||
- `formdata.py` demonstrates how to process a form that includes file uploads.
|
||||
|
||||
17
examples/uploads/formdata.html
Normal file
17
examples/uploads/formdata.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Microdot Multipart Form-Data Example</title>
|
||||
<meta charset="UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Microdot Multipart Form-Data Example</h1>
|
||||
<form method="POST" action="" enctype="multipart/form-data">
|
||||
<p>Name: <input type="text" name="name" /></p>
|
||||
<p>Age: <input type="text" name="age" /></p>
|
||||
<p>Comments: <textarea name="comments" rows="4"></textarea></p>
|
||||
<p>File: <input type="file" id="file" name="file" /></p>
|
||||
<input type="submit" value="Submit" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
26
examples/uploads/formdata.py
Normal file
26
examples/uploads/formdata.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from microdot import Microdot, send_file, Request
|
||||
from microdot.multipart import with_form_data
|
||||
|
||||
app = Microdot()
|
||||
Request.max_content_length = 1024 * 1024 # 1MB (change as needed)
|
||||
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return send_file('formdata.html')
|
||||
|
||||
|
||||
@app.post('/')
|
||||
@with_form_data
|
||||
async def upload(request):
|
||||
print('Form fields:')
|
||||
for field, value in request.form.items():
|
||||
print(f'- {field}: {value}')
|
||||
print('\nFile uploads:')
|
||||
for field, value in request.files.items():
|
||||
print(f'- {field}: {value.filename}, {await value.read()}')
|
||||
return 'We have received your data!'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
@@ -6,7 +6,7 @@ Request.max_content_length = 1024 * 1024 # 1MB (change as needed)
|
||||
|
||||
@app.get('/')
|
||||
async def index(request):
|
||||
return send_file('index.html')
|
||||
return send_file('simple_uploads.html')
|
||||
|
||||
|
||||
@app.post('/upload')
|
||||
139
libs/circuitpython/adafruit_ticks.py
Normal file
139
libs/circuitpython/adafruit_ticks.py
Normal file
@@ -0,0 +1,139 @@
|
||||
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
|
||||
# SPDX-FileCopyrightText: Copyright (c) 2021 Jeff Epler for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""
|
||||
`adafruit_ticks`
|
||||
================================================================================
|
||||
|
||||
Work with intervals and deadlines in milliseconds
|
||||
|
||||
|
||||
* Author(s): Jeff Epler
|
||||
|
||||
Implementation Notes
|
||||
--------------------
|
||||
|
||||
**Software and Dependencies:**
|
||||
|
||||
* Adafruit CircuitPython firmware for the supported boards:
|
||||
https://github.com/adafruit/circuitpython/releases
|
||||
|
||||
"""
|
||||
|
||||
# imports
|
||||
from micropython import const
|
||||
|
||||
__version__ = "0.0.0+auto.0"
|
||||
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ticks.git"
|
||||
|
||||
_TICKS_PERIOD = const(1 << 29)
|
||||
_TICKS_MAX = const(_TICKS_PERIOD - 1)
|
||||
_TICKS_HALFPERIOD = const(_TICKS_PERIOD // 2)
|
||||
|
||||
# Get the correct implementation of ticks_ms. There are three possibilities:
|
||||
#
|
||||
# - supervisor.ticks_ms is present. This will be the case starting in CP7.0
|
||||
#
|
||||
# - time.ticks_ms is present. This is the case for MicroPython & for the "unix
|
||||
# port" of CircuitPython, used for some automated testing.
|
||||
#
|
||||
# - time.monotonic_ns is present, and works. This is the case on most
|
||||
# Express boards in CP6.x, and most host computer versions of Python.
|
||||
#
|
||||
# - Otherwise, time.monotonic is assumed to be present. This is the case
|
||||
# on most non-express boards in CP6.x, and some old host computer versions
|
||||
# of Python.
|
||||
#
|
||||
# Note that on microcontrollers, this time source becomes increasingly
|
||||
# inaccurate when the board has not been reset in a long time, losing the
|
||||
# ability to measure 1ms intervals after about 1 hour, and losing the
|
||||
# ability to meausre 128ms intervals after 6 days. The only solution is to
|
||||
# either upgrade to a version with supervisor.ticks_ms, or to switch to a
|
||||
# board with time.monotonic_ns.
|
||||
|
||||
try:
|
||||
from supervisor import ticks_ms # pylint: disable=unused-import
|
||||
except (ImportError, NameError):
|
||||
import time
|
||||
|
||||
if _ticks_ms := getattr(time, "ticks_ms", None):
|
||||
|
||||
def ticks_ms() -> int:
|
||||
"""Return the time in milliseconds since an unspecified moment,
|
||||
wrapping after 2**29ms.
|
||||
|
||||
The wrap value was chosen so that it is always possible to add or
|
||||
subtract two `ticks_ms` values without overflow on a board without
|
||||
long ints (or without allocating any long integer objects, on
|
||||
boards with long ints).
|
||||
|
||||
This ticks value comes from a low-accuracy clock internal to the
|
||||
microcontroller, just like `time.monotonic`. Due to its low
|
||||
accuracy and the fact that it "wraps around" every few days, it is
|
||||
intended for working with short term events like advancing an LED
|
||||
animation, not for long term events like counting down the time
|
||||
until a holiday."""
|
||||
return _ticks_ms() & _TICKS_MAX # pylint: disable=not-callable
|
||||
|
||||
else:
|
||||
try:
|
||||
from time import monotonic_ns as _monotonic_ns
|
||||
|
||||
_monotonic_ns() # Check that monotonic_ns is usable
|
||||
|
||||
def ticks_ms() -> int:
|
||||
"""Return the time in milliseconds since an unspecified moment,
|
||||
wrapping after 2**29ms.
|
||||
|
||||
The wrap value was chosen so that it is always possible to add or
|
||||
subtract two `ticks_ms` values without overflow on a board without
|
||||
long ints (or without allocating any long integer objects, on
|
||||
boards with long ints).
|
||||
|
||||
This ticks value comes from a low-accuracy clock internal to the
|
||||
microcontroller, just like `time.monotonic`. Due to its low
|
||||
accuracy and the fact that it "wraps around" every few days, it is
|
||||
intended for working with short term events like advancing an LED
|
||||
animation, not for long term events like counting down the time
|
||||
until a holiday."""
|
||||
return (_monotonic_ns() // 1_000_000) & _TICKS_MAX
|
||||
|
||||
except (ImportError, NameError, NotImplementedError):
|
||||
from time import monotonic as _monotonic
|
||||
|
||||
def ticks_ms() -> int:
|
||||
"""Return the time in milliseconds since an unspecified moment,
|
||||
wrapping after 2**29ms.
|
||||
|
||||
The wrap value was chosen so that it is always possible to add or
|
||||
subtract two `ticks_ms` values without overflow on a board without
|
||||
long ints (or without allocating any long integer objects, on
|
||||
boards with long ints).
|
||||
|
||||
This ticks value comes from a low-accuracy clock internal to the
|
||||
microcontroller, just like `time.monotonic`. Due to its low
|
||||
accuracy and the fact that it "wraps around" every few days, it is
|
||||
intended for working with short term events like advancing an LED
|
||||
animation, not for long term events like counting down the time
|
||||
until a holiday."""
|
||||
return int(_monotonic() * 1000) & _TICKS_MAX
|
||||
|
||||
|
||||
def ticks_add(ticks: int, delta: int) -> int:
|
||||
"Add a delta to a base number of ticks, performing wraparound at 2**29ms."
|
||||
return (ticks + delta) % _TICKS_PERIOD
|
||||
|
||||
|
||||
def ticks_diff(ticks1: int, ticks2: int) -> int:
|
||||
"""Compute the signed difference between two ticks values,
|
||||
assuming that they are within 2**28 ticks"""
|
||||
diff = (ticks1 - ticks2) & _TICKS_MAX
|
||||
diff = ((diff + _TICKS_HALFPERIOD) & _TICKS_MAX) - _TICKS_HALFPERIOD
|
||||
return diff
|
||||
|
||||
|
||||
def ticks_less(ticks1: int, ticks2: int) -> bool:
|
||||
"""Return true if ticks1 is before ticks2 and false otherwise,
|
||||
assuming that they are within 2**28 ticks"""
|
||||
return ticks_diff(ticks1, ticks2) < 0
|
||||
41
libs/circuitpython/asyncio/__init__.py
Normal file
41
libs/circuitpython/asyncio/__init__.py
Normal file
@@ -0,0 +1,41 @@
|
||||
# SPDX-FileCopyrightText: 2019 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
|
||||
from .core import *
|
||||
|
||||
__version__ = "0.0.0+auto.0"
|
||||
__repo__ = "https://github.com/Adafruit/Adafruit_CircuitPython_asyncio.git"
|
||||
|
||||
_attrs = {
|
||||
"wait_for": "funcs",
|
||||
"wait_for_ms": "funcs",
|
||||
"gather": "funcs",
|
||||
"Event": "event",
|
||||
"ThreadSafeFlag": "event",
|
||||
"Lock": "lock",
|
||||
"open_connection": "stream",
|
||||
"start_server": "stream",
|
||||
"StreamReader": "stream",
|
||||
"StreamWriter": "stream",
|
||||
}
|
||||
|
||||
# Lazy loader, effectively does:
|
||||
# global attr
|
||||
# from .mod import attr
|
||||
def __getattr__(attr):
|
||||
mod = _attrs.get(attr, None)
|
||||
if mod is None:
|
||||
raise AttributeError(attr)
|
||||
value = getattr(__import__(mod, None, None, True, 1), attr)
|
||||
globals()[attr] = value
|
||||
return value
|
||||
430
libs/circuitpython/asyncio/core.py
Normal file
430
libs/circuitpython/asyncio/core.py
Normal file
@@ -0,0 +1,430 @@
|
||||
# SPDX-FileCopyrightText: 2019 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
"""
|
||||
Core
|
||||
====
|
||||
"""
|
||||
|
||||
from adafruit_ticks import ticks_ms as ticks, ticks_diff, ticks_add
|
||||
import sys, select
|
||||
|
||||
try:
|
||||
from traceback import print_exception
|
||||
except:
|
||||
from .traceback import print_exception
|
||||
|
||||
# Import TaskQueue and Task, preferring built-in C code over Python code
|
||||
try:
|
||||
from _asyncio import TaskQueue, Task
|
||||
except ImportError:
|
||||
from .task import TaskQueue, Task
|
||||
|
||||
################################################################################
|
||||
# Exceptions
|
||||
|
||||
|
||||
# Depending on the release of CircuitPython these errors may or may not
|
||||
# exist in the C implementation of `_asyncio`. However, when they
|
||||
# do exist, they must be preferred over the Python code.
|
||||
try:
|
||||
from _asyncio import CancelledError, InvalidStateError
|
||||
except (ImportError, AttributeError):
|
||||
class CancelledError(BaseException):
|
||||
"""Injected into a task when calling `Task.cancel()`"""
|
||||
pass
|
||||
|
||||
|
||||
class InvalidStateError(Exception):
|
||||
"""Can be raised in situations like setting a result value for a task object that already has a result value set."""
|
||||
pass
|
||||
|
||||
|
||||
class TimeoutError(Exception):
|
||||
"""Raised when waiting for a task longer than the specified timeout."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
# Used when calling Loop.call_exception_handler
|
||||
_exc_context = {"message": "Task exception wasn't retrieved", "exception": None, "future": None}
|
||||
|
||||
|
||||
################################################################################
|
||||
# Sleep functions
|
||||
|
||||
# "Yield" once, then raise StopIteration
|
||||
class SingletonGenerator:
|
||||
def __init__(self):
|
||||
self.state = None
|
||||
self.exc = StopIteration()
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __await__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self.state is not None:
|
||||
_task_queue.push_sorted(cur_task, self.state)
|
||||
self.state = None
|
||||
return None
|
||||
else:
|
||||
self.exc.__traceback__ = None
|
||||
raise self.exc
|
||||
|
||||
|
||||
# Pause task execution for the given time (integer in milliseconds, uPy extension)
|
||||
# Use a SingletonGenerator to do it without allocating on the heap
|
||||
def sleep_ms(t, sgen=SingletonGenerator()):
|
||||
"""Sleep for *t* milliseconds.
|
||||
|
||||
This is a coroutine, and a MicroPython extension.
|
||||
"""
|
||||
|
||||
assert sgen.state is None, "Check for a missing `await` in your code"
|
||||
sgen.state = ticks_add(ticks(), max(0, t))
|
||||
return sgen
|
||||
|
||||
|
||||
# Pause task execution for the given time (in seconds)
|
||||
def sleep(t):
|
||||
"""Sleep for *t* seconds
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
return sleep_ms(int(t * 1000))
|
||||
|
||||
|
||||
################################################################################
|
||||
# "Never schedule" object"
|
||||
# Don't re-schedule the object that awaits _never().
|
||||
# For internal use only. Some constructs, like `await event.wait()`,
|
||||
# work by NOT re-scheduling the task which calls wait(), but by
|
||||
# having some other task schedule it later.
|
||||
class _NeverSingletonGenerator:
|
||||
def __init__(self):
|
||||
self.state = None
|
||||
self.exc = StopIteration()
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __await__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self.state is not None:
|
||||
self.state = None
|
||||
return None
|
||||
else:
|
||||
self.exc.__traceback__ = None
|
||||
raise self.exc
|
||||
|
||||
def _never(sgen=_NeverSingletonGenerator()):
|
||||
# assert sgen.state is None, "Check for a missing `await` in your code"
|
||||
sgen.state = False
|
||||
return sgen
|
||||
|
||||
|
||||
################################################################################
|
||||
# Queue and poller for stream IO
|
||||
|
||||
|
||||
class IOQueue:
|
||||
def __init__(self):
|
||||
self.poller = select.poll()
|
||||
self.map = {} # maps id(stream) to [task_waiting_read, task_waiting_write, stream]
|
||||
|
||||
def _enqueue(self, s, idx):
|
||||
if id(s) not in self.map:
|
||||
entry = [None, None, s]
|
||||
entry[idx] = cur_task
|
||||
self.map[id(s)] = entry
|
||||
self.poller.register(s, select.POLLIN if idx == 0 else select.POLLOUT)
|
||||
else:
|
||||
sm = self.map[id(s)]
|
||||
assert sm[idx] is None
|
||||
assert sm[1 - idx] is not None
|
||||
sm[idx] = cur_task
|
||||
self.poller.modify(s, select.POLLIN | select.POLLOUT)
|
||||
# Link task to this IOQueue so it can be removed if needed
|
||||
cur_task.data = self
|
||||
|
||||
def _dequeue(self, s):
|
||||
del self.map[id(s)]
|
||||
self.poller.unregister(s)
|
||||
|
||||
async def queue_read(self, s):
|
||||
self._enqueue(s, 0)
|
||||
await _never()
|
||||
|
||||
async def queue_write(self, s):
|
||||
self._enqueue(s, 1)
|
||||
await _never()
|
||||
|
||||
def remove(self, task):
|
||||
while True:
|
||||
del_s = None
|
||||
for k in self.map: # Iterate without allocating on the heap
|
||||
q0, q1, s = self.map[k]
|
||||
if q0 is task or q1 is task:
|
||||
del_s = s
|
||||
break
|
||||
if del_s is not None:
|
||||
self._dequeue(s)
|
||||
else:
|
||||
break
|
||||
|
||||
def wait_io_event(self, dt):
|
||||
for s, ev in self.poller.ipoll(dt):
|
||||
sm = self.map[id(s)]
|
||||
# print('poll', s, sm, ev)
|
||||
if ev & ~select.POLLOUT and sm[0] is not None:
|
||||
# POLLIN or error
|
||||
_task_queue.push_head(sm[0])
|
||||
sm[0] = None
|
||||
if ev & ~select.POLLIN and sm[1] is not None:
|
||||
# POLLOUT or error
|
||||
_task_queue.push_head(sm[1])
|
||||
sm[1] = None
|
||||
if sm[0] is None and sm[1] is None:
|
||||
self._dequeue(s)
|
||||
elif sm[0] is None:
|
||||
self.poller.modify(s, select.POLLOUT)
|
||||
else:
|
||||
self.poller.modify(s, select.POLLIN)
|
||||
|
||||
|
||||
################################################################################
|
||||
# Main run loop
|
||||
|
||||
# Ensure the awaitable is a task
|
||||
def _promote_to_task(aw):
|
||||
return aw if isinstance(aw, Task) else create_task(aw)
|
||||
|
||||
|
||||
# Create and schedule a new task from a coroutine
|
||||
def create_task(coro):
|
||||
"""Create a new task from the given coroutine and schedule it to run.
|
||||
|
||||
Returns the corresponding `Task` object.
|
||||
"""
|
||||
|
||||
if not hasattr(coro, "send"):
|
||||
raise TypeError("coroutine expected")
|
||||
t = Task(coro, globals())
|
||||
_task_queue.push_head(t)
|
||||
return t
|
||||
|
||||
|
||||
# Keep scheduling tasks until there are none left to schedule
|
||||
def run_until_complete(main_task=None):
|
||||
"""Run the given *main_task* until it completes."""
|
||||
|
||||
global cur_task
|
||||
excs_all = (CancelledError, Exception) # To prevent heap allocation in loop
|
||||
excs_stop = (CancelledError, StopIteration) # To prevent heap allocation in loop
|
||||
while True:
|
||||
# Wait until the head of _task_queue is ready to run
|
||||
dt = 1
|
||||
while dt > 0:
|
||||
dt = -1
|
||||
t = _task_queue.peek()
|
||||
if t:
|
||||
# A task waiting on _task_queue; "ph_key" is time to schedule task at
|
||||
dt = max(0, ticks_diff(t.ph_key, ticks()))
|
||||
elif not _io_queue.map:
|
||||
# No tasks can be woken so finished running
|
||||
return
|
||||
# print('(poll {})'.format(dt), len(_io_queue.map))
|
||||
_io_queue.wait_io_event(dt)
|
||||
|
||||
# Get next task to run and continue it
|
||||
t = _task_queue.pop_head()
|
||||
cur_task = t
|
||||
try:
|
||||
# Continue running the coroutine, it's responsible for rescheduling itself
|
||||
exc = t.data
|
||||
if not exc:
|
||||
t.coro.send(None)
|
||||
else:
|
||||
# If the task is finished and on the run queue and gets here, then it
|
||||
# had an exception and was not await'ed on. Throwing into it now will
|
||||
# raise StopIteration and the code below will catch this and run the
|
||||
# call_exception_handler function.
|
||||
t.data = None
|
||||
t.coro.throw(exc)
|
||||
except excs_all as er:
|
||||
# Check the task is not on any event queue
|
||||
assert t.data is None
|
||||
# This task is done, check if it's the main task and then loop should stop
|
||||
if t is main_task:
|
||||
if isinstance(er, StopIteration):
|
||||
return er.value
|
||||
raise er
|
||||
if t.state:
|
||||
# Task was running but is now finished.
|
||||
waiting = False
|
||||
if t.state is True:
|
||||
# "None" indicates that the task is complete and not await'ed on (yet).
|
||||
t.state = None
|
||||
elif callable(t.state):
|
||||
# The task has a callback registered to be called on completion.
|
||||
t.state(t, er)
|
||||
t.state = False
|
||||
waiting = True
|
||||
else:
|
||||
# Schedule any other tasks waiting on the completion of this task.
|
||||
while t.state.peek():
|
||||
_task_queue.push_head(t.state.pop_head())
|
||||
waiting = True
|
||||
# "False" indicates that the task is complete and has been await'ed on.
|
||||
t.state = False
|
||||
if not waiting and not isinstance(er, excs_stop):
|
||||
# An exception ended this detached task, so queue it for later
|
||||
# execution to handle the uncaught exception if no other task retrieves
|
||||
# the exception in the meantime (this is handled by Task.throw).
|
||||
_task_queue.push_head(t)
|
||||
# Save return value of coro to pass up to caller.
|
||||
t.data = er
|
||||
elif t.state is None:
|
||||
# Task is already finished and nothing await'ed on the task,
|
||||
# so call the exception handler.
|
||||
_exc_context["exception"] = exc
|
||||
_exc_context["future"] = t
|
||||
Loop.call_exception_handler(_exc_context)
|
||||
|
||||
|
||||
# Create a new task from a coroutine and run it until it finishes
|
||||
def run(coro):
|
||||
"""Create a new task from the given coroutine and run it until it completes.
|
||||
|
||||
Returns the value returned by *coro*.
|
||||
"""
|
||||
|
||||
return run_until_complete(create_task(coro))
|
||||
|
||||
|
||||
################################################################################
|
||||
# Event loop wrapper
|
||||
|
||||
|
||||
async def _stopper():
|
||||
pass
|
||||
|
||||
|
||||
_stop_task = None
|
||||
|
||||
|
||||
class Loop:
|
||||
"""Class representing the event loop"""
|
||||
|
||||
_exc_handler = None
|
||||
|
||||
def create_task(coro):
|
||||
"""Create a task from the given *coro* and return the new `Task` object."""
|
||||
|
||||
return create_task(coro)
|
||||
|
||||
def run_forever():
|
||||
"""Run the event loop until `Loop.stop()` is called."""
|
||||
|
||||
global _stop_task
|
||||
_stop_task = Task(_stopper(), globals())
|
||||
run_until_complete(_stop_task)
|
||||
# TODO should keep running until .stop() is called, even if there're no tasks left
|
||||
|
||||
def run_until_complete(aw):
|
||||
"""Run the given *awaitable* until it completes. If *awaitable* is not a task then
|
||||
it will be promoted to one.
|
||||
"""
|
||||
|
||||
return run_until_complete(_promote_to_task(aw))
|
||||
|
||||
def stop():
|
||||
"""Stop the event loop"""
|
||||
|
||||
global _stop_task
|
||||
if _stop_task is not None:
|
||||
_task_queue.push_head(_stop_task)
|
||||
# If stop() is called again, do nothing
|
||||
_stop_task = None
|
||||
|
||||
def close():
|
||||
"""Close the event loop."""
|
||||
|
||||
pass
|
||||
|
||||
def set_exception_handler(handler):
|
||||
"""Set the exception handler to call when a Task raises an exception that is not
|
||||
caught. The *handler* should accept two arguments: ``(loop, context)``
|
||||
"""
|
||||
|
||||
Loop._exc_handler = handler
|
||||
|
||||
def get_exception_handler():
|
||||
"""Get the current exception handler. Returns the handler, or ``None`` if no
|
||||
custom handler is set.
|
||||
"""
|
||||
|
||||
return Loop._exc_handler
|
||||
|
||||
def default_exception_handler(loop, context):
|
||||
"""The default exception handler that is called."""
|
||||
|
||||
exc = context["exception"]
|
||||
print_exception(None, exc, exc.__traceback__)
|
||||
|
||||
def call_exception_handler(context):
|
||||
"""Call the current exception handler. The argument *context* is passed through
|
||||
and is a dictionary containing keys:
|
||||
``'message'``, ``'exception'``, ``'future'``
|
||||
"""
|
||||
(Loop._exc_handler or Loop.default_exception_handler)(Loop, context)
|
||||
|
||||
|
||||
# The runq_len and waitq_len arguments are for legacy uasyncio compatibility
|
||||
def get_event_loop(runq_len=0, waitq_len=0):
|
||||
"""Return the event loop used to schedule and run tasks. See `Loop`."""
|
||||
|
||||
return Loop
|
||||
|
||||
|
||||
def current_task():
|
||||
"""Return the `Task` object associated with the currently running task."""
|
||||
|
||||
return cur_task
|
||||
|
||||
|
||||
def new_event_loop():
|
||||
"""Reset the event loop and return it.
|
||||
|
||||
**NOTE**: Since MicroPython only has a single event loop, this function just resets
|
||||
the loop's state, it does not create a new one
|
||||
"""
|
||||
|
||||
global _task_queue, _io_queue, _exc_context, cur_task
|
||||
# TaskQueue of Task instances
|
||||
_task_queue = TaskQueue()
|
||||
# Task queue and poller for stream IO
|
||||
_io_queue = IOQueue()
|
||||
cur_task = None
|
||||
_exc_context['exception'] = None
|
||||
_exc_context['future'] = None
|
||||
return Loop
|
||||
|
||||
|
||||
# Initialise default event loop
|
||||
new_event_loop()
|
||||
92
libs/circuitpython/asyncio/event.py
Normal file
92
libs/circuitpython/asyncio/event.py
Normal file
@@ -0,0 +1,92 @@
|
||||
# SPDX-FileCopyrightText: 2019-2020 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
"""
|
||||
Events
|
||||
======
|
||||
"""
|
||||
|
||||
from . import core
|
||||
|
||||
# Event class for primitive events that can be waited on, set, and cleared
|
||||
class Event:
|
||||
"""Create a new event which can be used to synchronize tasks. Events
|
||||
start in the cleared state.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.state = False # False=unset; True=set
|
||||
self.waiting = core.TaskQueue() # Queue of Tasks waiting on completion of this event
|
||||
|
||||
def is_set(self):
|
||||
"""Returns ``True`` if the event is set, ``False`` otherwise."""
|
||||
|
||||
return self.state
|
||||
|
||||
def set(self):
|
||||
"""Set the event. Any tasks waiting on the event will be scheduled to run.
|
||||
"""
|
||||
|
||||
# Event becomes set, schedule any tasks waiting on it
|
||||
# Note: This must not be called from anything except the thread running
|
||||
# the asyncio loop (i.e. neither hard or soft IRQ, or a different thread).
|
||||
while self.waiting.peek():
|
||||
core._task_queue.push_head(self.waiting.pop_head())
|
||||
self.state = True
|
||||
|
||||
def clear(self):
|
||||
"""Clear the event."""
|
||||
|
||||
self.state = False
|
||||
|
||||
async def wait(self):
|
||||
"""Wait for the event to be set. If the event is already set then it returns
|
||||
immediately.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
if not self.state:
|
||||
# Event not set, put the calling task on the event's waiting queue
|
||||
self.waiting.push_head(core.cur_task)
|
||||
# Set calling task's data to the event's queue so it can be removed if needed
|
||||
core.cur_task.data = self.waiting
|
||||
await core._never()
|
||||
return True
|
||||
|
||||
|
||||
# MicroPython-extension: This can be set from outside the asyncio event loop,
|
||||
# such as other threads, IRQs or scheduler context. Implementation is a stream
|
||||
# that asyncio will poll until a flag is set.
|
||||
# Note: Unlike Event, this is self-clearing.
|
||||
try:
|
||||
import uio
|
||||
|
||||
class ThreadSafeFlag(uio.IOBase):
|
||||
def __init__(self):
|
||||
self._flag = 0
|
||||
|
||||
def ioctl(self, req, flags):
|
||||
if req == 3: # MP_STREAM_POLL
|
||||
return self._flag * flags
|
||||
return None
|
||||
|
||||
def set(self):
|
||||
self._flag = 1
|
||||
|
||||
async def wait(self):
|
||||
if not self._flag:
|
||||
yield core._io_queue.queue_read(self)
|
||||
self._flag = 0
|
||||
|
||||
except ImportError:
|
||||
pass
|
||||
165
libs/circuitpython/asyncio/funcs.py
Normal file
165
libs/circuitpython/asyncio/funcs.py
Normal file
@@ -0,0 +1,165 @@
|
||||
# SPDX-FileCopyrightText: 2019-2020 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019-2022 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
"""
|
||||
Functions
|
||||
=========
|
||||
"""
|
||||
|
||||
|
||||
from . import core
|
||||
|
||||
|
||||
async def _run(waiter, aw):
|
||||
try:
|
||||
result = await aw
|
||||
status = True
|
||||
except BaseException as er:
|
||||
result = None
|
||||
status = er
|
||||
if waiter.data is None:
|
||||
# The waiter is still waiting, cancel it.
|
||||
if waiter.cancel():
|
||||
# Waiter was cancelled by us, change its CancelledError to an instance of
|
||||
# CancelledError that contains the status and result of waiting on aw.
|
||||
# If the wait_for task subsequently gets cancelled externally then this
|
||||
# instance will be reset to a CancelledError instance without arguments.
|
||||
waiter.data = core.CancelledError(status, result)
|
||||
|
||||
async def wait_for(aw, timeout, sleep=core.sleep):
|
||||
"""Wait for the *aw* awaitable to complete, but cancel if it takes longer
|
||||
than *timeout* seconds. If *aw* is not a task then a task will be created
|
||||
from it.
|
||||
|
||||
If a timeout occurs, it cancels the task and raises ``asyncio.TimeoutError``:
|
||||
this should be trapped by the caller.
|
||||
|
||||
Returns the return value of *aw*.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
aw = core._promote_to_task(aw)
|
||||
if timeout is None:
|
||||
return await aw
|
||||
|
||||
# Run aw in a separate runner task that manages its exceptions.
|
||||
runner_task = core.create_task(_run(core.cur_task, aw))
|
||||
|
||||
try:
|
||||
# Wait for the timeout to elapse.
|
||||
await sleep(timeout)
|
||||
except core.CancelledError as er:
|
||||
status = er.args[0] if er.args else None
|
||||
if status is None:
|
||||
# This wait_for was cancelled externally, so cancel aw and re-raise.
|
||||
runner_task.cancel()
|
||||
raise er
|
||||
elif status is True:
|
||||
# aw completed successfully and cancelled the sleep, so return aw's result.
|
||||
return er.args[1]
|
||||
else:
|
||||
# aw raised an exception, propagate it out to the caller.
|
||||
raise status
|
||||
|
||||
# The sleep finished before aw, so cancel aw and raise TimeoutError.
|
||||
runner_task.cancel()
|
||||
await runner_task
|
||||
raise core.TimeoutError
|
||||
|
||||
|
||||
def wait_for_ms(aw, timeout):
|
||||
"""Similar to `wait_for` but *timeout* is an integer in milliseconds.
|
||||
|
||||
This is a coroutine, and a MicroPython extension.
|
||||
"""
|
||||
|
||||
return wait_for(aw, timeout, core.sleep_ms)
|
||||
|
||||
|
||||
class _Remove:
|
||||
@staticmethod
|
||||
def remove(t):
|
||||
pass
|
||||
|
||||
|
||||
async def gather(*aws, return_exceptions=False):
|
||||
"""Run all *aws* awaitables concurrently. Any *aws* that are not tasks
|
||||
are promoted to tasks.
|
||||
|
||||
Returns a list of return values of all *aws*
|
||||
"""
|
||||
if not aws:
|
||||
return []
|
||||
|
||||
def done(t, er):
|
||||
# Sub-task "t" has finished, with exception "er".
|
||||
nonlocal state
|
||||
if gather_task.data is not _Remove:
|
||||
# The main gather task has already been scheduled, so do nothing.
|
||||
# This happens if another sub-task already raised an exception and
|
||||
# woke the main gather task (via this done function), or if the main
|
||||
# gather task was cancelled externally.
|
||||
return
|
||||
elif not return_exceptions and not isinstance(er, StopIteration):
|
||||
# A sub-task raised an exception, indicate that to the gather task.
|
||||
state = er
|
||||
else:
|
||||
state -= 1
|
||||
if state:
|
||||
# Still some sub-tasks running.
|
||||
return
|
||||
# Gather waiting is done, schedule the main gather task.
|
||||
core._task_queue.push_head(gather_task)
|
||||
|
||||
ts = [core._promote_to_task(aw) for aw in aws]
|
||||
for i in range(len(ts)):
|
||||
if ts[i].state is not True:
|
||||
# Task is not running, gather not currently supported for this case.
|
||||
raise RuntimeError("can't gather")
|
||||
# Register the callback to call when the task is done.
|
||||
ts[i].state = done
|
||||
|
||||
# Set the state for execution of the gather.
|
||||
gather_task = core.cur_task
|
||||
state = len(ts)
|
||||
cancel_all = False
|
||||
|
||||
# Wait for the a sub-task to need attention.
|
||||
gather_task.data = _Remove
|
||||
try:
|
||||
await core._never()
|
||||
except core.CancelledError as er:
|
||||
cancel_all = True
|
||||
state = er
|
||||
|
||||
# Clean up tasks.
|
||||
for i in range(len(ts)):
|
||||
if ts[i].state is done:
|
||||
# Sub-task is still running, deregister the callback and cancel if needed.
|
||||
ts[i].state = True
|
||||
if cancel_all:
|
||||
ts[i].cancel()
|
||||
elif isinstance(ts[i].data, StopIteration):
|
||||
# Sub-task ran to completion, get its return value.
|
||||
ts[i] = ts[i].data.value
|
||||
else:
|
||||
# Sub-task had an exception with return_exceptions==True, so get its exception.
|
||||
ts[i] = ts[i].data
|
||||
|
||||
# Either this gather was cancelled, or one of the sub-tasks raised an exception with
|
||||
# return_exceptions==False, so reraise the exception here.
|
||||
if state is not 0:
|
||||
raise state
|
||||
|
||||
# Return the list of return values of each sub-task.
|
||||
return ts
|
||||
87
libs/circuitpython/asyncio/lock.py
Normal file
87
libs/circuitpython/asyncio/lock.py
Normal file
@@ -0,0 +1,87 @@
|
||||
# SPDX-FileCopyrightText: 2019-2020 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
"""
|
||||
Locks
|
||||
=====
|
||||
"""
|
||||
|
||||
from . import core
|
||||
|
||||
# Lock class for primitive mutex capability
|
||||
class Lock:
|
||||
"""Create a new lock which can be used to coordinate tasks. Locks start in
|
||||
the unlocked state.
|
||||
|
||||
In addition to the methods below, locks can be used in an ``async with``
|
||||
statement.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# The state can take the following values:
|
||||
# - 0: unlocked
|
||||
# - 1: locked
|
||||
# - <Task>: unlocked but this task has been scheduled to acquire the lock next
|
||||
self.state = 0
|
||||
# Queue of Tasks waiting to acquire this Lock
|
||||
self.waiting = core.TaskQueue()
|
||||
|
||||
def locked(self):
|
||||
"""Returns ``True`` if the lock is locked, otherwise ``False``."""
|
||||
|
||||
return self.state == 1
|
||||
|
||||
def release(self):
|
||||
"""Release the lock. If any tasks are waiting on the lock then the next
|
||||
one in the queue is scheduled to run and the lock remains locked. Otherwise,
|
||||
no tasks are waiting and the lock becomes unlocked.
|
||||
"""
|
||||
|
||||
if self.state != 1:
|
||||
raise RuntimeError("Lock not acquired")
|
||||
if self.waiting.peek():
|
||||
# Task(s) waiting on lock, schedule next Task
|
||||
self.state = self.waiting.pop_head()
|
||||
core._task_queue.push_head(self.state)
|
||||
else:
|
||||
# No Task waiting so unlock
|
||||
self.state = 0
|
||||
|
||||
async def acquire(self):
|
||||
"""Wait for the lock to be in the unlocked state and then lock it in an
|
||||
atomic way. Only one task can acquire the lock at any one time.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
if self.state != 0:
|
||||
# Lock unavailable, put the calling Task on the waiting queue
|
||||
self.waiting.push_head(core.cur_task)
|
||||
# Set calling task's data to the lock's queue so it can be removed if needed
|
||||
core.cur_task.data = self.waiting
|
||||
try:
|
||||
await core._never()
|
||||
except core.CancelledError as er:
|
||||
if self.state == core.cur_task:
|
||||
# Cancelled while pending on resume, schedule next waiting Task
|
||||
self.state = 1
|
||||
self.release()
|
||||
raise er
|
||||
# Lock available, set it as locked
|
||||
self.state = 1
|
||||
return True
|
||||
|
||||
async def __aenter__(self):
|
||||
return await self.acquire()
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
return self.release()
|
||||
24
libs/circuitpython/asyncio/manifest.py
Normal file
24
libs/circuitpython/asyncio/manifest.py
Normal file
@@ -0,0 +1,24 @@
|
||||
# SPDX-FileCopyrightText: 2019 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
|
||||
# This list of frozen files doesn't include task.py because that's provided by the C module.
|
||||
freeze(
|
||||
"..",
|
||||
(
|
||||
"uasyncio/__init__.py",
|
||||
"uasyncio/core.py",
|
||||
"uasyncio/event.py",
|
||||
"uasyncio/funcs.py",
|
||||
"uasyncio/lock.py",
|
||||
"uasyncio/stream.py",
|
||||
),
|
||||
opt=3,
|
||||
)
|
||||
263
libs/circuitpython/asyncio/stream.py
Normal file
263
libs/circuitpython/asyncio/stream.py
Normal file
@@ -0,0 +1,263 @@
|
||||
# SPDX-FileCopyrightText: 2019-2020 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
"""
|
||||
Streams
|
||||
=======
|
||||
"""
|
||||
|
||||
from . import core
|
||||
|
||||
|
||||
class Stream:
|
||||
"""This represents a TCP stream connection. To minimise code this class
|
||||
implements both a reader and a writer, and both ``StreamReader`` and
|
||||
``StreamWriter`` alias to this class.
|
||||
"""
|
||||
|
||||
def __init__(self, s, e={}):
|
||||
self.s = s
|
||||
self.e = e
|
||||
self.out_buf = b""
|
||||
|
||||
def get_extra_info(self, v):
|
||||
"""Get extra information about the stream, given by *v*. The valid
|
||||
values for *v* are: ``peername``.
|
||||
"""
|
||||
|
||||
return self.e[v]
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
await self.close()
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
async def wait_closed(self):
|
||||
"""Wait for the stream to close.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
# TODO yield?
|
||||
self.s.close()
|
||||
|
||||
async def read(self, n):
|
||||
"""Read up to *n* bytes and return them.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
await core._io_queue.queue_read(self.s)
|
||||
return self.s.read(n)
|
||||
|
||||
async def readinto(self, buf):
|
||||
"""Read up to n bytes into *buf* with n being equal to the length of *buf*
|
||||
|
||||
Return the number of bytes read into *buf*
|
||||
|
||||
This is a coroutine, and a MicroPython extension.
|
||||
"""
|
||||
|
||||
await core._io_queue.queue_read(self.s)
|
||||
return self.s.readinto(buf)
|
||||
|
||||
async def readexactly(self, n):
|
||||
"""Read exactly *n* bytes and return them as a bytes object.
|
||||
|
||||
Raises an ``EOFError`` exception if the stream ends before reading
|
||||
*n* bytes.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
r = b""
|
||||
while n:
|
||||
await core._io_queue.queue_read(self.s)
|
||||
r2 = self.s.read(n)
|
||||
if r2 is not None:
|
||||
if not len(r2):
|
||||
raise EOFError
|
||||
r += r2
|
||||
n -= len(r2)
|
||||
return r
|
||||
|
||||
async def readline(self):
|
||||
"""Read a line and return it.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
l = b""
|
||||
while True:
|
||||
await core._io_queue.queue_read(self.s)
|
||||
l2 = self.s.readline() # may do multiple reads but won't block
|
||||
l += l2
|
||||
if not l2 or l[-1] == 10: # \n (check l in case l2 is str)
|
||||
return l
|
||||
|
||||
def write(self, buf):
|
||||
"""Accumulated *buf* to the output buffer. The data is only flushed when
|
||||
`Stream.drain` is called. It is recommended to call `Stream.drain`
|
||||
immediately after calling this function.
|
||||
"""
|
||||
if not self.out_buf:
|
||||
# Try to write immediately to the underlying stream.
|
||||
ret = self.s.write(buf)
|
||||
if ret == len(buf):
|
||||
return
|
||||
if ret is not None:
|
||||
buf = buf[ret:]
|
||||
|
||||
self.out_buf += buf
|
||||
|
||||
async def drain(self):
|
||||
"""Drain (write) all buffered output data out to the stream.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
mv = memoryview(self.out_buf)
|
||||
off = 0
|
||||
while off < len(mv):
|
||||
await core._io_queue.queue_write(self.s)
|
||||
ret = self.s.write(mv[off:])
|
||||
if ret is not None:
|
||||
off += ret
|
||||
self.out_buf = b""
|
||||
|
||||
|
||||
# Stream can be used for both reading and writing to save code size
|
||||
StreamReader = Stream
|
||||
StreamWriter = Stream
|
||||
|
||||
|
||||
# Create a TCP stream connection to a remote host
|
||||
async def open_connection(host, port):
|
||||
"""Open a TCP connection to the given *host* and *port*. The *host* address will
|
||||
be resolved using `socket.getaddrinfo`, which is currently a blocking call.
|
||||
|
||||
Returns a pair of streams: a reader and a writer stream. Will raise a socket-specific
|
||||
``OSError`` if the host could not be resolved or if the connection could not be made.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
from uerrno import EINPROGRESS
|
||||
import usocket as socket
|
||||
|
||||
ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] # TODO this is blocking!
|
||||
s = socket.socket(ai[0], ai[1], ai[2])
|
||||
s.setblocking(False)
|
||||
ss = Stream(s)
|
||||
try:
|
||||
s.connect(ai[-1])
|
||||
except OSError as er:
|
||||
if er.errno != EINPROGRESS:
|
||||
raise er
|
||||
await core._io_queue.queue_write(s)
|
||||
return ss, ss
|
||||
|
||||
|
||||
# Class representing a TCP stream server, can be closed and used in "async with"
|
||||
class Server:
|
||||
"""This represents the server class returned from `start_server`. It can be used in
|
||||
an ``async with`` statement to close the server upon exit.
|
||||
"""
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
self.close()
|
||||
await self.wait_closed()
|
||||
|
||||
def close(self):
|
||||
"""Close the server."""
|
||||
|
||||
self.task.cancel()
|
||||
|
||||
async def wait_closed(self):
|
||||
"""Wait for the server to close.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
await self.task
|
||||
|
||||
async def _serve(self, s, cb):
|
||||
# Accept incoming connections
|
||||
while True:
|
||||
try:
|
||||
await core._io_queue.queue_read(s)
|
||||
except core.CancelledError:
|
||||
# Shutdown server
|
||||
s.close()
|
||||
return
|
||||
try:
|
||||
s2, addr = s.accept()
|
||||
except:
|
||||
# Ignore a failed accept
|
||||
continue
|
||||
s2.setblocking(False)
|
||||
s2s = Stream(s2, {"peername": addr})
|
||||
core.create_task(cb(s2s, s2s))
|
||||
|
||||
|
||||
# Helper function to start a TCP stream server, running as a new task
|
||||
# TODO could use an accept-callback on socket read activity instead of creating a task
|
||||
async def start_server(cb, host, port, backlog=5):
|
||||
"""Start a TCP server on the given *host* and *port*. The *cb* callback will be
|
||||
called with incoming, accepted connections, and be passed 2 arguments: reader
|
||||
writer streams for the connection.
|
||||
|
||||
Returns a `Server` object.
|
||||
|
||||
This is a coroutine.
|
||||
"""
|
||||
|
||||
import usocket as socket
|
||||
|
||||
# Create and bind server socket.
|
||||
host = socket.getaddrinfo(host, port)[0] # TODO this is blocking!
|
||||
s = socket.socket()
|
||||
s.setblocking(False)
|
||||
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
s.bind(host[-1])
|
||||
s.listen(backlog)
|
||||
|
||||
# Create and return server object and task.
|
||||
srv = Server()
|
||||
srv.task = core.create_task(srv._serve(s, cb))
|
||||
return srv
|
||||
|
||||
|
||||
################################################################################
|
||||
# Legacy uasyncio compatibility
|
||||
|
||||
|
||||
async def stream_awrite(self, buf, off=0, sz=-1):
|
||||
if off != 0 or sz != -1:
|
||||
buf = memoryview(buf)
|
||||
if sz == -1:
|
||||
sz = len(buf)
|
||||
buf = buf[off : off + sz]
|
||||
self.write(buf)
|
||||
await self.drain()
|
||||
|
||||
|
||||
Stream.aclose = Stream.wait_closed
|
||||
Stream.awrite = stream_awrite
|
||||
Stream.awritestr = stream_awrite # TODO explicitly convert to bytes?
|
||||
215
libs/circuitpython/asyncio/task.py
Normal file
215
libs/circuitpython/asyncio/task.py
Normal file
@@ -0,0 +1,215 @@
|
||||
# SPDX-FileCopyrightText: 2019-2020 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
||||
#
|
||||
# This code comes from MicroPython, and has not been run through black or pylint there.
|
||||
# Altering these files significantly would make merging difficult, so we will not use
|
||||
# pylint or black.
|
||||
# pylint: skip-file
|
||||
# fmt: off
|
||||
"""
|
||||
Tasks
|
||||
=====
|
||||
"""
|
||||
|
||||
# This file contains the core TaskQueue based on a pairing heap, and the core Task class.
|
||||
# They can optionally be replaced by C implementations.
|
||||
|
||||
from . import core
|
||||
|
||||
|
||||
# pairing-heap meld of 2 heaps; O(1)
|
||||
def ph_meld(h1, h2):
|
||||
if h1 is None:
|
||||
return h2
|
||||
if h2 is None:
|
||||
return h1
|
||||
lt = core.ticks_diff(h1.ph_key, h2.ph_key) < 0
|
||||
if lt:
|
||||
if h1.ph_child is None:
|
||||
h1.ph_child = h2
|
||||
else:
|
||||
h1.ph_child_last.ph_next = h2
|
||||
h1.ph_child_last = h2
|
||||
h2.ph_next = None
|
||||
h2.ph_rightmost_parent = h1
|
||||
return h1
|
||||
else:
|
||||
h1.ph_next = h2.ph_child
|
||||
h2.ph_child = h1
|
||||
if h1.ph_next is None:
|
||||
h2.ph_child_last = h1
|
||||
h1.ph_rightmost_parent = h2
|
||||
return h2
|
||||
|
||||
|
||||
# pairing-heap pairing operation; amortised O(log N)
|
||||
def ph_pairing(child):
|
||||
heap = None
|
||||
while child is not None:
|
||||
n1 = child
|
||||
child = child.ph_next
|
||||
n1.ph_next = None
|
||||
if child is not None:
|
||||
n2 = child
|
||||
child = child.ph_next
|
||||
n2.ph_next = None
|
||||
n1 = ph_meld(n1, n2)
|
||||
heap = ph_meld(heap, n1)
|
||||
return heap
|
||||
|
||||
|
||||
# pairing-heap delete of a node; stable, amortised O(log N)
|
||||
def ph_delete(heap, node):
|
||||
if node is heap:
|
||||
child = heap.ph_child
|
||||
node.ph_child = None
|
||||
return ph_pairing(child)
|
||||
# Find parent of node
|
||||
parent = node
|
||||
while parent.ph_next is not None:
|
||||
parent = parent.ph_next
|
||||
parent = parent.ph_rightmost_parent
|
||||
# Replace node with pairing of its children
|
||||
if node is parent.ph_child and node.ph_child is None:
|
||||
parent.ph_child = node.ph_next
|
||||
node.ph_next = None
|
||||
return heap
|
||||
elif node is parent.ph_child:
|
||||
child = node.ph_child
|
||||
next = node.ph_next
|
||||
node.ph_child = None
|
||||
node.ph_next = None
|
||||
node = ph_pairing(child)
|
||||
parent.ph_child = node
|
||||
else:
|
||||
n = parent.ph_child
|
||||
while node is not n.ph_next:
|
||||
n = n.ph_next
|
||||
child = node.ph_child
|
||||
next = node.ph_next
|
||||
node.ph_child = None
|
||||
node.ph_next = None
|
||||
node = ph_pairing(child)
|
||||
if node is None:
|
||||
node = n
|
||||
else:
|
||||
n.ph_next = node
|
||||
node.ph_next = next
|
||||
if next is None:
|
||||
node.ph_rightmost_parent = parent
|
||||
parent.ph_child_last = node
|
||||
return heap
|
||||
|
||||
|
||||
# TaskQueue class based on the above pairing-heap functions.
|
||||
class TaskQueue:
|
||||
def __init__(self):
|
||||
self.heap = None
|
||||
|
||||
def peek(self):
|
||||
return self.heap
|
||||
|
||||
def push(self, v, key=None):
|
||||
assert v.ph_child is None
|
||||
assert v.ph_next is None
|
||||
v.data = None
|
||||
v.ph_key = key if key is not None else core.ticks()
|
||||
self.heap = ph_meld(v, self.heap)
|
||||
|
||||
def pop(self):
|
||||
v = self.heap
|
||||
assert v.ph_next is None
|
||||
self.heap = ph_pairing(v.ph_child)
|
||||
v.ph_child = None
|
||||
return v
|
||||
|
||||
def remove(self, v):
|
||||
self.heap = ph_delete(self.heap, v)
|
||||
|
||||
# Compatibility aliases, remove after they are no longer used
|
||||
push_head = push
|
||||
push_sorted = push
|
||||
pop_head = pop
|
||||
|
||||
# Task class representing a coroutine, can be waited on and cancelled.
|
||||
class Task:
|
||||
"""This object wraps a coroutine into a running task. Tasks can be waited on
|
||||
using ``await task``, which will wait for the task to complete and return the
|
||||
return value of the task.
|
||||
|
||||
Tasks should not be created directly, rather use ``create_task`` to create them.
|
||||
"""
|
||||
|
||||
def __init__(self, coro, globals=None):
|
||||
self.coro = coro # Coroutine of this Task
|
||||
self.data = None # General data for queue it is waiting on
|
||||
self.state = True # None, False, True, a callable, or a TaskQueue instance
|
||||
self.ph_key = 0 # Pairing heap
|
||||
self.ph_child = None # Paring heap
|
||||
self.ph_child_last = None # Paring heap
|
||||
self.ph_next = None # Paring heap
|
||||
self.ph_rightmost_parent = None # Paring heap
|
||||
|
||||
def __iter__(self):
|
||||
if not self.state:
|
||||
# Task finished, signal that is has been await'ed on.
|
||||
self.state = False
|
||||
elif self.state is True:
|
||||
# Allocated head of linked list of Tasks waiting on completion of this task.
|
||||
self.state = TaskQueue()
|
||||
elif type(self.state) is not TaskQueue:
|
||||
# Task has state used for another purpose, so can't also wait on it.
|
||||
raise RuntimeError("can't wait")
|
||||
return self
|
||||
|
||||
# CircuitPython needs __await()__.
|
||||
__await__ = __iter__
|
||||
|
||||
def __next__(self):
|
||||
if not self.state:
|
||||
if self.data is None:
|
||||
# Task finished but has already been sent to the loop's exception handler.
|
||||
raise StopIteration
|
||||
else:
|
||||
# Task finished, raise return value to caller so it can continue.
|
||||
raise self.data
|
||||
else:
|
||||
# Put calling task on waiting queue.
|
||||
self.state.push(core.cur_task)
|
||||
# Set calling task's data to this task that it waits on, to double-link it.
|
||||
core.cur_task.data = self
|
||||
|
||||
def done(self):
|
||||
"""Whether the task is complete."""
|
||||
|
||||
return not self.state
|
||||
|
||||
def cancel(self):
|
||||
"""Cancel the task by injecting a ``CancelledError`` into it. The task
|
||||
may or may not ignore this exception.
|
||||
"""
|
||||
|
||||
# Check if task is already finished.
|
||||
if not self.state:
|
||||
return False
|
||||
# Can't cancel self (not supported yet).
|
||||
if self is core.cur_task:
|
||||
raise RuntimeError("can't cancel self")
|
||||
# If Task waits on another task then forward the cancel to the one it's waiting on.
|
||||
while isinstance(self.data, Task):
|
||||
self = self.data
|
||||
# Reschedule Task as a cancelled task.
|
||||
if hasattr(self.data, "remove"):
|
||||
# Not on the main running queue, remove the task from the queue it's on.
|
||||
self.data.remove(self)
|
||||
core._task_queue.push(self)
|
||||
elif core.ticks_diff(self.ph_key, core.ticks()) > 0:
|
||||
# On the main running queue but scheduled in the future, so bring it forward to now.
|
||||
core._task_queue.remove(self)
|
||||
core._task_queue.push(self)
|
||||
self.data = core.CancelledError
|
||||
return True
|
||||
57
libs/circuitpython/asyncio/traceback.py
Normal file
57
libs/circuitpython/asyncio/traceback.py
Normal file
@@ -0,0 +1,57 @@
|
||||
# SPDX-FileCopyrightText: 2019-2020 Damien P. George
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
#
|
||||
# MicroPython uasyncio module
|
||||
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
||||
"""
|
||||
Fallback traceback module if the system traceback is missing.
|
||||
"""
|
||||
|
||||
try:
|
||||
from typing import List
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def _print_traceback(traceback, limit=None, file=sys.stderr) -> List[str]:
|
||||
if limit is None:
|
||||
if hasattr(sys, "tracebacklimit"):
|
||||
limit = sys.tracebacklimit
|
||||
|
||||
n = 0
|
||||
while traceback is not None:
|
||||
frame = traceback.tb_frame
|
||||
line_number = traceback.tb_lineno
|
||||
frame_code = frame.f_code
|
||||
filename = frame_code.co_filename
|
||||
name = frame_code.co_name
|
||||
print(' File "%s", line %d, in %s' % (filename, line_number, name), file=file)
|
||||
traceback = traceback.tb_next
|
||||
n = n + 1
|
||||
if limit is not None and n >= limit:
|
||||
break
|
||||
|
||||
|
||||
def print_exception(exception, value=None, traceback=None, limit=None, file=sys.stderr):
|
||||
"""
|
||||
Print exception information and stack trace to file.
|
||||
"""
|
||||
if traceback:
|
||||
print("Traceback (most recent call last):", file=file)
|
||||
_print_traceback(traceback, limit=limit, file=file)
|
||||
|
||||
if isinstance(exception, BaseException):
|
||||
exception_type = type(exception).__name__
|
||||
elif hasattr(exception, "__name__"):
|
||||
exception_type = exception.__name__
|
||||
else:
|
||||
exception_type = type(value).__name__
|
||||
|
||||
valuestr = str(value)
|
||||
if value is None or not valuestr:
|
||||
print(exception_type, file=file)
|
||||
else:
|
||||
print("%s: %s" % (str(exception_type), valuestr), file=file)
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "microdot"
|
||||
version = "2.0.3"
|
||||
version = "2.5.1"
|
||||
authors = [
|
||||
{ name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" },
|
||||
]
|
||||
@@ -14,6 +14,8 @@ classifiers = [
|
||||
"Operating System :: OS Independent",
|
||||
]
|
||||
requires-python = ">=3.8"
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
[project.readme]
|
||||
file = "README.md"
|
||||
@@ -24,8 +26,13 @@ Homepage = "https://github.com/miguelgrinberg/microdot"
|
||||
"Bug Tracker" = "https://github.com/miguelgrinberg/microdot/issues"
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"tox",
|
||||
]
|
||||
docs = [
|
||||
"sphinx",
|
||||
"furo",
|
||||
"pyjwt",
|
||||
]
|
||||
|
||||
[tool.setuptools]
|
||||
|
||||
@@ -2,7 +2,11 @@ import sys
|
||||
|
||||
sys.path.insert(0, 'src')
|
||||
sys.path.insert(2, 'libs/common')
|
||||
sys.path.insert(3, 'libs/micropython')
|
||||
if sys.implementation.name == 'circuitpython':
|
||||
sys.path.insert(3, 'libs/circuitpython')
|
||||
sys.path.insert(4, 'libs/micropython')
|
||||
else:
|
||||
sys.path.insert(3, 'libs/micropython')
|
||||
|
||||
import unittest
|
||||
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
|
||||
send_file # noqa: F401
|
||||
send_file, URLPattern, AsyncBytesIO, iscoroutine # noqa: F401
|
||||
|
||||
__version__ = '2.5.1'
|
||||
|
||||
@@ -48,15 +48,47 @@ class Microdot(BaseMicrodot):
|
||||
"""A subclass of the core :class:`Microdot <microdot.Microdot>` class that
|
||||
implements the ASGI protocol.
|
||||
|
||||
:param startup: An optional function to handle the `lifespan.startup` ASGI
|
||||
signal.
|
||||
:param shutdown: An optional function to handle the `lifespan.shutdown`
|
||||
ASGI signal.
|
||||
|
||||
This class must be used as the application instance when running under an
|
||||
ASGI web server.
|
||||
"""
|
||||
def __init__(self):
|
||||
def __init__(self, lifespan_startup=None, lifespan_shutdown=None):
|
||||
super().__init__()
|
||||
self.lifespan_startup = lifespan_startup
|
||||
self.lifespan_shutdown = lifespan_shutdown
|
||||
self.embedded_server = False
|
||||
|
||||
async def handle_lifespan(self, scope, receive, send):
|
||||
while True:
|
||||
message = await receive()
|
||||
if message['type'] == 'lifespan.startup':
|
||||
try:
|
||||
if self.lifespan_startup:
|
||||
await self.lifespan_startup(scope)
|
||||
except Exception as e:
|
||||
await send({'type': 'lifespan.startup.failed',
|
||||
'message': repr(e)})
|
||||
else:
|
||||
await send({'type': 'lifespan.startup.complete'})
|
||||
elif message['type'] == 'lifespan.shutdown': # pragma: no branch
|
||||
try:
|
||||
if self.lifespan_shutdown:
|
||||
await self.lifespan_shutdown(scope)
|
||||
except Exception as e:
|
||||
await send({'type': 'lifespan.shutdown.failed',
|
||||
'message': repr(e)})
|
||||
else:
|
||||
await send({'type': 'lifespan.shutdown.complete'})
|
||||
break
|
||||
|
||||
async def asgi_app(self, scope, receive, send):
|
||||
"""An ASGI application."""
|
||||
if scope['type'] == 'lifespan':
|
||||
return await self.handle_lifespan(scope, receive, send)
|
||||
if scope['type'] not in ['http', 'websocket']: # pragma: no cover
|
||||
return
|
||||
path = scope['path']
|
||||
@@ -91,7 +123,8 @@ class Microdot(BaseMicrodot):
|
||||
headers,
|
||||
body=body,
|
||||
stream=stream,
|
||||
sock=(receive, send))
|
||||
sock=(receive, send),
|
||||
scheme=scope.get('scheme'))
|
||||
req.asgi_scope = scope
|
||||
|
||||
res = await self.dispatch_request(req)
|
||||
@@ -127,19 +160,19 @@ class Microdot(BaseMicrodot):
|
||||
monitor_task = asyncio.ensure_future(cancel_monitor())
|
||||
|
||||
body_iter = res.body_iter().__aiter__()
|
||||
res_body = b''
|
||||
try:
|
||||
res_body = await body_iter.__anext__()
|
||||
while not cancelled: # pragma: no branch
|
||||
next_body = await body_iter.__anext__()
|
||||
res_body = await body_iter.__anext__()
|
||||
if isinstance(res_body, str):
|
||||
res_body = res_body.encode()
|
||||
await send({'type': 'http.response.body',
|
||||
'body': res_body,
|
||||
'more_body': True})
|
||||
res_body = next_body
|
||||
except StopAsyncIteration:
|
||||
await send({'type': 'http.response.body',
|
||||
'body': res_body,
|
||||
'more_body': False})
|
||||
pass
|
||||
await send({'type': 'http.response.body',
|
||||
'body': b'',
|
||||
'more_body': False})
|
||||
if hasattr(body_iter, 'aclose'): # pragma: no branch
|
||||
await body_iter.aclose()
|
||||
cancelled = True
|
||||
|
||||
162
src/microdot/auth.py
Normal file
162
src/microdot/auth.py
Normal file
@@ -0,0 +1,162 @@
|
||||
from microdot import abort
|
||||
from microdot.microdot import invoke_handler
|
||||
|
||||
|
||||
class BaseAuth:
|
||||
def __init__(self):
|
||||
self.auth_callback = None
|
||||
self.error_callback = None
|
||||
|
||||
def __call__(self, f):
|
||||
"""Decorator to protect a route with authentication.
|
||||
|
||||
An instance of this class must be used as a decorator on the routes
|
||||
that need to be protected. Example::
|
||||
|
||||
auth = BasicAuth() # or TokenAuth()
|
||||
|
||||
@app.route('/protected')
|
||||
@auth
|
||||
def protected(request):
|
||||
# ...
|
||||
|
||||
Routes that are decorated in this way will only be invoked if the
|
||||
authentication callback returned a valid user object, otherwise the
|
||||
error callback will be executed.
|
||||
"""
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
auth = self._get_auth(request)
|
||||
if not auth:
|
||||
return await invoke_handler(self.error_callback, request)
|
||||
request.g.current_user = await invoke_handler(
|
||||
self.auth_callback, request, *auth)
|
||||
if not request.g.current_user:
|
||||
return await invoke_handler(self.error_callback, request)
|
||||
return await invoke_handler(f, request, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def optional(self, f):
|
||||
"""Decorator to protect a route with optional authentication.
|
||||
|
||||
This decorator makes authentication for the decorated route optional,
|
||||
meaning that the route is allowed to run with or with
|
||||
authentication given in the request.
|
||||
"""
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
auth = self._get_auth(request)
|
||||
if not auth:
|
||||
request.g.current_user = None
|
||||
else:
|
||||
request.g.current_user = await invoke_handler(
|
||||
self.auth_callback, request, *auth)
|
||||
return await invoke_handler(f, request, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class BasicAuth(BaseAuth):
|
||||
"""Basic Authentication.
|
||||
|
||||
:param realm: The realm that is displayed when the user is prompted to
|
||||
authenticate in the browser.
|
||||
:param charset: The charset that is used to encode the realm.
|
||||
:param scheme: The authentication scheme. Defaults to 'Basic'.
|
||||
:param error_status: The error status code to return when authentication
|
||||
fails. Defaults to 401.
|
||||
"""
|
||||
def __init__(self, realm='Please login', charset='UTF-8', scheme='Basic',
|
||||
error_status=401):
|
||||
super().__init__()
|
||||
self.realm = realm
|
||||
self.charset = charset
|
||||
self.scheme = scheme
|
||||
self.error_status = error_status
|
||||
self.error_callback = self.authentication_error
|
||||
|
||||
def _get_auth(self, request):
|
||||
auth = request.headers.get('Authorization')
|
||||
if auth and auth.startswith('Basic '):
|
||||
import binascii
|
||||
try:
|
||||
username, password = binascii.a2b_base64(
|
||||
auth[6:]).decode().split(':', 1)
|
||||
except Exception: # pragma: no cover
|
||||
return None
|
||||
return username, password
|
||||
|
||||
async def authentication_error(self, request):
|
||||
return '', self.error_status, {
|
||||
'WWW-Authenticate': '{} realm="{}", charset="{}"'.format(
|
||||
self.scheme, self.realm, self.charset)}
|
||||
|
||||
def authenticate(self, f):
|
||||
"""Decorator to configure the authentication callback.
|
||||
|
||||
This decorator must be used with a function that accepts the request
|
||||
object, a username and a password and returns a user object if the
|
||||
credentials are valid, or ``None`` if they are not. Example::
|
||||
|
||||
@auth.authenticate
|
||||
async def check_credentials(request, username, password):
|
||||
user = get_user(username)
|
||||
if user and user.check_password(password):
|
||||
return get_user(username)
|
||||
"""
|
||||
self.auth_callback = f
|
||||
|
||||
|
||||
class TokenAuth(BaseAuth):
|
||||
"""Token based authentication.
|
||||
|
||||
:param header: The name of the header that will contain the token. Defaults
|
||||
to 'Authorization'.
|
||||
:param scheme: The authentication scheme. Defaults to 'Bearer'.
|
||||
:param error_status: The error status code to return when authentication
|
||||
fails. Defaults to 401.
|
||||
"""
|
||||
def __init__(self, header='Authorization', scheme='Bearer',
|
||||
error_status=401):
|
||||
super().__init__()
|
||||
self.header = header
|
||||
self.scheme = scheme.lower()
|
||||
self.error_status = error_status
|
||||
self.error_callback = self.authentication_error
|
||||
|
||||
def _get_auth(self, request):
|
||||
auth = request.headers.get(self.header)
|
||||
if auth:
|
||||
if self.header == 'Authorization':
|
||||
try:
|
||||
scheme, token = auth.split(' ', 1)
|
||||
except Exception:
|
||||
return None
|
||||
if scheme.lower() == self.scheme:
|
||||
return (token.strip(),)
|
||||
else:
|
||||
return (auth,)
|
||||
|
||||
def authenticate(self, f):
|
||||
"""Decorator to configure the authentication callback.
|
||||
|
||||
This decorator must be used with a function that accepts the request
|
||||
object, a username and a password and returns a user object if the
|
||||
credentials are valid, or ``None`` if they are not. Example::
|
||||
|
||||
@auth.authenticate
|
||||
async def check_credentials(request, token):
|
||||
return get_user(token)
|
||||
"""
|
||||
self.auth_callback = f
|
||||
|
||||
def errorhandler(self, f):
|
||||
"""Decorator to configure the error callback.
|
||||
|
||||
Microdot calls the error callback to allow the application to generate
|
||||
a custom error response. The default error response is to call
|
||||
``abort(401)``.
|
||||
"""
|
||||
self.error_callback = f
|
||||
|
||||
async def authentication_error(self, request):
|
||||
abort(self.error_status)
|
||||
@@ -104,7 +104,8 @@ class CORS:
|
||||
|
||||
def after_request(self, request, response):
|
||||
saved_vary = response.headers.get('Vary')
|
||||
response.headers.update(self.get_cors_headers(request))
|
||||
if request: # pragma: no branch
|
||||
response.headers.update(self.get_cors_headers(request))
|
||||
if saved_vary and saved_vary != response.headers.get('Vary'):
|
||||
response.headers['Vary'] = (
|
||||
saved_vary + ', ' + response.headers['Vary'])
|
||||
|
||||
120
src/microdot/csrf.py
Normal file
120
src/microdot/csrf.py
Normal file
@@ -0,0 +1,120 @@
|
||||
from microdot import abort
|
||||
|
||||
|
||||
class CSRF:
|
||||
"""CSRF protection for Microdot routes.
|
||||
|
||||
:param app: The application instance.
|
||||
:param cors: The ``CORS`` instance that defines the origins that are
|
||||
trusted by the application. This is used to validate requests
|
||||
from older browsers that do not send the ``Sec-Fetch-Site``
|
||||
header.
|
||||
:param protect_all: If ``True``, all state changing routes are protected by
|
||||
default, with the exception of routes that are
|
||||
decorated with the :meth:`exempt <exempt>` decorator.
|
||||
If ``False``, only routes decorated with the
|
||||
:meth:`protect <protect>` decorator are protected. The
|
||||
default is ``True``.
|
||||
:param allow_subdomains: If ``True``, requests from subdomains of the
|
||||
application domain are trusted. The default is
|
||||
``False``.
|
||||
|
||||
CSRF protection is implemented by checking the ``Sec-Fetch-Site`` sent by
|
||||
browsers. When the ``cors`` argument is provided, requests from older
|
||||
browsers that do not support the ``Sec-Fetch-Site`` header are validated
|
||||
by checking the ``Origin`` header.
|
||||
"""
|
||||
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
|
||||
|
||||
def __init__(self, app=None, cors=None, protect_all=True,
|
||||
allow_subdomains=False):
|
||||
self.cors = None
|
||||
self.protect_all = protect_all
|
||||
self.allow_subdomains = allow_subdomains
|
||||
self.exempt_routes = []
|
||||
self.protected_routes = []
|
||||
if app is not None:
|
||||
self.initialize(app, cors)
|
||||
|
||||
def initialize(self, app, cors=None):
|
||||
"""Initialize the CSRF class.
|
||||
|
||||
:param app: The application instance.
|
||||
:param cors: The ``CORS`` instance that defines the origins that are
|
||||
trusted by the application. This is used to validate
|
||||
requests from older browsers that do not send the
|
||||
``Sec-Fetch-Site`` header.
|
||||
"""
|
||||
self.cors = cors
|
||||
|
||||
@app.before_request
|
||||
async def csrf_before_request(request):
|
||||
if (
|
||||
self.protect_all
|
||||
and request.method not in self.SAFE_METHODS
|
||||
and request.route not in self.exempt_routes
|
||||
) or request.route in self.protected_routes:
|
||||
allow = False
|
||||
sfs = request.headers.get('Sec-Fetch-Site')
|
||||
origin = request.headers.get('Origin')
|
||||
if sfs:
|
||||
# if the Sec-Fetch-Site header was given, ensure it is not
|
||||
# cross-site
|
||||
if sfs in ['same-origin', 'none']:
|
||||
allow = True
|
||||
elif sfs == 'same-site' and self.allow_subdomains:
|
||||
allow = True
|
||||
if not allow and origin and self.cors and \
|
||||
self.cors.allowed_origins != '*':
|
||||
# if we have a list of allowed origins, then we can
|
||||
# validate the origin
|
||||
if not self.allow_subdomains:
|
||||
allow = origin in self.cors.allowed_origins
|
||||
else:
|
||||
origin_scheme, origin_host = origin.split('://', 1)
|
||||
for allowed_origin in self.cors.allowed_origins:
|
||||
allowed_scheme, allowed_host = \
|
||||
allowed_origin.split('://', 1)
|
||||
if origin == allowed_origin or (
|
||||
origin_host.endswith('.' + allowed_host)
|
||||
and origin_scheme == allowed_scheme
|
||||
):
|
||||
allow = True
|
||||
break
|
||||
if not allow and not sfs and not origin:
|
||||
allow = True # no headers to check
|
||||
|
||||
if not allow:
|
||||
abort(403, 'Forbidden')
|
||||
|
||||
def exempt(self, f):
|
||||
"""Decorator to exempt a route from CSRF protection.
|
||||
|
||||
This decorator must be added immediately after the route decorator to
|
||||
disable CSRF protection on the route. Example::
|
||||
|
||||
@app.post('/submit')
|
||||
@csrf.exempt
|
||||
# add additional decorators here
|
||||
def submit(request):
|
||||
# ...
|
||||
"""
|
||||
self.exempt_routes.append(f)
|
||||
return f
|
||||
|
||||
def protect(self, f):
|
||||
"""Decorator to protect a route against CSRF attacks.
|
||||
|
||||
This is useful when it is necessary to protect a request that uses one
|
||||
of the safe methods that are not supposed to make state changes. The
|
||||
decorator must be added immediately after the route decorator to
|
||||
disable CSRF protection on the route. Example::
|
||||
|
||||
@app.get('/data')
|
||||
@csrf.force
|
||||
# add additional decorators here
|
||||
def get_data(request):
|
||||
# ...
|
||||
"""
|
||||
self.protected_routes.append(f)
|
||||
return f
|
||||
8
src/microdot/helpers.py
Normal file
8
src/microdot/helpers.py
Normal file
@@ -0,0 +1,8 @@
|
||||
try:
|
||||
from functools import wraps
|
||||
except ImportError: # pragma: no cover
|
||||
# MicroPython does not currently implement functools.wraps
|
||||
def wraps(wrapped):
|
||||
def _(wrapper):
|
||||
return wrapper
|
||||
return _
|
||||
@@ -1,19 +1,27 @@
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
|
||||
_jinja_env = None
|
||||
|
||||
|
||||
class Template:
|
||||
"""A template object.
|
||||
|
||||
:param template: The filename of the template to render, relative to the
|
||||
configured template directory.
|
||||
:param kwargs: any additional options to be passed to the Jinja
|
||||
environment's ``get_template()`` method.
|
||||
"""
|
||||
#: The Jinja environment. The ``initialize()`` method must be called before
|
||||
#: this attribute is accessed.
|
||||
jinja_env = None
|
||||
|
||||
@classmethod
|
||||
def initialize(cls, template_dir='templates', enable_async=False,
|
||||
**kwargs):
|
||||
"""Initialize the templating subsystem.
|
||||
|
||||
This method is automatically invoked when the first template is
|
||||
created. The application can call it explicitly if custom options need
|
||||
to be provided.
|
||||
|
||||
:param template_dir: the directory where templates are stored. This
|
||||
argument is optional. The default is to load
|
||||
templates from a *templates* subdirectory.
|
||||
@@ -23,20 +31,19 @@ class Template:
|
||||
:param kwargs: any additional options to be passed to Jinja's
|
||||
``Environment`` class.
|
||||
"""
|
||||
global _jinja_env
|
||||
_jinja_env = Environment(
|
||||
cls.jinja_env = Environment(
|
||||
loader=FileSystemLoader(template_dir),
|
||||
autoescape=select_autoescape(),
|
||||
enable_async=enable_async,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
def __init__(self, template):
|
||||
if _jinja_env is None: # pragma: no cover
|
||||
def __init__(self, template, **kwargs):
|
||||
if self.jinja_env is None: # pragma: no cover
|
||||
self.initialize()
|
||||
#: The name of the template
|
||||
#: The name of the template.
|
||||
self.name = template
|
||||
self.template = _jinja_env.get_template(template)
|
||||
self.template = self.jinja_env.get_template(template, **kwargs)
|
||||
|
||||
def generate(self, *args, **kwargs):
|
||||
"""Return a generator that renders the template in chunks, with the
|
||||
|
||||
172
src/microdot/login.py
Normal file
172
src/microdot/login.py
Normal file
@@ -0,0 +1,172 @@
|
||||
from time import time
|
||||
from microdot import redirect
|
||||
from microdot.microdot import urlencode, invoke_handler
|
||||
|
||||
|
||||
class Login:
|
||||
"""User login support for Microdot.
|
||||
|
||||
:param login_url: the URL to redirect to when a login is required. The
|
||||
default is '/login'.
|
||||
"""
|
||||
def __init__(self, login_url='/login'):
|
||||
self.login_url = login_url
|
||||
self.user_loader_callback = None
|
||||
|
||||
def user_loader(self, f):
|
||||
"""Decorator to configure the user callback.
|
||||
|
||||
The decorated function receives the user ID as an argument and must
|
||||
return the corresponding user object, or ``None`` if the user ID is
|
||||
invalid.
|
||||
"""
|
||||
self.user_loader_callback = f
|
||||
|
||||
def _get_session(self, request):
|
||||
return request.app._session.get(request)
|
||||
|
||||
def _update_remember_cookie(self, request, days, user_id=None):
|
||||
remember_payload = request.app._session.encode({
|
||||
'user_id': user_id,
|
||||
'days': days,
|
||||
'exp': time() + days * 24 * 60 * 60
|
||||
})
|
||||
|
||||
@request.after_request
|
||||
async def _set_remember_cookie(request, response):
|
||||
response.set_cookie('_remember', remember_payload,
|
||||
max_age=days * 24 * 60 * 60)
|
||||
return response
|
||||
|
||||
def _get_user_id_from_session(self, request):
|
||||
session = self._get_session(request)
|
||||
if session and '_user_id' in session:
|
||||
return session['_user_id']
|
||||
if '_remember' in request.cookies:
|
||||
remember_payload = request.app._session.decode(
|
||||
request.cookies['_remember'])
|
||||
user_id = remember_payload.get('user_id')
|
||||
if user_id: # pragma: no branch
|
||||
self._update_remember_cookie(
|
||||
request, remember_payload.get('_days', 30), user_id)
|
||||
session['_user_id'] = user_id
|
||||
session['_fresh'] = False
|
||||
session.save()
|
||||
return user_id
|
||||
|
||||
async def _redirect_to_login(self, request):
|
||||
return '', 302, {'Location': self.login_url + '?next=' + urlencode(
|
||||
request.url)}
|
||||
|
||||
async def login_user(self, request, user, remember=False,
|
||||
redirect_url='/'):
|
||||
"""Log a user in.
|
||||
|
||||
:param request: the request object
|
||||
:param user: the user object
|
||||
:param remember: if the user's logged in state should be remembered
|
||||
with a cookie after the session ends. Set to the
|
||||
number of days the remember cookie should last, or to
|
||||
``True`` to use a default duration of 30 days.
|
||||
:param redirect_url: the URL to redirect to after login
|
||||
|
||||
This call marks the user as logged in by storing their user ID in the
|
||||
user session. The application must call this method to log a user in
|
||||
after their credentials have been validated.
|
||||
|
||||
The method returns a redirect response, either to the URL the user
|
||||
originally intended to visit, or if there is no original URL to the URL
|
||||
specified by the `redirect_url`.
|
||||
"""
|
||||
session = self._get_session(request)
|
||||
session['_user_id'] = user.id
|
||||
session['_fresh'] = True
|
||||
session.save()
|
||||
request.g.current_user = user
|
||||
|
||||
if remember:
|
||||
days = 30 if remember is True else int(remember)
|
||||
self._update_remember_cookie(request, days, session['_user_id'])
|
||||
|
||||
next_url = request.args.get('next', redirect_url)
|
||||
if not next_url.startswith('/'):
|
||||
next_url = redirect_url
|
||||
return redirect(next_url)
|
||||
|
||||
async def logout_user(self, request):
|
||||
"""Log a user out.
|
||||
|
||||
:param request: the request object
|
||||
|
||||
This call removes information about the user's log in from the user
|
||||
session. If a remember cookie exists, it is removed as well.
|
||||
"""
|
||||
session = self._get_session(request)
|
||||
session.pop('_user_id', None)
|
||||
session.pop('_fresh', None)
|
||||
session.save()
|
||||
request.g.current_user = None
|
||||
if '_remember' in request.cookies:
|
||||
self._update_remember_cookie(request, 0)
|
||||
|
||||
async def get_current_user(self, request):
|
||||
"""Return the currently logged in user."""
|
||||
if not hasattr(request.g, 'current_user'):
|
||||
user_id = self._get_user_id_from_session(request)
|
||||
if user_id:
|
||||
request.g.current_user = await invoke_handler(
|
||||
self.user_loader_callback, user_id)
|
||||
else:
|
||||
request.g.current_user = None
|
||||
return request.g.current_user
|
||||
|
||||
def __call__(self, f):
|
||||
"""Decorator to protect a route with authentication.
|
||||
|
||||
If the user is not logged in, Microdot will redirect to the login page
|
||||
first. The decorated route will only run after successful login by the
|
||||
user. If the user is already logged in, the route will run immediately.
|
||||
Example::
|
||||
|
||||
login = Login()
|
||||
|
||||
@app.route('/secret')
|
||||
@login
|
||||
async def secret(request):
|
||||
# only accessible to authenticated users
|
||||
|
||||
"""
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
user = await self.get_current_user(request)
|
||||
if not user:
|
||||
return await self._redirect_to_login(request)
|
||||
return await invoke_handler(f, request, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def fresh(self, f):
|
||||
"""Decorator to protect a route with "fresh" authentication.
|
||||
|
||||
This decorator prevents the route from running when the login session
|
||||
is not fresh. A fresh session is a session that has been created from
|
||||
direct user interaction with the login page, while a non-fresh session
|
||||
occurs when a login is restored from a "remember me" cookie. Example::
|
||||
|
||||
login = Login()
|
||||
|
||||
@app.route('/secret')
|
||||
@auth.fresh
|
||||
async def secret(request):
|
||||
# only accessible to authenticated users
|
||||
# users logged in via remember me cookie will need to
|
||||
# re-authenticate
|
||||
"""
|
||||
base_wrapper = self.__call__(f)
|
||||
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
session = self._get_session(request)
|
||||
if session.get('_fresh'):
|
||||
return await base_wrapper(request, *args, **kwargs)
|
||||
return await self._redirect_to_login(request)
|
||||
|
||||
return wrapper
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user