Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb856e1bc7 | ||
|
|
110d7de6a9 | ||
|
|
46b120bc87 | ||
|
|
ddb3b8f442 | ||
|
|
9398c96075 | ||
|
|
4d432a7d6c | ||
|
|
d0d358f94a | ||
|
|
680cd9c023 | ||
|
|
ec72d54203 | ||
|
|
c00b24c943 | ||
|
|
878a911afc | ||
|
|
ecd84ecb7b | ||
|
|
fcaeee6905 | ||
|
|
427a4d49de | ||
|
|
f56c826149 | ||
|
|
2aa90d4245 | ||
|
|
8139498023 | ||
|
|
3d6815119c | ||
|
|
818f98d9a4 | ||
|
|
dd15d90239 | ||
|
|
d42388d6fe | ||
|
|
1abe8edc56 | ||
|
|
e69c2dc42f | ||
|
|
5a589afd5e | ||
|
|
c841cbedda | ||
|
|
24d74fb848 | ||
|
|
4a9b92b800 | ||
|
|
c443599089 | ||
|
|
6554f29ddc | ||
|
|
211ad953ae | ||
|
|
63f43e1e7e | ||
|
|
cb2a23285e | ||
|
|
b133dcc343 | ||
|
|
01947b101e | ||
|
|
1547e861ee | ||
|
|
672512e086 | ||
|
|
a8515c97b0 | ||
|
|
8ebe81c09b | ||
|
|
4f263c63ab | ||
|
|
b0fd6c4323 | ||
|
|
cbefb6bf3a | ||
|
|
c81a2649c5 | ||
|
|
ff178508f9 | ||
|
|
5693b812ce | ||
|
|
f540e04ffe | ||
|
|
c028e4eddb | ||
|
|
51a0aa62e1 | ||
|
|
dc7a041ebd | ||
|
|
59453a52a1 | ||
|
|
75725795b4 | ||
|
|
019eb4d6bb | ||
|
|
fe750feb03 | ||
|
|
b61f51f243 | ||
|
|
2399c29c8a | ||
|
|
ec0f9ba855 | ||
|
|
a01fc9c3f0 | ||
|
|
3c125c43d2 | ||
|
|
e767426228 | ||
|
|
42b6d69793 | ||
|
|
2dc34a463b | ||
|
|
abb7900691 |
@@ -1,2 +1,5 @@
|
|||||||
[run]
|
[run]
|
||||||
omit=src/utemplate/*
|
omit=
|
||||||
|
src/microdot_websocket_alt.py
|
||||||
|
src/microdot_asgi_websocket.py
|
||||||
|
src/microdot_ssl.py
|
||||||
|
|||||||
2
.github/workflows/tests.yml
vendored
@@ -21,7 +21,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
python: ['3.6', '3.7', '3.8', '3.9', '3.10']
|
python: ['3.7', '3.8', '3.9', '3.10', '3.11']
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
55
CHANGES.md
@@ -1,5 +1,60 @@
|
|||||||
# Microdot change log
|
# Microdot change log
|
||||||
|
|
||||||
|
**Release 1.2.3** - 2023-03-03
|
||||||
|
|
||||||
|
- Corrected a problem with previous build.
|
||||||
|
|
||||||
|
**Release 1.2.2** - 2023-03-03
|
||||||
|
|
||||||
|
- Add a socket read timeout to abort incomplete requests [#99](https://github.com/miguelgrinberg/microdot/issues/99) ([commit](https://github.com/miguelgrinberg/microdot/commit/d0d358f94a63f8565d6406feff0c6e7418cc7f81))
|
||||||
|
- More robust timeout handling [#106](https://github.com/miguelgrinberg/microdot/issues/106) ([commit](https://github.com/miguelgrinberg/microdot/commit/4d432a7d6cd88b874a8b825fb62891ed22881f74))
|
||||||
|
- Add @after_error_handler decorator [#97](https://github.com/miguelgrinberg/microdot/issues/97) ([commit](https://github.com/miguelgrinberg/microdot/commit/fcaeee69052b5681706f65b022e667baeee30d4d))
|
||||||
|
- Return headers as lowercase byte sequences as required by ASGI ([commit](https://github.com/miguelgrinberg/microdot/commit/ddb3b8f442d3683df04554104edaf8acd9c68148))
|
||||||
|
- Async example of static file serving ([commit](https://github.com/miguelgrinberg/microdot/commit/680cd9c023352f0ff03d67f1041ea174b7b7385b))
|
||||||
|
- Fixing broken links to examples in documentation [#101](https://github.com/miguelgrinberg/microdot/issues/101) ([commit](https://github.com/miguelgrinberg/microdot/commit/c00b24c9436e1b8f3d4c9bb6f2adfca988902e91)) (thanks **Eric Welch**!)
|
||||||
|
- Add scrollbar to documentation's left sidebar ([commit](https://github.com/miguelgrinberg/microdot/commit/2aa90d42451dc64c84efcc4f40a1b6c8d1ef1e8d))
|
||||||
|
- Documentation typo [#90](https://github.com/miguelgrinberg/microdot/issues/90) ([commit](https://github.com/miguelgrinberg/microdot/commit/81394980234f24aac834faf8e2e8225231e9014b)) (thanks **William Wheeler**!)
|
||||||
|
- Add CPU timing to benchmark ([commit](https://github.com/miguelgrinberg/microdot/commit/9398c960752f87bc32d7c4349cbf594e5d678e99))
|
||||||
|
- Upgrade uasyncio release used in tests ([commit](https://github.com/miguelgrinberg/microdot/commit/3d6815119ca1ec989f704f626530f938c857a8e5))
|
||||||
|
- Update unittest library for MicroPython ([commit](https://github.com/miguelgrinberg/microdot/commit/ecd84ecb7bd3c29d5af96739442b908badeab804))
|
||||||
|
- New build of micropython for unit tests ([commit](https://github.com/miguelgrinberg/microdot/commit/818f98d9a4e531e01c0f913813425ab2b40c289d))
|
||||||
|
- Remove 3.6, add 3.11 to builds ([commit](https://github.com/miguelgrinberg/microdot/commit/dd15d90239b73b5fd413515c9cd4ac23f6d42f67))
|
||||||
|
|
||||||
|
**Release 1.2.1** - 2022-12-06
|
||||||
|
|
||||||
|
- Error handling invokes parent exceptions [#74](https://github.com/miguelgrinberg/microdot/issues/74) ([commit](https://github.com/miguelgrinberg/microdot/commit/24d74fb8483b04e8abe6e303e06f0a310f32700b)) (thanks **Diego Pomares**!)
|
||||||
|
- Addressed error when deleting a user session in async app [#86](https://github.com/miguelgrinberg/microdot/issues/86) ([commit](https://github.com/miguelgrinberg/microdot/commit/5a589afd5e519e94e84fc1ee69033f2dad51c3ea))
|
||||||
|
- Add asyncio file upload example ([commit](https://github.com/miguelgrinberg/microdot/commit/c841cbedda40f59a9d87f6895fdf9fd954f854a2))
|
||||||
|
- New Jinja and uTemplate examples with Bootstrap ([commit](https://github.com/miguelgrinberg/microdot/commit/211ad953aeedb4c7f73fe210424aa173b4dc7fee))
|
||||||
|
- Fix typos in documentation [#77](https://github.com/miguelgrinberg/microdot/issues/77) ([commit](https://github.com/miguelgrinberg/microdot/commit/4a9b92b800d3fd87110f7bc9f546c10185ee13bc)) (thanks **Diego Pomares**!)
|
||||||
|
- Add missing exception argument to error handler example in documentation [#73](https://github.com/miguelgrinberg/microdot/issues/73) ([commit](https://github.com/miguelgrinberg/microdot/commit/c443599089f2127d1cb052dfba8a05c1969d65e3)) (thanks **Diego Pomares**!)
|
||||||
|
|
||||||
|
**Release 1.2.0** - 2022-09-25
|
||||||
|
|
||||||
|
- Use a case insensitive dict for headers ([commit #1](https://github.com/miguelgrinberg/microdot/commit/b0fd6c432371ca5cb10d07ff84c4deed7aa0ce2e) [commit #2](https://github.com/miguelgrinberg/microdot/commit/a8515c97b030f942fa6ca85cbe1772291468fb0d))
|
||||||
|
- urlencode() helper function ([commit #1](https://github.com/miguelgrinberg/microdot/commit/672512e086384e808489305502e6ebebcc5a888f) [commit #2](https://github.com/miguelgrinberg/microdot/commit/b133dcc34368853ee685396a1bcb50360e807813))
|
||||||
|
- Added `request.url` attribute with the complete URL of the request ([commit](https://github.com/miguelgrinberg/microdot/commit/1547e861ee28d43d10fe4c4ed1871345d4b81086))
|
||||||
|
- Do not log HTTPException occurrences ([commit](https://github.com/miguelgrinberg/microdot/commit/cbefb6bf3a3fdcff8b7a8bacad3449be18e46e3b))
|
||||||
|
- Cache user session for performance ([commit](https://github.com/miguelgrinberg/microdot/commit/01947b101ebe198312c88d73872e3248024918f0))
|
||||||
|
- File upload example ([commit](https://github.com/miguelgrinberg/microdot/commit/8ebe81c09b604ddc1123e78ad6bc87ceda5f8597))
|
||||||
|
- Minor documentation styling fixes ([commit](https://github.com/miguelgrinberg/microdot/commit/4f263c63ab7bb1ce0dd48d8e00f3c6891e1bf07e))
|
||||||
|
|
||||||
|
**Release 1.1.1** - 2022-09-18
|
||||||
|
|
||||||
|
- Make WebSocket internals consistent between TLS and non-TLS [#61](https://github.com/miguelgrinberg/microdot/issues/61) ([commit](https://github.com/miguelgrinberg/microdot/commit/5693b812ceb2c0d51ec3c991adf6894a87e6fcc7))
|
||||||
|
|
||||||
|
**Release 1.1.0** - 2022-09-17
|
||||||
|
|
||||||
|
- Websocket support [#55](https://github.com/miguelgrinberg/microdot/issues/55) ([commit](https://github.com/miguelgrinberg/microdot/commit/2399c29c8a45289f009f47fd66438452da93cdab))
|
||||||
|
- SSL/TLS support ([commit #1](https://github.com/miguelgrinberg/microdot/commit/b61f51f2434465b7a0ee197aabf46e8f99f6e8ad) [commit #2](https://github.com/miguelgrinberg/microdot/commit/fe750feb0373b41cb022521a6a3edf1973847a74))
|
||||||
|
- Add `abort()` function ([commit](https://github.com/miguelgrinberg/microdot/commit/3c125c43d2e037ce64138e22c1ff4186ea107471))
|
||||||
|
- Charset handling in Content-Type headers [#60](https://github.com/miguelgrinberg/microdot/issues/60) ([commit](https://github.com/miguelgrinberg/microdot/commit/75725795b45d275deaee133204e400e8fbb3de70))
|
||||||
|
- Recover from errors writing the response ([commit](https://github.com/miguelgrinberg/microdot/commit/dc7a041ebd30f38b9f6b22c4bbcd61993c43944e))
|
||||||
|
- Reorganized examples into subdirectories ([commit](https://github.com/miguelgrinberg/microdot/commit/a01fc9c3f070e21e705b8f12ceb8288b0f304569))
|
||||||
|
- Update tests to use MicroPython 1.19 ([commit](https://github.com/miguelgrinberg/microdot/commit/42b6d6979381d9cd8ccc6ab6e079f12ec5987b80))
|
||||||
|
- Update MicroPython libraries used by tests ([commit](https://github.com/miguelgrinberg/microdot/commit/e767426228eeacd58886bccb5046049e994c0479))
|
||||||
|
- Fix links to hello and gpio examples in documentation [#53](https://github.com/miguelgrinberg/microdot/issues/53) ([commit](https://github.com/miguelgrinberg/microdot/commit/ec0f9ba855cca7dd35cddad40c4cb7eb17d8842a)) (thanks **Sterling G. Baird**!)
|
||||||
|
|
||||||
**Release 1.0.0** - 2022-08-07
|
**Release 1.0.0** - 2022-08-07
|
||||||
|
|
||||||
- User sessions with signed JWTs ([commit](https://github.com/miguelgrinberg/microdot/commit/355ffefcb2697b30d03359d35283835901f375d6))
|
- User sessions with signed JWTs ([commit](https://github.com/miguelgrinberg/microdot/commit/355ffefcb2697b30d03359d35283835901f375d6))
|
||||||
|
|||||||
BIN
bin/micropython
7
docs/_static/css/custom.css
vendored
@@ -1,3 +1,8 @@
|
|||||||
.py .class, .py .method, .py .property {
|
.py.class, .py.function, .py.method, .py.property {
|
||||||
margin-top: 20px;
|
margin-top: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
div.sphinxsidebar {
|
||||||
|
max-height: 100%;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|||||||
27
docs/api.rst
@@ -13,6 +13,9 @@ API Reference
|
|||||||
.. autoclass:: microdot.Response
|
.. autoclass:: microdot.Response
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
.. autoclass:: microdot.NoCaseDict
|
||||||
|
:members:
|
||||||
|
|
||||||
.. autoclass:: microdot.MultiDict
|
.. autoclass:: microdot.MultiDict
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
@@ -49,6 +52,30 @@ API Reference
|
|||||||
.. automodule:: microdot_session
|
.. automodule:: microdot_session
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
``microdot_websocket`` module
|
||||||
|
------------------------------
|
||||||
|
|
||||||
|
.. automodule:: microdot_websocket
|
||||||
|
:members:
|
||||||
|
|
||||||
|
``microdot_asyncio_websocket`` module
|
||||||
|
-------------------------------------
|
||||||
|
|
||||||
|
.. automodule:: microdot_asyncio_websocket
|
||||||
|
:members:
|
||||||
|
|
||||||
|
``microdot_asgi_websocket`` module
|
||||||
|
-------------------------------------
|
||||||
|
|
||||||
|
.. automodule:: microdot_asgi_websocket
|
||||||
|
:members:
|
||||||
|
|
||||||
|
``microdot_ssl`` module
|
||||||
|
-----------------------
|
||||||
|
|
||||||
|
.. automodule:: microdot_ssl
|
||||||
|
:members:
|
||||||
|
|
||||||
``microdot_test_client`` module
|
``microdot_test_client`` module
|
||||||
-------------------------------
|
-------------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ Asynchronous Support with Asyncio
|
|||||||
| MicroPython: `uasyncio <https://github.com/micropython/micropython/tree/master/extmod/uasyncio>`_
|
| MicroPython: `uasyncio <https://github.com/micropython/micropython/tree/master/extmod/uasyncio>`_
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello_async.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello_async.py>`_
|
- | `hello_async.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_async.py>`_
|
||||||
|
|
||||||
Microdot can be extended to use an asynchronous programming model based on the
|
Microdot can be extended to use an asynchronous programming model based on the
|
||||||
``asyncio`` package. When the :class:`Microdot <microdot_asyncio.Microdot>`
|
``asyncio`` package. When the :class:`Microdot <microdot_asyncio.Microdot>`
|
||||||
@@ -68,8 +68,8 @@ Using the uTemplate Engine
|
|||||||
- | `utemplate <https://github.com/pfalcon/utemplate/tree/master/utemplate>`_
|
- | `utemplate <https://github.com/pfalcon/utemplate/tree/master/utemplate>`_
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello_utemplate.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello_utemplate.py>`_
|
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/utemplate/hello.py>`_
|
||||||
| `hello_utemplate_async.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello_utemplate_async.py>`_
|
| `hello_utemplate_async.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_utemplate_async.py>`_
|
||||||
|
|
||||||
The :func:`render_template <microdot_utemplate.render_template>` function is
|
The :func:`render_template <microdot_utemplate.render_template>` function is
|
||||||
used to render HTML templates with the uTemplate engine. The first argument is
|
used to render HTML templates with the uTemplate engine. The first argument is
|
||||||
@@ -110,7 +110,7 @@ Using the Jinja Engine
|
|||||||
- | `Jinja2 <https://jinja.palletsprojects.com/>`_
|
- | `Jinja2 <https://jinja.palletsprojects.com/>`_
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello_jinja.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello_jinja.py>`_
|
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/templates/jinja/hello.py>`_
|
||||||
|
|
||||||
The :func:`render_template <microdot_jinja.render_template>` function is used
|
The :func:`render_template <microdot_jinja.render_template>` function is used
|
||||||
to render HTML templates with the Jinja engine. The first argument is the
|
to render HTML templates with the Jinja engine. The first argument is the
|
||||||
@@ -152,13 +152,11 @@ Maintaing Secure User Sessions
|
|||||||
|
|
||||||
* - Required external dependencies
|
* - Required external dependencies
|
||||||
- | CPython: `PyJWT <https://pyjwt.readthedocs.io/>`_
|
- | CPython: `PyJWT <https://pyjwt.readthedocs.io/>`_
|
||||||
| MicroPython: `jwt.py <https://github.com/miguelgrinberg/micropython-lib/blob/ujwt-module/python-ecosys/ujwt/ujwt.py>`_,
|
| MicroPython: `jwt.py <https://github.com/micropython/micropython-lib/blob/master/python-ecosys/pyjwt/jwt.py>`_,
|
||||||
`hmac <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/hmac/hmac.py>`_,
|
`hmac <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/hmac/hmac.py>`_
|
||||||
`hashlib <https://github.com/miguelgrinberg/micropython-lib/blob/ujwt-module/python-stdlib/hashlib>`_,
|
|
||||||
`warnings <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/warnings/warnings.py>`_
|
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `login.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/login.py>`_
|
- | `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
|
The session extension provides a secure way for the application to maintain
|
||||||
user sessions. The session is stored as a signed cookie in the client's
|
user sessions. The session is stored as a signed cookie in the client's
|
||||||
@@ -210,6 +208,125 @@ Example::
|
|||||||
delete_session(req)
|
delete_session(req)
|
||||||
return redirect('/')
|
return redirect('/')
|
||||||
|
|
||||||
|
WebSocket Support
|
||||||
|
~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. list-table::
|
||||||
|
:align: left
|
||||||
|
|
||||||
|
* - Compatibility
|
||||||
|
- | CPython & MicroPython
|
||||||
|
|
||||||
|
* - Required Microdot source files
|
||||||
|
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||||
|
| `microdot_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>`_
|
||||||
|
| `echo_wsgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_wsgi.py>`_
|
||||||
|
|
||||||
|
The WebSocket extension provides a way for the application to handle WebSocket
|
||||||
|
requests. The :func:`websocket <microdot_websocket.with_websocket>` decorator
|
||||||
|
is used to mark a route handler as a WebSocket handler. The handler receives
|
||||||
|
a WebSocket object as a second argument. The WebSocket object provides
|
||||||
|
``send()`` and ``receive()`` methods to send and receive messages respectively.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
message = ws.receive()
|
||||||
|
ws.send(message)
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
An unsupported *microdot_websocket_alt.py* module, with the same
|
||||||
|
interface, is also provided. This module uses the native WebSocket support
|
||||||
|
in MicroPython that powers the WebREPL, and may provide slightly better
|
||||||
|
performance for MicroPython low-end boards. This module is not compatible
|
||||||
|
with CPython.
|
||||||
|
|
||||||
|
Asynchronous WebSocket
|
||||||
|
~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. list-table::
|
||||||
|
:align: left
|
||||||
|
|
||||||
|
* - Compatibility
|
||||||
|
- | CPython & MicroPython
|
||||||
|
|
||||||
|
* - Required Microdot source files
|
||||||
|
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||||
|
| `microdot_asyncio.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot_asyncio.py>`_
|
||||||
|
| `microdot_websocket.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot_websocket.py>`_
|
||||||
|
| `microdot_asyncio_websocket.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot_asyncio_websocket.py>`_
|
||||||
|
|
||||||
|
* - Required external dependencies
|
||||||
|
- | CPython: None
|
||||||
|
| MicroPython: `uasyncio <https://github.com/micropython/micropython/tree/master/extmod/uasyncio>`_
|
||||||
|
|
||||||
|
* - Examples
|
||||||
|
- | `echo_async.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_async.py>`_
|
||||||
|
|
||||||
|
This extension has the same interface as the synchronous WebSocket extension,
|
||||||
|
but the ``receive()`` and ``send()`` methods are asynchronous.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
An unsupported *microdot_asgi_websocket.py* module, with the same
|
||||||
|
interface, is also provided. This module must be used instead of
|
||||||
|
*microdot_asyncio_websocket.py* when the ASGI support is used. The
|
||||||
|
`echo_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/websocket/echo_asgi.py>`_
|
||||||
|
example shows how to use this module.
|
||||||
|
|
||||||
|
HTTPS Support
|
||||||
|
~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. list-table::
|
||||||
|
:align: left
|
||||||
|
|
||||||
|
* - Compatibility
|
||||||
|
- | CPython & MicroPython
|
||||||
|
|
||||||
|
* - Required Microdot source files
|
||||||
|
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||||
|
| `microdot_ssl.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot_ssl.py>`_
|
||||||
|
|
||||||
|
* - Examples
|
||||||
|
- | `hello_tls.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/tls/hello_tls.py>`_
|
||||||
|
| `hello_async_tls.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/tls/hello_async_tls.py>`_
|
||||||
|
|
||||||
|
The ``run()`` function accepts an optional ``ssl`` argument, through which an
|
||||||
|
initialized ``SSLContext`` object can be passed. MicroPython does not currently
|
||||||
|
have a ``SSLContext`` implementation, so the ``microdot_ssl`` module provides
|
||||||
|
a basic implementation that can be used to create a context.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
from microdot import Microdot
|
||||||
|
from microdot_ssl import create_ssl_context
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
return 'Hello, World!'
|
||||||
|
|
||||||
|
sslctx = create_ssl_context('cert.der', 'key.der')
|
||||||
|
app.run(port=4443, debug=True, ssl=sslctx)
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
The ``microdot_ssl`` module is only needed for MicroPython. When used under
|
||||||
|
CPython, this module creates a standard ``SSLContext`` instance.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
The ``uasyncio`` library for MicroPython does not currently support TLS, so
|
||||||
|
this feature is not available for asynchronous applications on that
|
||||||
|
platform. The ``asyncio`` library for CPython is fully supported.
|
||||||
|
|
||||||
Test Client
|
Test Client
|
||||||
~~~~~~~~~~~
|
~~~~~~~~~~~
|
||||||
|
|
||||||
@@ -306,7 +423,7 @@ Using a WSGI Web Server
|
|||||||
- | A WSGI web server, such as `Gunicorn <https://gunicorn.org/>`_.
|
- | A WSGI web server, such as `Gunicorn <https://gunicorn.org/>`_.
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello_wsgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello_wsgi.py>`_
|
- | `hello_wsgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_wsgi.py>`_
|
||||||
|
|
||||||
|
|
||||||
The ``microdot_wsgi`` module provides an extended ``Microdot`` class that
|
The ``microdot_wsgi`` module provides an extended ``Microdot`` class that
|
||||||
@@ -351,7 +468,7 @@ Using an ASGI Web Server
|
|||||||
- | An ASGI web server, such as `Uvicorn <https://uvicorn.org/>`_.
|
- | An ASGI web server, such as `Uvicorn <https://uvicorn.org/>`_.
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello_asgi.py>`_
|
- | `hello_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_asgi.py>`_
|
||||||
|
|
||||||
The ``microdot_asgi`` module provides an extended ``Microdot`` class that
|
The ``microdot_asgi`` module provides an extended ``Microdot`` class that
|
||||||
implements the ASGI protocol and can be used with a compliant ASGI server such
|
implements the ASGI protocol and can be used with a compliant ASGI server such
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ Running with CPython
|
|||||||
- | None
|
- | None
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello.py>`_
|
- | `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
|
When using CPython, you can start the web server by running the script that
|
||||||
defines and runs the application instance::
|
defines and runs the application instance::
|
||||||
@@ -93,8 +93,8 @@ Running with MicroPython
|
|||||||
- | None
|
- | None
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello.py>`_
|
- | `hello.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello.py>`_
|
||||||
| `gpio.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/gpio.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
|
When using MicroPython, you can upload a *main.py* file containing the web
|
||||||
server code to your device along with *microdot.py*. MicroPython will
|
server code to your device along with *microdot.py*. MicroPython will
|
||||||
@@ -283,7 +283,7 @@ handled::
|
|||||||
def start_timer(request):
|
def start_timer(request):
|
||||||
request.g.start_time = time.time()
|
request.g.start_time = time.time()
|
||||||
|
|
||||||
@ap.after_request
|
@app.after_request
|
||||||
def end_timer(request, response):
|
def end_timer(request, response):
|
||||||
duration = time.time() - request.g.start_time
|
duration = time.time() - request.g.start_time
|
||||||
print(f'Request took {duration:0.2f} seconds')
|
print(f'Request took {duration:0.2f} seconds')
|
||||||
@@ -293,6 +293,12 @@ The function can return a modified response object to replace the original. If
|
|||||||
the function does not return a value, then the original response object is
|
the function does not return a value, then the original response object is
|
||||||
used.
|
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.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
The :ref:`request.g <The "g" Object>` object is a special object that allows
|
The :ref:`request.g <The "g" Object>` object is a special object that allows
|
||||||
the before and after request handlers, as well sa the route function to
|
the before and after request handlers, as well sa the route function to
|
||||||
@@ -314,7 +320,7 @@ automatically handled by Microdot are:
|
|||||||
While the above errors are fully complaint with the HTTP specification, the
|
While the above errors are fully complaint with the HTTP specification, the
|
||||||
application might want to provide custom responses for them. The
|
application might want to provide custom responses for them. The
|
||||||
:func:`errorhandler() <microdot.Microdot.errorhandler>` decorator registers
|
:func:`errorhandler() <microdot.Microdot.errorhandler>` decorator registers
|
||||||
a functions to respond to specific error codes. The following example shows a
|
functions to respond to specific error codes. The following example shows a
|
||||||
custom error handler for 404 errors::
|
custom error handler for 404 errors::
|
||||||
|
|
||||||
@app.errorhandler(404)
|
@app.errorhandler(404)
|
||||||
@@ -322,14 +328,18 @@ custom error handler for 404 errors::
|
|||||||
return {'error': 'resource not found'}, 404
|
return {'error': 'resource not found'}, 404
|
||||||
|
|
||||||
The ``errorhandler()`` decorator has a second form, in which it takes an
|
The ``errorhandler()`` decorator has a second form, in which it takes an
|
||||||
exception class as an argument. Microdot will then invoke the handler when an
|
exception class as an argument. Microdot will then invoke the handler when the
|
||||||
exception of that class is raised. The next example provides a custom response
|
exception is an instance of the given class is raised. The next example
|
||||||
for division by zero errors::
|
provides a custom response for division by zero errors::
|
||||||
|
|
||||||
@app.errorhandler(ZeroDivisionError)
|
@app.errorhandler(ZeroDivisionError)
|
||||||
def division_by_zero(request):
|
def division_by_zero(request, exception):
|
||||||
return {'error': 'division by zero'}, 500
|
return {'error': 'division by zero'}, 500
|
||||||
|
|
||||||
|
When the raised exception class does not have an error handler defined, but
|
||||||
|
one or more of its base classes do, Microdot makes an attempt to invoke the
|
||||||
|
most specific handler.
|
||||||
|
|
||||||
Mounting a Sub-Application
|
Mounting a Sub-Application
|
||||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
@@ -481,7 +491,7 @@ Accessing the Raw Request Body
|
|||||||
|
|
||||||
For cases in which neither JSON nor form data is expected, the
|
For cases in which neither JSON nor form data is expected, the
|
||||||
:attr:`body <microdot.Request.body>` request attribute returns the entire body
|
:attr:`body <microdot.Request.body>` request attribute returns the entire body
|
||||||
of the request as a byte sequence.
|
of the request as a byte sequence.
|
||||||
|
|
||||||
If the expected body is too large to fit in memory, the application can use the
|
If the expected body is too large to fit in memory, the application can use the
|
||||||
:attr:`stream <microdot.Request.stream>` request attribute to read the body
|
:attr:`stream <microdot.Request.stream>` request attribute to read the body
|
||||||
@@ -645,9 +655,9 @@ File Responses
|
|||||||
|
|
||||||
The :func:`send_file <microdot.Response.send_file>` function builds a response
|
The :func:`send_file <microdot.Response.send_file>` function builds a response
|
||||||
object for a file::
|
object for a file::
|
||||||
|
|
||||||
from microdot import send_file
|
from microdot import send_file
|
||||||
|
|
||||||
@app.get('/')
|
@app.get('/')
|
||||||
def index(request):
|
def index(request):
|
||||||
return send_file('/static/index.html')
|
return send_file('/static/index.html')
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
aiofiles==0.8.0
|
aiofiles==0.8.0
|
||||||
anyio==3.6.1
|
anyio==3.6.1
|
||||||
blinker==1.5
|
blinker==1.5
|
||||||
certifi==2022.6.15
|
certifi==2022.12.7
|
||||||
charset-normalizer==2.1.0
|
charset-normalizer==2.1.0
|
||||||
click==8.1.3
|
click==8.1.3
|
||||||
fastapi==0.79.0
|
fastapi==0.79.0
|
||||||
@@ -24,10 +24,10 @@ pydantic==1.9.1
|
|||||||
quart==0.18.0
|
quart==0.18.0
|
||||||
requests==2.28.1
|
requests==2.28.1
|
||||||
sniffio==1.2.0
|
sniffio==1.2.0
|
||||||
starlette==0.19.1
|
starlette==0.25.0
|
||||||
toml==0.10.2
|
toml==0.10.2
|
||||||
typing_extensions==4.3.0
|
typing_extensions==4.3.0
|
||||||
urllib3==1.26.11
|
urllib3==1.26.11
|
||||||
uvicorn==0.18.2
|
uvicorn==0.18.2
|
||||||
Werkzeug==2.2.1
|
Werkzeug==2.2.3
|
||||||
wsproto==1.1.0
|
wsproto==1.1.0
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
❯ curl -X GET http://localhost:5000/ <-- microdot
|
|
||||||
{"ram": 8429568}%
|
|
||||||
❯ curl -X GET http://localhost:5000/ <-- microdot_asyncio
|
|
||||||
{"ram": 12410880}%
|
|
||||||
❯ curl -X GET http://localhost:8000/ <-- microdot_wsgi
|
|
||||||
{"ram": 9101312}%
|
|
||||||
❯ curl -X GET http://localhost:8000/ <-- microdot_asgi
|
|
||||||
{"ram": 18620416}%
|
|
||||||
❯ curl -X GET http://localhost:5000/ <-- flask app.run
|
|
||||||
{"ram":25460736}
|
|
||||||
❯ curl -X GET http://localhost:5000/ <-- flask run
|
|
||||||
{"ram":26210304}
|
|
||||||
❯ curl -X GET http://localhost:5000/ <-- quart run
|
|
||||||
{"ram":31748096}%
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
|
from timeit import timeit
|
||||||
import requests
|
import requests
|
||||||
import psutil
|
import psutil
|
||||||
import humanize
|
import humanize
|
||||||
@@ -76,19 +77,23 @@ apps = [
|
|||||||
for app, env, name in apps:
|
for app, env, name in apps:
|
||||||
p = subprocess.Popen(
|
p = subprocess.Popen(
|
||||||
app.split() if isinstance(app, str) else app,
|
app.split() if isinstance(app, str) else app,
|
||||||
env={'PATH': os.environ['PATH'], **env},
|
env={'PATH': os.environ['PATH'] + ':../../bin', **env},
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=subprocess.DEVNULL,
|
||||||
stderr=subprocess.DEVNULL
|
stderr=subprocess.DEVNULL
|
||||||
)
|
)
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
tm = 0
|
||||||
if not name.startswith('baseline'):
|
if not name.startswith('baseline'):
|
||||||
r = requests.get('http://localhost:5000')
|
def req():
|
||||||
r.raise_for_status()
|
r = requests.get('http://localhost:5000')
|
||||||
|
r.raise_for_status()
|
||||||
|
|
||||||
|
tm = timeit(req, number=1000)
|
||||||
proc = psutil.Process(p.pid)
|
proc = psutil.Process(p.pid)
|
||||||
mem = proc.memory_info().rss
|
mem = proc.memory_info().rss
|
||||||
for child in proc.children(recursive=True):
|
for child in proc.children(recursive=True):
|
||||||
mem += child.memory_info().rss
|
mem += child.memory_info().rss
|
||||||
bar = '*' * (mem // (1024 * 1024))
|
bar = '*' * (mem // (1024 * 1024))
|
||||||
print(f'{name:<28}{humanize.naturalsize(mem):>10} {bar}')
|
print(f'{name:<28}{tm:10.2f}s {humanize.naturalsize(mem):>10} {bar}')
|
||||||
p.terminate()
|
p.terminate()
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|||||||
2
examples/hello/README.md
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
This directory contains several "Hello, World!" type examples for different
|
||||||
|
platforms and configurations supported by Microdot.
|
||||||
1
examples/sessions/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This directory contains examples that take advantage of user sessions.
|
||||||
2
examples/static/README.md
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
The example in this directory demonstrates how to serve static files out of a
|
||||||
|
directory.
|
||||||
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
19
examples/static/static_async.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from microdot_asyncio import Microdot
|
||||||
|
from microdot import send_file
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
async def index(request):
|
||||||
|
return send_file('static/index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@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)
|
||||||
|
|
||||||
|
|
||||||
|
app.run(debug=True)
|
||||||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.4 KiB |
1
examples/streaming/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This directory contain examples that demonstrate how to use streaming responses.
|
||||||
19
examples/templates/jinja/bootstrap.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from microdot import Microdot, Response
|
||||||
|
from microdot_jinja import render_template
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
Response.default_content_type = 'text/html'
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
return render_template('page1.html', page='Page 1')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/page2')
|
||||||
|
def page2(req):
|
||||||
|
return render_template('page2.html', page='Page 2')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run()
|
||||||
@@ -10,7 +10,7 @@ def index(req):
|
|||||||
name = None
|
name = None
|
||||||
if req.method == 'POST':
|
if req.method == 'POST':
|
||||||
name = req.form.get('name')
|
name = req.form.get('name')
|
||||||
return render_template('index_jinja.html', name=name)
|
return render_template('index.html', name=name)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
48
examples/templates/jinja/templates/base.html
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<!--
|
||||||
|
This is based on the Bootstrap 5 starter template from the documentation:
|
||||||
|
https://getbootstrap.com/docs/5.0/getting-started/introduction/#starter-template
|
||||||
|
-->
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<!-- Required meta tags -->
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
|
||||||
|
<!-- Bootstrap CSS -->
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
|
||||||
|
|
||||||
|
<title>Microdot + Jinja + Bootstrap</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav class="navbar navbar-expand-lg navbar-light bg-light">
|
||||||
|
<div class="container">
|
||||||
|
<a class="navbar-brand" href="/">Microdot + Jinja + Bootstrap</a>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<br>
|
||||||
|
<div class="container">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
|
||||||
|
<symbol id="info-fill" fill="currentColor" viewBox="0 0 16 16">
|
||||||
|
<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
<div class="alert alert-primary d-flex align-items-center" role="alert">
|
||||||
|
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Info:"><use xlink:href="#info-fill"/></svg>
|
||||||
|
<div>This example demonstrates how to create an application that uses <a href="https://getbootstrap.com" class="alert-link">Bootstrap</a> styling. The page layout is defined in a base template that is inherited by several pages.</div>
|
||||||
|
</div>
|
||||||
|
{% block content %}{% endblock %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Optional JavaScript; choose one of the two! -->
|
||||||
|
|
||||||
|
<!-- Option 1: Bootstrap Bundle with Popper -->
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
|
||||||
|
|
||||||
|
<!-- Option 2: Separate Popper and Bootstrap JS -->
|
||||||
|
<!--
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
|
||||||
|
-->
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
6
examples/templates/jinja/templates/page1.html
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h2>This is {{ page }}</h2>
|
||||||
|
<p>Go to <a href="/page2">Page 2</a>.</p>
|
||||||
|
{% endblock %}
|
||||||
6
examples/templates/jinja/templates/page2.html
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h2>This is {{ page }}</h2>
|
||||||
|
<p>Go back <a href="/">Page 1</a>.</p>
|
||||||
|
{% endblock %}
|
||||||
19
examples/templates/utemplate/bootstrap.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from microdot import Microdot, Response
|
||||||
|
from microdot_utemplate import render_template
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
Response.default_content_type = 'text/html'
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
return render_template('page1.html', page='Page 1')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/page2')
|
||||||
|
def page2(req):
|
||||||
|
return render_template('page2.html', page='Page 2')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
||||||
@@ -10,7 +10,7 @@ def index(req):
|
|||||||
name = None
|
name = None
|
||||||
if req.method == 'POST':
|
if req.method == 'POST':
|
||||||
name = req.form.get('name')
|
name = req.form.get('name')
|
||||||
return render_template('index_utemplate.html', name=name)
|
return render_template('index.html', name=name)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
14
examples/templates/utemplate/templates/base_footer.html
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Optional JavaScript; choose one of the two! -->
|
||||||
|
|
||||||
|
<!-- Option 1: Bootstrap Bundle with Popper -->
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
|
||||||
|
|
||||||
|
<!-- Option 2: Separate Popper and Bootstrap JS -->
|
||||||
|
<!--
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
|
||||||
|
-->
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
33
examples/templates/utemplate/templates/base_header.html
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<!--
|
||||||
|
This is based on the Bootstrap 5 starter template from the documentation:
|
||||||
|
https://getbootstrap.com/docs/5.0/getting-started/introduction/#starter-template
|
||||||
|
-->
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<!-- Required meta tags -->
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
|
||||||
|
<!-- Bootstrap CSS -->
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
|
||||||
|
|
||||||
|
<title>Microdot + uTemplate + Bootstrap</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav class="navbar navbar-expand-lg navbar-light bg-light">
|
||||||
|
<div class="container">
|
||||||
|
<a class="navbar-brand" href="/">Microdot + uTemplate + Bootstrap</a>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<br>
|
||||||
|
<div class="container">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
|
||||||
|
<symbol id="info-fill" fill="currentColor" viewBox="0 0 16 16">
|
||||||
|
<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
<div class="alert alert-primary d-flex align-items-center" role="alert">
|
||||||
|
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Info:"><use xlink:href="#info-fill"/></svg>
|
||||||
|
<div>This example demonstrates how to create an application that uses <a href="https://getbootstrap.com" class="alert-link">Bootstrap</a> styling. The page layout is defined in a base template that is inherited by several pages.</div>
|
||||||
|
</div>
|
||||||
7
examples/templates/utemplate/templates/page1.html
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{% args page %}
|
||||||
|
{% include 'base_header.html' %}
|
||||||
|
|
||||||
|
<h2>This is {{ page }}</h2>
|
||||||
|
<p>Go to <a href="/page2">Page 2</a>.</p>
|
||||||
|
|
||||||
|
{% include 'base_footer.html' %}
|
||||||
7
examples/templates/utemplate/templates/page2.html
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{% args page %}
|
||||||
|
{% include 'base_header.html' %}
|
||||||
|
|
||||||
|
<h2>This is {{ page }}</h2>
|
||||||
|
<p>Go back <a href="/">Page 1</a>.</p>
|
||||||
|
|
||||||
|
{% include 'base_footer.html' %}
|
||||||
20
examples/tls/README.md
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
This directory contains examples that demonstrate how to start TLS servers.
|
||||||
|
|
||||||
|
To run these examples, SSL certificate and private key files need to be
|
||||||
|
created. When running under CPython, the files should be in PEM format, named
|
||||||
|
`cert.pem` and `key.pem`. When running under MicroPython, they should be in DER
|
||||||
|
format, and named `cert.der` and `key.der`.
|
||||||
|
|
||||||
|
To quickly create a self-signed SSL certificate, use the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
|
||||||
|
```
|
||||||
|
|
||||||
|
To convert the resulting PEM files to DER format for MicroPython, use these
|
||||||
|
commands:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openssl x509 -in cert.pem -out cert.der -outform DER
|
||||||
|
openssl rsa -in key.pem -out key.der -outform DER
|
||||||
|
```
|
||||||
23
examples/tls/echo_async_tls.py
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import ssl
|
||||||
|
from microdot_asyncio import Microdot, send_file
|
||||||
|
from microdot_asyncio_websocket import with_websocket
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
data = await ws.receive()
|
||||||
|
await ws.send(data)
|
||||||
|
|
||||||
|
|
||||||
|
sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
sslctx.load_cert_chain('cert.pem', 'key.pem')
|
||||||
|
app.run(port=4443, debug=True, ssl=sslctx)
|
||||||
24
examples/tls/echo_tls.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import sys
|
||||||
|
from microdot import Microdot, send_file
|
||||||
|
from microdot_websocket import with_websocket
|
||||||
|
from microdot_ssl import create_ssl_context
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
data = ws.receive()
|
||||||
|
ws.send(data)
|
||||||
|
|
||||||
|
|
||||||
|
ext = 'der' if sys.implementation.name == 'micropython' else 'pem'
|
||||||
|
sslctx = create_ssl_context('cert.' + ext, 'key.' + ext)
|
||||||
|
app.run(port=4443, debug=True, ssl=sslctx)
|
||||||
35
examples/tls/hello_async_tls.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import ssl
|
||||||
|
from microdot_asyncio import Microdot
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
htmldoc = '''<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Microdot Example Page</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<h1>Microdot Example Page</h1>
|
||||||
|
<p>Hello from Microdot!</p>
|
||||||
|
<p><a href="/shutdown">Click to shutdown the server</a></p>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
async def hello(request):
|
||||||
|
return htmldoc, 200, {'Content-Type': 'text/html'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/shutdown')
|
||||||
|
async def shutdown(request):
|
||||||
|
request.app.shutdown()
|
||||||
|
return 'The server is shutting down...'
|
||||||
|
|
||||||
|
|
||||||
|
sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
sslctx.load_cert_chain('cert.pem', 'key.pem')
|
||||||
|
app.run(port=4443, debug=True, ssl=sslctx)
|
||||||
36
examples/tls/hello_tls.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import sys
|
||||||
|
from microdot import Microdot
|
||||||
|
from microdot_ssl import create_ssl_context
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
htmldoc = '''<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Microdot Example Page</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<h1>Microdot Example Page</h1>
|
||||||
|
<p>Hello from Microdot!</p>
|
||||||
|
<p><a href="/shutdown">Click to shutdown the server</a></p>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def hello(request):
|
||||||
|
return htmldoc, 200, {'Content-Type': 'text/html'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/shutdown')
|
||||||
|
def shutdown(request):
|
||||||
|
request.app.shutdown()
|
||||||
|
return 'The server is shutting down...'
|
||||||
|
|
||||||
|
|
||||||
|
ext = 'der' if sys.implementation.name == 'micropython' else 'pem'
|
||||||
|
sslctx = create_ssl_context('cert.' + ext, 'key.' + ext)
|
||||||
|
app.run(port=4443, debug=True, ssl=sslctx)
|
||||||
35
examples/tls/index.html
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Microdot TLS WebSocket Demo</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Microdot TLS WebSocket Demo</h1>
|
||||||
|
<div id="log"></div>
|
||||||
|
<br>
|
||||||
|
<form id="form">
|
||||||
|
<label for="text">Input: </label>
|
||||||
|
<input type="text" id="text" autofocus>
|
||||||
|
</form>
|
||||||
|
<script>
|
||||||
|
const log = (text, color) => {
|
||||||
|
document.getElementById('log').innerHTML += `<span style="color: ${color}">${text}</span><br>`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const socket = new WebSocket('wss://' + location.host + '/echo');
|
||||||
|
socket.addEventListener('message', ev => {
|
||||||
|
log('<<< ' + ev.data, 'blue');
|
||||||
|
});
|
||||||
|
socket.addEventListener('close', ev => {
|
||||||
|
log('<<< closed');
|
||||||
|
});
|
||||||
|
document.getElementById('form').onsubmit = ev => {
|
||||||
|
ev.preventDefault();
|
||||||
|
const textField = document.getElementById('text');
|
||||||
|
log('>>> ' + textField.value, 'red');
|
||||||
|
socket.send(textField.value);
|
||||||
|
textField.value = '';
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
1
examples/uploads/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This directory contains file upload examples.
|
||||||
1
examples/uploads/files/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Uploaded files are saved to this directory.
|
||||||
34
examples/uploads/index.html
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Microdot Upload Example</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Microdot Upload Example</h1>
|
||||||
|
<form id="form">
|
||||||
|
<input type="file" id="file" name="file" />
|
||||||
|
<input type="submit" value="Upload" />
|
||||||
|
</form>
|
||||||
|
<script>
|
||||||
|
async function upload(ev) {
|
||||||
|
ev.preventDefault();
|
||||||
|
const file = document.getElementById('file').files[0];
|
||||||
|
if (!file) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await fetch('/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
body: file,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/octet-stream',
|
||||||
|
'Content-Disposition': `attachment; filename="${file.name}"`,
|
||||||
|
},
|
||||||
|
}).then(res => {
|
||||||
|
console.log('Upload accepted');
|
||||||
|
window.location.href = '/';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
document.getElementById('form').addEventListener('submit', upload);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
34
examples/uploads/uploads.py
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
from microdot import Microdot, send_file, Request
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
Request.max_content_length = 1024 * 1024 # 1MB (change as needed)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/upload')
|
||||||
|
def upload(request):
|
||||||
|
# obtain the filename and size from request headers
|
||||||
|
filename = request.headers['Content-Disposition'].split(
|
||||||
|
'filename=')[1].strip('"')
|
||||||
|
size = int(request.headers['Content-Length'])
|
||||||
|
|
||||||
|
# sanitize the filename
|
||||||
|
filename = filename.replace('/', '_')
|
||||||
|
|
||||||
|
# write the file to the files directory in 1K chunks
|
||||||
|
with open('files/' + filename, 'wb') as f:
|
||||||
|
while size > 0:
|
||||||
|
chunk = request.stream.read(min(size, 1024))
|
||||||
|
f.write(chunk)
|
||||||
|
size -= len(chunk)
|
||||||
|
|
||||||
|
print('Successfully saved file: ' + filename)
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
||||||
34
examples/uploads/uploads_async.py
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
from microdot_asyncio import Microdot, send_file, Request
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
Request.max_content_length = 1024 * 1024 # 1MB (change as needed)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/')
|
||||||
|
async def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/upload')
|
||||||
|
async def upload(request):
|
||||||
|
# obtain the filename and size from request headers
|
||||||
|
filename = request.headers['Content-Disposition'].split(
|
||||||
|
'filename=')[1].strip('"')
|
||||||
|
size = int(request.headers['Content-Length'])
|
||||||
|
|
||||||
|
# sanitize the filename
|
||||||
|
filename = filename.replace('/', '_')
|
||||||
|
|
||||||
|
# write the file to the files directory in 1K chunks
|
||||||
|
with open('files/' + filename, 'wb') as f:
|
||||||
|
while size > 0:
|
||||||
|
chunk = await request.stream.read(min(size, 1024))
|
||||||
|
f.write(chunk)
|
||||||
|
size -= len(chunk)
|
||||||
|
|
||||||
|
print('Successfully saved file: ' + filename)
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
||||||
1
examples/websocket/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This directory contains WebSocket examples.
|
||||||
20
examples/websocket/echo.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from microdot import Microdot, send_file
|
||||||
|
from microdot_websocket import with_websocket
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
data = ws.receive()
|
||||||
|
ws.send(data)
|
||||||
|
|
||||||
|
|
||||||
|
app.run()
|
||||||
17
examples/websocket/echo_asgi.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
from microdot_asgi import Microdot, send_file
|
||||||
|
from microdot_asgi_websocket import with_websocket
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
data = await ws.receive()
|
||||||
|
await ws.send(data)
|
||||||
20
examples/websocket/echo_async.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from microdot_asyncio import Microdot, send_file
|
||||||
|
from microdot_asyncio_websocket import with_websocket
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
data = await ws.receive()
|
||||||
|
await ws.send(data)
|
||||||
|
|
||||||
|
|
||||||
|
app.run()
|
||||||
17
examples/websocket/echo_wsgi.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
from microdot_wsgi import Microdot, send_file
|
||||||
|
from microdot_websocket import with_websocket
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(request):
|
||||||
|
return send_file('index.html')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
data = ws.receive()
|
||||||
|
ws.send(data)
|
||||||
35
examples/websocket/index.html
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Microdot WebSocket Demo</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Microdot WebSocket Demo</h1>
|
||||||
|
<div id="log"></div>
|
||||||
|
<br>
|
||||||
|
<form id="form">
|
||||||
|
<label for="text">Input: </label>
|
||||||
|
<input type="text" id="text" autofocus>
|
||||||
|
</form>
|
||||||
|
<script>
|
||||||
|
const log = (text, color) => {
|
||||||
|
document.getElementById('log').innerHTML += `<span style="color: ${color}">${text}</span><br>`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const socket = new WebSocket('ws://' + location.host + '/echo');
|
||||||
|
socket.addEventListener('message', ev => {
|
||||||
|
log('<<< ' + ev.data, 'blue');
|
||||||
|
});
|
||||||
|
socket.addEventListener('close', ev => {
|
||||||
|
log('<<< closed');
|
||||||
|
});
|
||||||
|
document.getElementById('form').onsubmit = ev => {
|
||||||
|
ev.preventDefault();
|
||||||
|
const textField = document.getElementById('text');
|
||||||
|
log('>>> ' + textField.value, 'red');
|
||||||
|
socket.send(textField.value);
|
||||||
|
textField.value = '';
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
try:
|
|
||||||
import uhashlib
|
|
||||||
except ImportError:
|
|
||||||
uhashlib = None
|
|
||||||
|
|
||||||
|
|
||||||
def init():
|
|
||||||
for i in ("sha1", "sha224", "sha256", "sha384", "sha512"):
|
|
||||||
try:
|
|
||||||
c = __import__("_" + i, None, None, (), 1)
|
|
||||||
except ImportError:
|
|
||||||
c = uhashlib
|
|
||||||
c = getattr(c, i, None)
|
|
||||||
globals()[i] = c
|
|
||||||
|
|
||||||
|
|
||||||
init()
|
|
||||||
|
|
||||||
|
|
||||||
def new(algo, data=b""):
|
|
||||||
try:
|
|
||||||
c = globals()[algo]
|
|
||||||
return c(data)
|
|
||||||
except KeyError:
|
|
||||||
raise ValueError(algo)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
from ._sha256 import sha224
|
|
||||||
@@ -1,301 +0,0 @@
|
|||||||
SHA_BLOCKSIZE = 64
|
|
||||||
SHA_DIGESTSIZE = 32
|
|
||||||
|
|
||||||
|
|
||||||
def new_shaobject():
|
|
||||||
return {
|
|
||||||
"digest": [0] * 8,
|
|
||||||
"count_lo": 0,
|
|
||||||
"count_hi": 0,
|
|
||||||
"data": [0] * SHA_BLOCKSIZE,
|
|
||||||
"local": 0,
|
|
||||||
"digestsize": 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
ROR = lambda x, y: (((x & 0xFFFFFFFF) >> (y & 31)) | (x << (32 - (y & 31)))) & 0xFFFFFFFF
|
|
||||||
Ch = lambda x, y, z: (z ^ (x & (y ^ z)))
|
|
||||||
Maj = lambda x, y, z: (((x | y) & z) | (x & y))
|
|
||||||
S = lambda x, n: ROR(x, n)
|
|
||||||
R = lambda x, n: (x & 0xFFFFFFFF) >> n
|
|
||||||
Sigma0 = lambda x: (S(x, 2) ^ S(x, 13) ^ S(x, 22))
|
|
||||||
Sigma1 = lambda x: (S(x, 6) ^ S(x, 11) ^ S(x, 25))
|
|
||||||
Gamma0 = lambda x: (S(x, 7) ^ S(x, 18) ^ R(x, 3))
|
|
||||||
Gamma1 = lambda x: (S(x, 17) ^ S(x, 19) ^ R(x, 10))
|
|
||||||
|
|
||||||
|
|
||||||
def sha_transform(sha_info):
|
|
||||||
W = []
|
|
||||||
|
|
||||||
d = sha_info["data"]
|
|
||||||
for i in range(0, 16):
|
|
||||||
W.append((d[4 * i] << 24) + (d[4 * i + 1] << 16) + (d[4 * i + 2] << 8) + d[4 * i + 3])
|
|
||||||
|
|
||||||
for i in range(16, 64):
|
|
||||||
W.append((Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xFFFFFFFF)
|
|
||||||
|
|
||||||
ss = sha_info["digest"][:]
|
|
||||||
|
|
||||||
def RND(a, b, c, d, e, f, g, h, i, ki):
|
|
||||||
t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]
|
|
||||||
t1 = Sigma0(a) + Maj(a, b, c)
|
|
||||||
d += t0
|
|
||||||
h = t0 + t1
|
|
||||||
return d & 0xFFFFFFFF, h & 0xFFFFFFFF
|
|
||||||
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 0, 0x428A2F98)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 1, 0x71374491)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 2, 0xB5C0FBCF)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 3, 0xE9B5DBA5)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 4, 0x3956C25B)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 5, 0x59F111F1)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 6, 0x923F82A4)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 7, 0xAB1C5ED5)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 8, 0xD807AA98)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 9, 0x12835B01)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 10, 0x243185BE)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 11, 0x550C7DC3)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 12, 0x72BE5D74)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 13, 0x80DEB1FE)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 14, 0x9BDC06A7)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 15, 0xC19BF174)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 16, 0xE49B69C1)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 17, 0xEFBE4786)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 18, 0x0FC19DC6)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 19, 0x240CA1CC)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 20, 0x2DE92C6F)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 21, 0x4A7484AA)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 22, 0x5CB0A9DC)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 23, 0x76F988DA)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 24, 0x983E5152)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 25, 0xA831C66D)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 26, 0xB00327C8)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 27, 0xBF597FC7)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 28, 0xC6E00BF3)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 29, 0xD5A79147)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 30, 0x06CA6351)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 31, 0x14292967)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 32, 0x27B70A85)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 33, 0x2E1B2138)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 34, 0x4D2C6DFC)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 35, 0x53380D13)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 36, 0x650A7354)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 37, 0x766A0ABB)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 38, 0x81C2C92E)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 39, 0x92722C85)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 40, 0xA2BFE8A1)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 41, 0xA81A664B)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 42, 0xC24B8B70)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 43, 0xC76C51A3)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 44, 0xD192E819)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 45, 0xD6990624)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 46, 0xF40E3585)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 47, 0x106AA070)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 48, 0x19A4C116)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 49, 0x1E376C08)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 50, 0x2748774C)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 51, 0x34B0BCB5)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 52, 0x391C0CB3)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 53, 0x4ED8AA4A)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 54, 0x5B9CCA4F)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 55, 0x682E6FF3)
|
|
||||||
ss[3], ss[7] = RND(ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 56, 0x748F82EE)
|
|
||||||
ss[2], ss[6] = RND(ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 57, 0x78A5636F)
|
|
||||||
ss[1], ss[5] = RND(ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 58, 0x84C87814)
|
|
||||||
ss[0], ss[4] = RND(ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 59, 0x8CC70208)
|
|
||||||
ss[7], ss[3] = RND(ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 60, 0x90BEFFFA)
|
|
||||||
ss[6], ss[2] = RND(ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 61, 0xA4506CEB)
|
|
||||||
ss[5], ss[1] = RND(ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 62, 0xBEF9A3F7)
|
|
||||||
ss[4], ss[0] = RND(ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 63, 0xC67178F2)
|
|
||||||
|
|
||||||
dig = []
|
|
||||||
for i, x in enumerate(sha_info["digest"]):
|
|
||||||
dig.append((x + ss[i]) & 0xFFFFFFFF)
|
|
||||||
sha_info["digest"] = dig
|
|
||||||
|
|
||||||
|
|
||||||
def sha_init():
|
|
||||||
sha_info = new_shaobject()
|
|
||||||
sha_info["digest"] = [
|
|
||||||
0x6A09E667,
|
|
||||||
0xBB67AE85,
|
|
||||||
0x3C6EF372,
|
|
||||||
0xA54FF53A,
|
|
||||||
0x510E527F,
|
|
||||||
0x9B05688C,
|
|
||||||
0x1F83D9AB,
|
|
||||||
0x5BE0CD19,
|
|
||||||
]
|
|
||||||
sha_info["count_lo"] = 0
|
|
||||||
sha_info["count_hi"] = 0
|
|
||||||
sha_info["local"] = 0
|
|
||||||
sha_info["digestsize"] = 32
|
|
||||||
return sha_info
|
|
||||||
|
|
||||||
|
|
||||||
def sha224_init():
|
|
||||||
sha_info = new_shaobject()
|
|
||||||
sha_info["digest"] = [
|
|
||||||
0xC1059ED8,
|
|
||||||
0x367CD507,
|
|
||||||
0x3070DD17,
|
|
||||||
0xF70E5939,
|
|
||||||
0xFFC00B31,
|
|
||||||
0x68581511,
|
|
||||||
0x64F98FA7,
|
|
||||||
0xBEFA4FA4,
|
|
||||||
]
|
|
||||||
sha_info["count_lo"] = 0
|
|
||||||
sha_info["count_hi"] = 0
|
|
||||||
sha_info["local"] = 0
|
|
||||||
sha_info["digestsize"] = 28
|
|
||||||
return sha_info
|
|
||||||
|
|
||||||
|
|
||||||
def getbuf(s):
|
|
||||||
if isinstance(s, str):
|
|
||||||
return s.encode("ascii")
|
|
||||||
else:
|
|
||||||
return bytes(s)
|
|
||||||
|
|
||||||
|
|
||||||
def sha_update(sha_info, buffer):
|
|
||||||
if isinstance(buffer, str):
|
|
||||||
raise TypeError("Unicode strings must be encoded before hashing")
|
|
||||||
count = len(buffer)
|
|
||||||
buffer_idx = 0
|
|
||||||
clo = (sha_info["count_lo"] + (count << 3)) & 0xFFFFFFFF
|
|
||||||
if clo < sha_info["count_lo"]:
|
|
||||||
sha_info["count_hi"] += 1
|
|
||||||
sha_info["count_lo"] = clo
|
|
||||||
|
|
||||||
sha_info["count_hi"] += count >> 29
|
|
||||||
|
|
||||||
if sha_info["local"]:
|
|
||||||
i = SHA_BLOCKSIZE - sha_info["local"]
|
|
||||||
if i > count:
|
|
||||||
i = count
|
|
||||||
|
|
||||||
# copy buffer
|
|
||||||
for x in enumerate(buffer[buffer_idx : buffer_idx + i]):
|
|
||||||
sha_info["data"][sha_info["local"] + x[0]] = x[1]
|
|
||||||
|
|
||||||
count -= i
|
|
||||||
buffer_idx += i
|
|
||||||
|
|
||||||
sha_info["local"] += i
|
|
||||||
if sha_info["local"] == SHA_BLOCKSIZE:
|
|
||||||
sha_transform(sha_info)
|
|
||||||
sha_info["local"] = 0
|
|
||||||
else:
|
|
||||||
return
|
|
||||||
|
|
||||||
while count >= SHA_BLOCKSIZE:
|
|
||||||
# copy buffer
|
|
||||||
sha_info["data"] = list(buffer[buffer_idx : buffer_idx + SHA_BLOCKSIZE])
|
|
||||||
count -= SHA_BLOCKSIZE
|
|
||||||
buffer_idx += SHA_BLOCKSIZE
|
|
||||||
sha_transform(sha_info)
|
|
||||||
|
|
||||||
# copy buffer
|
|
||||||
pos = sha_info["local"]
|
|
||||||
sha_info["data"][pos : pos + count] = list(buffer[buffer_idx : buffer_idx + count])
|
|
||||||
sha_info["local"] = count
|
|
||||||
|
|
||||||
|
|
||||||
def sha_final(sha_info):
|
|
||||||
lo_bit_count = sha_info["count_lo"]
|
|
||||||
hi_bit_count = sha_info["count_hi"]
|
|
||||||
count = (lo_bit_count >> 3) & 0x3F
|
|
||||||
sha_info["data"][count] = 0x80
|
|
||||||
count += 1
|
|
||||||
if count > SHA_BLOCKSIZE - 8:
|
|
||||||
# zero the bytes in data after the count
|
|
||||||
sha_info["data"] = sha_info["data"][:count] + ([0] * (SHA_BLOCKSIZE - count))
|
|
||||||
sha_transform(sha_info)
|
|
||||||
# zero bytes in data
|
|
||||||
sha_info["data"] = [0] * SHA_BLOCKSIZE
|
|
||||||
else:
|
|
||||||
sha_info["data"] = sha_info["data"][:count] + ([0] * (SHA_BLOCKSIZE - count))
|
|
||||||
|
|
||||||
sha_info["data"][56] = (hi_bit_count >> 24) & 0xFF
|
|
||||||
sha_info["data"][57] = (hi_bit_count >> 16) & 0xFF
|
|
||||||
sha_info["data"][58] = (hi_bit_count >> 8) & 0xFF
|
|
||||||
sha_info["data"][59] = (hi_bit_count >> 0) & 0xFF
|
|
||||||
sha_info["data"][60] = (lo_bit_count >> 24) & 0xFF
|
|
||||||
sha_info["data"][61] = (lo_bit_count >> 16) & 0xFF
|
|
||||||
sha_info["data"][62] = (lo_bit_count >> 8) & 0xFF
|
|
||||||
sha_info["data"][63] = (lo_bit_count >> 0) & 0xFF
|
|
||||||
|
|
||||||
sha_transform(sha_info)
|
|
||||||
|
|
||||||
dig = []
|
|
||||||
for i in sha_info["digest"]:
|
|
||||||
dig.extend([((i >> 24) & 0xFF), ((i >> 16) & 0xFF), ((i >> 8) & 0xFF), (i & 0xFF)])
|
|
||||||
return bytes(dig)
|
|
||||||
|
|
||||||
|
|
||||||
class sha256(object):
|
|
||||||
digest_size = digestsize = SHA_DIGESTSIZE
|
|
||||||
block_size = SHA_BLOCKSIZE
|
|
||||||
|
|
||||||
def __init__(self, s=None):
|
|
||||||
self._sha = sha_init()
|
|
||||||
if s:
|
|
||||||
sha_update(self._sha, getbuf(s))
|
|
||||||
|
|
||||||
def update(self, s):
|
|
||||||
sha_update(self._sha, getbuf(s))
|
|
||||||
|
|
||||||
def digest(self):
|
|
||||||
return sha_final(self._sha.copy())[: self._sha["digestsize"]]
|
|
||||||
|
|
||||||
def hexdigest(self):
|
|
||||||
return "".join(["%.2x" % i for i in self.digest()])
|
|
||||||
|
|
||||||
def copy(self):
|
|
||||||
new = sha256()
|
|
||||||
new._sha = self._sha.copy()
|
|
||||||
return new
|
|
||||||
|
|
||||||
|
|
||||||
class sha224(sha256):
|
|
||||||
digest_size = digestsize = 28
|
|
||||||
|
|
||||||
def __init__(self, s=None):
|
|
||||||
self._sha = sha224_init()
|
|
||||||
if s:
|
|
||||||
sha_update(self._sha, getbuf(s))
|
|
||||||
|
|
||||||
def copy(self):
|
|
||||||
new = sha224()
|
|
||||||
new._sha = self._sha.copy()
|
|
||||||
return new
|
|
||||||
|
|
||||||
|
|
||||||
def test():
|
|
||||||
a_str = "just a test string"
|
|
||||||
|
|
||||||
assert (
|
|
||||||
b"\xe3\xb0\xc4B\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99o\xb9$'\xaeA\xe4d\x9b\x93L\xa4\x95\x99\x1bxR\xb8U"
|
|
||||||
== sha256().digest()
|
|
||||||
)
|
|
||||||
assert (
|
|
||||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" == sha256().hexdigest()
|
|
||||||
)
|
|
||||||
assert (
|
|
||||||
"d7b553c6f09ac85d142415f857c5310f3bbbe7cdd787cce4b985acedd585266f"
|
|
||||||
== sha256(a_str).hexdigest()
|
|
||||||
)
|
|
||||||
assert (
|
|
||||||
"8113ebf33c97daa9998762aacafe750c7cefc2b2f173c90c59663a57fe626f21"
|
|
||||||
== sha256(a_str * 7).hexdigest()
|
|
||||||
)
|
|
||||||
|
|
||||||
s = sha256(a_str)
|
|
||||||
s.update(a_str)
|
|
||||||
assert "03d9963e05a094593190b6fc794cb1a3e1ac7d7883f0b5855268afeccc70d461" == s.hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
test()
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
from ._sha512 import sha384
|
|
||||||
@@ -1,519 +0,0 @@
|
|||||||
"""
|
|
||||||
This code was Ported from CPython's sha512module.c
|
|
||||||
"""
|
|
||||||
|
|
||||||
SHA_BLOCKSIZE = 128
|
|
||||||
SHA_DIGESTSIZE = 64
|
|
||||||
|
|
||||||
|
|
||||||
def new_shaobject():
|
|
||||||
return {
|
|
||||||
"digest": [0] * 8,
|
|
||||||
"count_lo": 0,
|
|
||||||
"count_hi": 0,
|
|
||||||
"data": [0] * SHA_BLOCKSIZE,
|
|
||||||
"local": 0,
|
|
||||||
"digestsize": 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
ROR64 = (
|
|
||||||
lambda x, y: (((x & 0xFFFFFFFFFFFFFFFF) >> (y & 63)) | (x << (64 - (y & 63))))
|
|
||||||
& 0xFFFFFFFFFFFFFFFF
|
|
||||||
)
|
|
||||||
Ch = lambda x, y, z: (z ^ (x & (y ^ z)))
|
|
||||||
Maj = lambda x, y, z: (((x | y) & z) | (x & y))
|
|
||||||
S = lambda x, n: ROR64(x, n)
|
|
||||||
R = lambda x, n: (x & 0xFFFFFFFFFFFFFFFF) >> n
|
|
||||||
Sigma0 = lambda x: (S(x, 28) ^ S(x, 34) ^ S(x, 39))
|
|
||||||
Sigma1 = lambda x: (S(x, 14) ^ S(x, 18) ^ S(x, 41))
|
|
||||||
Gamma0 = lambda x: (S(x, 1) ^ S(x, 8) ^ R(x, 7))
|
|
||||||
Gamma1 = lambda x: (S(x, 19) ^ S(x, 61) ^ R(x, 6))
|
|
||||||
|
|
||||||
|
|
||||||
def sha_transform(sha_info):
|
|
||||||
W = []
|
|
||||||
|
|
||||||
d = sha_info["data"]
|
|
||||||
for i in range(0, 16):
|
|
||||||
W.append(
|
|
||||||
(d[8 * i] << 56)
|
|
||||||
+ (d[8 * i + 1] << 48)
|
|
||||||
+ (d[8 * i + 2] << 40)
|
|
||||||
+ (d[8 * i + 3] << 32)
|
|
||||||
+ (d[8 * i + 4] << 24)
|
|
||||||
+ (d[8 * i + 5] << 16)
|
|
||||||
+ (d[8 * i + 6] << 8)
|
|
||||||
+ d[8 * i + 7]
|
|
||||||
)
|
|
||||||
|
|
||||||
for i in range(16, 80):
|
|
||||||
W.append(
|
|
||||||
(Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xFFFFFFFFFFFFFFFF
|
|
||||||
)
|
|
||||||
|
|
||||||
ss = sha_info["digest"][:]
|
|
||||||
|
|
||||||
def RND(a, b, c, d, e, f, g, h, i, ki):
|
|
||||||
t0 = (h + Sigma1(e) + Ch(e, f, g) + ki + W[i]) & 0xFFFFFFFFFFFFFFFF
|
|
||||||
t1 = (Sigma0(a) + Maj(a, b, c)) & 0xFFFFFFFFFFFFFFFF
|
|
||||||
d = (d + t0) & 0xFFFFFFFFFFFFFFFF
|
|
||||||
h = (t0 + t1) & 0xFFFFFFFFFFFFFFFF
|
|
||||||
return d & 0xFFFFFFFFFFFFFFFF, h & 0xFFFFFFFFFFFFFFFF
|
|
||||||
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 0, 0x428A2F98D728AE22
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 1, 0x7137449123EF65CD
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 2, 0xB5C0FBCFEC4D3B2F
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 3, 0xE9B5DBA58189DBBC
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 4, 0x3956C25BF348B538
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 5, 0x59F111F1B605D019
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 6, 0x923F82A4AF194F9B
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 7, 0xAB1C5ED5DA6D8118
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 8, 0xD807AA98A3030242
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 9, 0x12835B0145706FBE
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 10, 0x243185BE4EE4B28C
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 11, 0x550C7DC3D5FFB4E2
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 12, 0x72BE5D74F27B896F
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 13, 0x80DEB1FE3B1696B1
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 14, 0x9BDC06A725C71235
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 15, 0xC19BF174CF692694
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 16, 0xE49B69C19EF14AD2
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 17, 0xEFBE4786384F25E3
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 18, 0x0FC19DC68B8CD5B5
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 19, 0x240CA1CC77AC9C65
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 20, 0x2DE92C6F592B0275
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 21, 0x4A7484AA6EA6E483
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 22, 0x5CB0A9DCBD41FBD4
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 23, 0x76F988DA831153B5
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 24, 0x983E5152EE66DFAB
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 25, 0xA831C66D2DB43210
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 26, 0xB00327C898FB213F
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 27, 0xBF597FC7BEEF0EE4
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 28, 0xC6E00BF33DA88FC2
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 29, 0xD5A79147930AA725
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 30, 0x06CA6351E003826F
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 31, 0x142929670A0E6E70
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 32, 0x27B70A8546D22FFC
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 33, 0x2E1B21385C26C926
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 34, 0x4D2C6DFC5AC42AED
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 35, 0x53380D139D95B3DF
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 36, 0x650A73548BAF63DE
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 37, 0x766A0ABB3C77B2A8
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 38, 0x81C2C92E47EDAEE6
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 39, 0x92722C851482353B
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 40, 0xA2BFE8A14CF10364
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 41, 0xA81A664BBC423001
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 42, 0xC24B8B70D0F89791
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 43, 0xC76C51A30654BE30
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 44, 0xD192E819D6EF5218
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 45, 0xD69906245565A910
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 46, 0xF40E35855771202A
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 47, 0x106AA07032BBD1B8
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 48, 0x19A4C116B8D2D0C8
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 49, 0x1E376C085141AB53
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 50, 0x2748774CDF8EEB99
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 51, 0x34B0BCB5E19B48A8
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 52, 0x391C0CB3C5C95A63
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 53, 0x4ED8AA4AE3418ACB
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 54, 0x5B9CCA4F7763E373
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 55, 0x682E6FF3D6B2B8A3
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 56, 0x748F82EE5DEFB2FC
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 57, 0x78A5636F43172F60
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 58, 0x84C87814A1F0AB72
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 59, 0x8CC702081A6439EC
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 60, 0x90BEFFFA23631E28
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 61, 0xA4506CEBDE82BDE9
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 62, 0xBEF9A3F7B2C67915
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 63, 0xC67178F2E372532B
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 64, 0xCA273ECEEA26619C
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 65, 0xD186B8C721C0C207
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 66, 0xEADA7DD6CDE0EB1E
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 67, 0xF57D4F7FEE6ED178
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 68, 0x06F067AA72176FBA
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 69, 0x0A637DC5A2C898A6
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 70, 0x113F9804BEF90DAE
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 71, 0x1B710B35131C471B
|
|
||||||
)
|
|
||||||
ss[3], ss[7] = RND(
|
|
||||||
ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 72, 0x28DB77F523047D84
|
|
||||||
)
|
|
||||||
ss[2], ss[6] = RND(
|
|
||||||
ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 73, 0x32CAAB7B40C72493
|
|
||||||
)
|
|
||||||
ss[1], ss[5] = RND(
|
|
||||||
ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 74, 0x3C9EBE0A15C9BEBC
|
|
||||||
)
|
|
||||||
ss[0], ss[4] = RND(
|
|
||||||
ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 75, 0x431D67C49C100D4C
|
|
||||||
)
|
|
||||||
ss[7], ss[3] = RND(
|
|
||||||
ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 76, 0x4CC5D4BECB3E42B6
|
|
||||||
)
|
|
||||||
ss[6], ss[2] = RND(
|
|
||||||
ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 77, 0x597F299CFC657E2A
|
|
||||||
)
|
|
||||||
ss[5], ss[1] = RND(
|
|
||||||
ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 78, 0x5FCB6FAB3AD6FAEC
|
|
||||||
)
|
|
||||||
ss[4], ss[0] = RND(
|
|
||||||
ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 79, 0x6C44198C4A475817
|
|
||||||
)
|
|
||||||
|
|
||||||
dig = []
|
|
||||||
for i, x in enumerate(sha_info["digest"]):
|
|
||||||
dig.append((x + ss[i]) & 0xFFFFFFFFFFFFFFFF)
|
|
||||||
sha_info["digest"] = dig
|
|
||||||
|
|
||||||
|
|
||||||
def sha_init():
|
|
||||||
sha_info = new_shaobject()
|
|
||||||
sha_info["digest"] = [
|
|
||||||
0x6A09E667F3BCC908,
|
|
||||||
0xBB67AE8584CAA73B,
|
|
||||||
0x3C6EF372FE94F82B,
|
|
||||||
0xA54FF53A5F1D36F1,
|
|
||||||
0x510E527FADE682D1,
|
|
||||||
0x9B05688C2B3E6C1F,
|
|
||||||
0x1F83D9ABFB41BD6B,
|
|
||||||
0x5BE0CD19137E2179,
|
|
||||||
]
|
|
||||||
sha_info["count_lo"] = 0
|
|
||||||
sha_info["count_hi"] = 0
|
|
||||||
sha_info["local"] = 0
|
|
||||||
sha_info["digestsize"] = 64
|
|
||||||
return sha_info
|
|
||||||
|
|
||||||
|
|
||||||
def sha384_init():
|
|
||||||
sha_info = new_shaobject()
|
|
||||||
sha_info["digest"] = [
|
|
||||||
0xCBBB9D5DC1059ED8,
|
|
||||||
0x629A292A367CD507,
|
|
||||||
0x9159015A3070DD17,
|
|
||||||
0x152FECD8F70E5939,
|
|
||||||
0x67332667FFC00B31,
|
|
||||||
0x8EB44A8768581511,
|
|
||||||
0xDB0C2E0D64F98FA7,
|
|
||||||
0x47B5481DBEFA4FA4,
|
|
||||||
]
|
|
||||||
sha_info["count_lo"] = 0
|
|
||||||
sha_info["count_hi"] = 0
|
|
||||||
sha_info["local"] = 0
|
|
||||||
sha_info["digestsize"] = 48
|
|
||||||
return sha_info
|
|
||||||
|
|
||||||
|
|
||||||
def getbuf(s):
|
|
||||||
if isinstance(s, str):
|
|
||||||
return s.encode("ascii")
|
|
||||||
else:
|
|
||||||
return bytes(s)
|
|
||||||
|
|
||||||
|
|
||||||
def sha_update(sha_info, buffer):
|
|
||||||
if isinstance(buffer, str):
|
|
||||||
raise TypeError("Unicode strings must be encoded before hashing")
|
|
||||||
count = len(buffer)
|
|
||||||
buffer_idx = 0
|
|
||||||
clo = (sha_info["count_lo"] + (count << 3)) & 0xFFFFFFFF
|
|
||||||
if clo < sha_info["count_lo"]:
|
|
||||||
sha_info["count_hi"] += 1
|
|
||||||
sha_info["count_lo"] = clo
|
|
||||||
|
|
||||||
sha_info["count_hi"] += count >> 29
|
|
||||||
|
|
||||||
if sha_info["local"]:
|
|
||||||
i = SHA_BLOCKSIZE - sha_info["local"]
|
|
||||||
if i > count:
|
|
||||||
i = count
|
|
||||||
|
|
||||||
# copy buffer
|
|
||||||
for x in enumerate(buffer[buffer_idx : buffer_idx + i]):
|
|
||||||
sha_info["data"][sha_info["local"] + x[0]] = x[1]
|
|
||||||
|
|
||||||
count -= i
|
|
||||||
buffer_idx += i
|
|
||||||
|
|
||||||
sha_info["local"] += i
|
|
||||||
if sha_info["local"] == SHA_BLOCKSIZE:
|
|
||||||
sha_transform(sha_info)
|
|
||||||
sha_info["local"] = 0
|
|
||||||
else:
|
|
||||||
return
|
|
||||||
|
|
||||||
while count >= SHA_BLOCKSIZE:
|
|
||||||
# copy buffer
|
|
||||||
sha_info["data"] = list(buffer[buffer_idx : buffer_idx + SHA_BLOCKSIZE])
|
|
||||||
count -= SHA_BLOCKSIZE
|
|
||||||
buffer_idx += SHA_BLOCKSIZE
|
|
||||||
sha_transform(sha_info)
|
|
||||||
|
|
||||||
# copy buffer
|
|
||||||
pos = sha_info["local"]
|
|
||||||
sha_info["data"][pos : pos + count] = list(buffer[buffer_idx : buffer_idx + count])
|
|
||||||
sha_info["local"] = count
|
|
||||||
|
|
||||||
|
|
||||||
def sha_final(sha_info):
|
|
||||||
lo_bit_count = sha_info["count_lo"]
|
|
||||||
hi_bit_count = sha_info["count_hi"]
|
|
||||||
count = (lo_bit_count >> 3) & 0x7F
|
|
||||||
sha_info["data"][count] = 0x80
|
|
||||||
count += 1
|
|
||||||
if count > SHA_BLOCKSIZE - 16:
|
|
||||||
# zero the bytes in data after the count
|
|
||||||
sha_info["data"] = sha_info["data"][:count] + ([0] * (SHA_BLOCKSIZE - count))
|
|
||||||
sha_transform(sha_info)
|
|
||||||
# zero bytes in data
|
|
||||||
sha_info["data"] = [0] * SHA_BLOCKSIZE
|
|
||||||
else:
|
|
||||||
sha_info["data"] = sha_info["data"][:count] + ([0] * (SHA_BLOCKSIZE - count))
|
|
||||||
|
|
||||||
sha_info["data"][112] = 0
|
|
||||||
sha_info["data"][113] = 0
|
|
||||||
sha_info["data"][114] = 0
|
|
||||||
sha_info["data"][115] = 0
|
|
||||||
sha_info["data"][116] = 0
|
|
||||||
sha_info["data"][117] = 0
|
|
||||||
sha_info["data"][118] = 0
|
|
||||||
sha_info["data"][119] = 0
|
|
||||||
|
|
||||||
sha_info["data"][120] = (hi_bit_count >> 24) & 0xFF
|
|
||||||
sha_info["data"][121] = (hi_bit_count >> 16) & 0xFF
|
|
||||||
sha_info["data"][122] = (hi_bit_count >> 8) & 0xFF
|
|
||||||
sha_info["data"][123] = (hi_bit_count >> 0) & 0xFF
|
|
||||||
sha_info["data"][124] = (lo_bit_count >> 24) & 0xFF
|
|
||||||
sha_info["data"][125] = (lo_bit_count >> 16) & 0xFF
|
|
||||||
sha_info["data"][126] = (lo_bit_count >> 8) & 0xFF
|
|
||||||
sha_info["data"][127] = (lo_bit_count >> 0) & 0xFF
|
|
||||||
|
|
||||||
sha_transform(sha_info)
|
|
||||||
|
|
||||||
dig = []
|
|
||||||
for i in sha_info["digest"]:
|
|
||||||
dig.extend(
|
|
||||||
[
|
|
||||||
((i >> 56) & 0xFF),
|
|
||||||
((i >> 48) & 0xFF),
|
|
||||||
((i >> 40) & 0xFF),
|
|
||||||
((i >> 32) & 0xFF),
|
|
||||||
((i >> 24) & 0xFF),
|
|
||||||
((i >> 16) & 0xFF),
|
|
||||||
((i >> 8) & 0xFF),
|
|
||||||
(i & 0xFF),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
return bytes(dig)
|
|
||||||
|
|
||||||
|
|
||||||
class sha512(object):
|
|
||||||
digest_size = digestsize = SHA_DIGESTSIZE
|
|
||||||
block_size = SHA_BLOCKSIZE
|
|
||||||
|
|
||||||
def __init__(self, s=None):
|
|
||||||
self._sha = sha_init()
|
|
||||||
if s:
|
|
||||||
sha_update(self._sha, getbuf(s))
|
|
||||||
|
|
||||||
def update(self, s):
|
|
||||||
sha_update(self._sha, getbuf(s))
|
|
||||||
|
|
||||||
def digest(self):
|
|
||||||
return sha_final(self._sha.copy())[: self._sha["digestsize"]]
|
|
||||||
|
|
||||||
def hexdigest(self):
|
|
||||||
return "".join(["%.2x" % i for i in self.digest()])
|
|
||||||
|
|
||||||
def copy(self):
|
|
||||||
new = sha512()
|
|
||||||
new._sha = self._sha.copy()
|
|
||||||
return new
|
|
||||||
|
|
||||||
|
|
||||||
class sha384(sha512):
|
|
||||||
digest_size = digestsize = 48
|
|
||||||
|
|
||||||
def __init__(self, s=None):
|
|
||||||
self._sha = sha384_init()
|
|
||||||
if s:
|
|
||||||
sha_update(self._sha, getbuf(s))
|
|
||||||
|
|
||||||
def copy(self):
|
|
||||||
new = sha384()
|
|
||||||
new._sha = self._sha.copy()
|
|
||||||
return new
|
|
||||||
|
|
||||||
|
|
||||||
def test():
|
|
||||||
a_str = "just a test string"
|
|
||||||
|
|
||||||
assert (
|
|
||||||
sha512().digest()
|
|
||||||
== b"\xcf\x83\xe15~\xef\xb8\xbd\xf1T(P\xd6m\x80\x07\xd6 \xe4\x05\x0bW\x15\xdc\x83\xf4\xa9!\xd3l\xe9\xceG\xd0\xd1<]\x85\xf2\xb0\xff\x83\x18\xd2\x87~\xec/c\xb91\xbdGAz\x81\xa582z\xf9'\xda>"
|
|
||||||
)
|
|
||||||
assert (
|
|
||||||
sha512().hexdigest()
|
|
||||||
== "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
|
|
||||||
)
|
|
||||||
assert (
|
|
||||||
sha512(a_str).hexdigest()
|
|
||||||
== "68be4c6664af867dd1d01c8d77e963d87d77b702400c8fabae355a41b8927a5a5533a7f1c28509bbd65c5f3ac716f33be271fbda0ca018b71a84708c9fae8a53"
|
|
||||||
)
|
|
||||||
assert (
|
|
||||||
sha512(a_str * 7).hexdigest()
|
|
||||||
== "3233acdbfcfff9bff9fc72401d31dbffa62bd24e9ec846f0578d647da73258d9f0879f7fde01fe2cc6516af3f343807fdef79e23d696c923d79931db46bf1819"
|
|
||||||
)
|
|
||||||
|
|
||||||
s = sha512(a_str)
|
|
||||||
s.update(a_str)
|
|
||||||
assert (
|
|
||||||
s.hexdigest()
|
|
||||||
== "341aeb668730bbb48127d5531115f3c39d12cb9586a6ca770898398aff2411087cfe0b570689adf328cddeb1f00803acce6737a19f310b53bbdb0320828f75bb"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
test()
|
|
||||||
@@ -1,152 +1,87 @@
|
|||||||
"""HMAC (Keyed-Hashing for Message Authentication) Python module.
|
# Implements the hmac module from the Python standard library.
|
||||||
Implements the HMAC algorithm as described by RFC 2104.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import warnings as _warnings
|
|
||||||
|
|
||||||
# from _operator import _compare_digest as compare_digest
|
|
||||||
import hashlib as _hashlib
|
|
||||||
|
|
||||||
PendingDeprecationWarning = None
|
|
||||||
RuntimeWarning = None
|
|
||||||
|
|
||||||
trans_5C = bytes((x ^ 0x5C) for x in range(256))
|
|
||||||
trans_36 = bytes((x ^ 0x36) for x in range(256))
|
|
||||||
|
|
||||||
|
|
||||||
def translate(d, t):
|
|
||||||
return bytes(t[x] for x in d)
|
|
||||||
|
|
||||||
|
|
||||||
# The size of the digests returned by HMAC depends on the underlying
|
|
||||||
# hashing module used. Use digest_size from the instance of HMAC instead.
|
|
||||||
digest_size = None
|
|
||||||
|
|
||||||
|
|
||||||
class HMAC:
|
class HMAC:
|
||||||
"""RFC 2104 HMAC class. Also complies with RFC 4231.
|
|
||||||
This supports the API for Cryptographic Hash Functions (PEP 247).
|
|
||||||
"""
|
|
||||||
|
|
||||||
blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
|
|
||||||
|
|
||||||
def __init__(self, key, msg=None, digestmod=None):
|
def __init__(self, key, msg=None, digestmod=None):
|
||||||
"""Create a new HMAC object.
|
|
||||||
key: key for the keyed hash object.
|
|
||||||
msg: Initial input for the hash, if provided.
|
|
||||||
digestmod: A module supporting PEP 247. *OR*
|
|
||||||
A hashlib constructor returning a new hash object. *OR*
|
|
||||||
A hash name suitable for hashlib.new().
|
|
||||||
Defaults to hashlib.md5.
|
|
||||||
Implicit default to hashlib.md5 is deprecated and will be
|
|
||||||
removed in Python 3.6.
|
|
||||||
Note: key and msg must be a bytes or bytearray objects.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if not isinstance(key, (bytes, bytearray)):
|
if not isinstance(key, (bytes, bytearray)):
|
||||||
raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
|
raise TypeError("key: expected bytes/bytearray")
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
|
||||||
if digestmod is None:
|
if digestmod is None:
|
||||||
_warnings.warn(
|
# TODO: Default hash algorithm is now deprecated.
|
||||||
"HMAC() without an explicit digestmod argument " "is deprecated.",
|
digestmod = hashlib.md5
|
||||||
PendingDeprecationWarning,
|
|
||||||
2,
|
|
||||||
)
|
|
||||||
digestmod = _hashlib.md5
|
|
||||||
|
|
||||||
if callable(digestmod):
|
if callable(digestmod):
|
||||||
self.digest_cons = digestmod
|
# A hashlib constructor returning a new hash object.
|
||||||
|
make_hash = digestmod # A
|
||||||
elif isinstance(digestmod, str):
|
elif isinstance(digestmod, str):
|
||||||
self.digest_cons = lambda d=b"": _hashlib.new(digestmod, d)
|
# A hash name suitable for hashlib.new().
|
||||||
|
make_hash = lambda d=b"": hashlib.new(digestmod, d) # B
|
||||||
else:
|
else:
|
||||||
self.digest_cons = lambda d=b"": digestmod.new(d)
|
# A module supporting PEP 247.
|
||||||
|
make_hash = digestmod.new # C
|
||||||
|
|
||||||
self.outer = self.digest_cons()
|
self._outer = make_hash()
|
||||||
self.inner = self.digest_cons()
|
self._inner = make_hash()
|
||||||
self.digest_size = self.inner.digest_size
|
|
||||||
|
|
||||||
if hasattr(self.inner, "block_size"):
|
self.digest_size = getattr(self._inner, "digest_size", None)
|
||||||
blocksize = self.inner.block_size
|
# If the provided hash doesn't support block_size (e.g. built-in
|
||||||
if blocksize < 16:
|
# hashlib), 64 is the correct default for all built-in hash
|
||||||
_warnings.warn(
|
# functions (md5, sha1, sha256).
|
||||||
"block_size of %d seems too small; using our "
|
self.block_size = getattr(self._inner, "block_size", 64)
|
||||||
"default of %d." % (blocksize, self.blocksize),
|
|
||||||
RuntimeWarning,
|
|
||||||
2,
|
|
||||||
)
|
|
||||||
blocksize = self.blocksize
|
|
||||||
else:
|
|
||||||
_warnings.warn(
|
|
||||||
"No block_size attribute on given digest object; "
|
|
||||||
"Assuming %d." % (self.blocksize),
|
|
||||||
RuntimeWarning,
|
|
||||||
2,
|
|
||||||
)
|
|
||||||
blocksize = self.blocksize
|
|
||||||
|
|
||||||
# self.blocksize is the default blocksize. self.block_size is
|
# Truncate to digest_size if greater than block_size.
|
||||||
# effective block size as well as the public API attribute.
|
if len(key) > self.block_size:
|
||||||
self.block_size = blocksize
|
key = make_hash(key).digest()
|
||||||
|
|
||||||
if len(key) > blocksize:
|
# Pad to block size.
|
||||||
key = self.digest_cons(key).digest()
|
key = key + bytes(self.block_size - len(key))
|
||||||
|
|
||||||
|
self._outer.update(bytes(x ^ 0x5C for x in key))
|
||||||
|
self._inner.update(bytes(x ^ 0x36 for x in key))
|
||||||
|
|
||||||
key = key + bytes(blocksize - len(key))
|
|
||||||
self.outer.update(translate(key, trans_5C))
|
|
||||||
self.inner.update(translate(key, trans_36))
|
|
||||||
if msg is not None:
|
if msg is not None:
|
||||||
self.update(msg)
|
self.update(msg)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
return "hmac-" + self.inner.name
|
return "hmac-" + getattr(self._inner, "name", type(self._inner).__name__)
|
||||||
|
|
||||||
def update(self, msg):
|
def update(self, msg):
|
||||||
"""Update this hashing object with the string msg."""
|
self._inner.update(msg)
|
||||||
self.inner.update(msg)
|
|
||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
"""Return a separate copy of this hashing object.
|
if not hasattr(self._inner, "copy"):
|
||||||
An update to this copy won't affect the original object.
|
# Not supported for built-in hash functions.
|
||||||
"""
|
raise NotImplementedError()
|
||||||
# Call __new__ directly to avoid the expensive __init__.
|
# Call __new__ directly to avoid the expensive __init__.
|
||||||
other = self.__class__.__new__(self.__class__)
|
other = self.__class__.__new__(self.__class__)
|
||||||
other.digest_cons = self.digest_cons
|
other.block_size = self.block_size
|
||||||
other.digest_size = self.digest_size
|
other.digest_size = self.digest_size
|
||||||
other.inner = self.inner.copy()
|
other._inner = self._inner.copy()
|
||||||
other.outer = self.outer.copy()
|
other._outer = self._outer.copy()
|
||||||
return other
|
return other
|
||||||
|
|
||||||
def _current(self):
|
def _current(self):
|
||||||
"""Return a hash object for the current state.
|
h = self._outer
|
||||||
To be used only internally with digest() and hexdigest().
|
if hasattr(h, "copy"):
|
||||||
"""
|
# built-in hash functions don't support this, and as a result,
|
||||||
h = self.outer.copy()
|
# digest() will finalise the hmac and further calls to
|
||||||
h.update(self.inner.digest())
|
# update/digest will fail.
|
||||||
|
h = h.copy()
|
||||||
|
h.update(self._inner.digest())
|
||||||
return h
|
return h
|
||||||
|
|
||||||
def digest(self):
|
def digest(self):
|
||||||
"""Return the hash value of this hashing object.
|
|
||||||
This returns a string containing 8-bit data. The object is
|
|
||||||
not altered in any way by this function; you can continue
|
|
||||||
updating the object after calling this function.
|
|
||||||
"""
|
|
||||||
h = self._current()
|
h = self._current()
|
||||||
return h.digest()
|
return h.digest()
|
||||||
|
|
||||||
def hexdigest(self):
|
def hexdigest(self):
|
||||||
"""Like digest(), but returns a string of hexadecimal digits instead."""
|
import binascii
|
||||||
h = self._current()
|
|
||||||
return h.hexdigest()
|
return str(binascii.hexlify(self.digest()), "utf-8")
|
||||||
|
|
||||||
|
|
||||||
def new(key, msg=None, digestmod=None):
|
def new(key, msg=None, digestmod=None):
|
||||||
"""Create a new hashing object and return it.
|
|
||||||
key: The starting key for the hash.
|
|
||||||
msg: if available, will immediately be hashed into the object's starting
|
|
||||||
state.
|
|
||||||
You can now feed arbitrary strings into the object using its update()
|
|
||||||
method, and can ask for the hash value at any time by calling its digest()
|
|
||||||
method.
|
|
||||||
"""
|
|
||||||
return HMAC(key, msg, digestmod)
|
return HMAC(key, msg, digestmod)
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import hmac
|
|||||||
import json
|
import json
|
||||||
from time import time
|
from time import time
|
||||||
|
|
||||||
|
|
||||||
def _to_b64url(data):
|
def _to_b64url(data):
|
||||||
return (
|
return (
|
||||||
binascii.b2a_base64(data)
|
binascii.b2a_base64(data)
|
||||||
@@ -32,13 +31,13 @@ class exceptions:
|
|||||||
class InvalidSignatureError(PyJWTError):
|
class InvalidSignatureError(PyJWTError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
class ExpiredTokenError(PyJWTError):
|
class ExpiredSignatureError(PyJWTError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def encode(payload, key, algorithm="HS256"):
|
def encode(payload, key, algorithm="HS256"):
|
||||||
if algorithm != "HS256":
|
if algorithm != "HS256":
|
||||||
raise exceptions.InvalidAlgorithmError()
|
raise exceptions.InvalidAlgorithmError
|
||||||
|
|
||||||
if isinstance(key, str):
|
if isinstance(key, str):
|
||||||
key = key.encode()
|
key = key.encode()
|
||||||
@@ -50,30 +49,30 @@ def encode(payload, key, algorithm="HS256"):
|
|||||||
|
|
||||||
def decode(token, key, algorithms=["HS256"]):
|
def decode(token, key, algorithms=["HS256"]):
|
||||||
if "HS256" not in algorithms:
|
if "HS256" not in algorithms:
|
||||||
raise exceptions.InvalidAlgorithmError()
|
raise exceptions.InvalidAlgorithmError
|
||||||
|
|
||||||
parts = token.encode().split(b".")
|
parts = token.encode().split(b".")
|
||||||
if len(parts) != 3:
|
if len(parts) != 3:
|
||||||
raise exceptions.InvalidTokenError()
|
raise exceptions.InvalidTokenError
|
||||||
|
|
||||||
try:
|
try:
|
||||||
header = json.loads(_from_b64url(parts[0]).decode())
|
header = json.loads(_from_b64url(parts[0]).decode())
|
||||||
payload = json.loads(_from_b64url(parts[1]).decode())
|
payload = json.loads(_from_b64url(parts[1]).decode())
|
||||||
signature = _from_b64url(parts[2])
|
signature = _from_b64url(parts[2])
|
||||||
except Exception:
|
except Exception:
|
||||||
raise exceptions.InvalidTokenError()
|
raise exceptions.InvalidTokenError
|
||||||
|
|
||||||
if header["alg"] not in algorithms or header["alg"] != "HS256":
|
if header["alg"] not in algorithms or header["alg"] != "HS256":
|
||||||
raise exceptions.InvalidAlgorithmError()
|
raise exceptions.InvalidAlgorithmError
|
||||||
|
|
||||||
if isinstance(key, str):
|
if isinstance(key, str):
|
||||||
key = key.encode()
|
key = key.encode()
|
||||||
calculated_signature = hmac.new(key, parts[0] + b"." + parts[1], hashlib.sha256).digest()
|
calculated_signature = hmac.new(key, parts[0] + b"." + parts[1], hashlib.sha256).digest()
|
||||||
if signature != calculated_signature:
|
if signature != calculated_signature:
|
||||||
raise exceptions.InvalidSignatureError()
|
raise exceptions.InvalidSignatureError
|
||||||
|
|
||||||
if "exp" in payload:
|
if "exp" in payload:
|
||||||
if time() > payload["exp"]:
|
if time() > payload["exp"]:
|
||||||
raise exceptions.ExpiredTokenError()
|
raise exceptions.ExpiredSignatureError
|
||||||
|
|
||||||
return payload
|
return payload
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class SingletonGenerator:
|
|||||||
|
|
||||||
def __next__(self):
|
def __next__(self):
|
||||||
if self.state is not None:
|
if self.state is not None:
|
||||||
_task_queue.push_sorted(cur_task, self.state)
|
_task_queue.push(cur_task, self.state)
|
||||||
self.state = None
|
self.state = None
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
@@ -115,11 +115,11 @@ class IOQueue:
|
|||||||
# print('poll', s, sm, ev)
|
# print('poll', s, sm, ev)
|
||||||
if ev & ~select.POLLOUT and sm[0] is not None:
|
if ev & ~select.POLLOUT and sm[0] is not None:
|
||||||
# POLLIN or error
|
# POLLIN or error
|
||||||
_task_queue.push_head(sm[0])
|
_task_queue.push(sm[0])
|
||||||
sm[0] = None
|
sm[0] = None
|
||||||
if ev & ~select.POLLIN and sm[1] is not None:
|
if ev & ~select.POLLIN and sm[1] is not None:
|
||||||
# POLLOUT or error
|
# POLLOUT or error
|
||||||
_task_queue.push_head(sm[1])
|
_task_queue.push(sm[1])
|
||||||
sm[1] = None
|
sm[1] = None
|
||||||
if sm[0] is None and sm[1] is None:
|
if sm[0] is None and sm[1] is None:
|
||||||
self._dequeue(s)
|
self._dequeue(s)
|
||||||
@@ -142,7 +142,7 @@ def create_task(coro):
|
|||||||
if not hasattr(coro, "send"):
|
if not hasattr(coro, "send"):
|
||||||
raise TypeError("coroutine expected")
|
raise TypeError("coroutine expected")
|
||||||
t = Task(coro, globals())
|
t = Task(coro, globals())
|
||||||
_task_queue.push_head(t)
|
_task_queue.push(t)
|
||||||
return t
|
return t
|
||||||
|
|
||||||
|
|
||||||
@@ -167,7 +167,7 @@ def run_until_complete(main_task=None):
|
|||||||
_io_queue.wait_io_event(dt)
|
_io_queue.wait_io_event(dt)
|
||||||
|
|
||||||
# Get next task to run and continue it
|
# Get next task to run and continue it
|
||||||
t = _task_queue.pop_head()
|
t = _task_queue.pop()
|
||||||
cur_task = t
|
cur_task = t
|
||||||
try:
|
try:
|
||||||
# Continue running the coroutine, it's responsible for rescheduling itself
|
# Continue running the coroutine, it's responsible for rescheduling itself
|
||||||
@@ -175,6 +175,10 @@ def run_until_complete(main_task=None):
|
|||||||
if not exc:
|
if not exc:
|
||||||
t.coro.send(None)
|
t.coro.send(None)
|
||||||
else:
|
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.data = None
|
||||||
t.coro.throw(exc)
|
t.coro.throw(exc)
|
||||||
except excs_all as er:
|
except excs_all as er:
|
||||||
@@ -185,22 +189,37 @@ def run_until_complete(main_task=None):
|
|||||||
if isinstance(er, StopIteration):
|
if isinstance(er, StopIteration):
|
||||||
return er.value
|
return er.value
|
||||||
raise er
|
raise er
|
||||||
# Schedule any other tasks waiting on the completion of this task
|
if t.state:
|
||||||
waiting = False
|
# Task was running but is now finished.
|
||||||
if hasattr(t, "waiting"):
|
waiting = False
|
||||||
while t.waiting.peek():
|
if t.state is True:
|
||||||
_task_queue.push_head(t.waiting.pop_head())
|
# "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
|
waiting = True
|
||||||
t.waiting = None # Free waiting queue head
|
else:
|
||||||
if not waiting and not isinstance(er, excs_stop):
|
# Schedule any other tasks waiting on the completion of this task.
|
||||||
# An exception ended this detached task, so queue it for later
|
while t.state.peek():
|
||||||
# execution to handle the uncaught exception if no other task retrieves
|
_task_queue.push(t.state.pop())
|
||||||
# the exception in the meantime (this is handled by Task.throw).
|
waiting = True
|
||||||
_task_queue.push_head(t)
|
# "False" indicates that the task is complete and has been await'ed on.
|
||||||
# Indicate task is done by setting coro to the task object itself
|
t.state = False
|
||||||
t.coro = t
|
if not waiting and not isinstance(er, excs_stop):
|
||||||
# Save return value of coro to pass up to caller
|
# An exception ended this detached task, so queue it for later
|
||||||
t.data = er
|
# 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(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
|
# Create a new task from a coroutine and run it until it finishes
|
||||||
@@ -237,7 +256,7 @@ class Loop:
|
|||||||
def stop():
|
def stop():
|
||||||
global _stop_task
|
global _stop_task
|
||||||
if _stop_task is not None:
|
if _stop_task is not None:
|
||||||
_task_queue.push_head(_stop_task)
|
_task_queue.push(_stop_task)
|
||||||
# If stop() is called again, do nothing
|
# If stop() is called again, do nothing
|
||||||
_stop_task = None
|
_stop_task = None
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class Event:
|
|||||||
# Note: This must not be called from anything except the thread running
|
# 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).
|
# the asyncio loop (i.e. neither hard or soft IRQ, or a different thread).
|
||||||
while self.waiting.peek():
|
while self.waiting.peek():
|
||||||
core._task_queue.push_head(self.waiting.pop_head())
|
core._task_queue.push(self.waiting.pop())
|
||||||
self.state = True
|
self.state = True
|
||||||
|
|
||||||
def clear(self):
|
def clear(self):
|
||||||
@@ -26,7 +26,7 @@ class Event:
|
|||||||
async def wait(self):
|
async def wait(self):
|
||||||
if not self.state:
|
if not self.state:
|
||||||
# Event not set, put the calling task on the event's waiting queue
|
# Event not set, put the calling task on the event's waiting queue
|
||||||
self.waiting.push_head(core.cur_task)
|
self.waiting.push(core.cur_task)
|
||||||
# Set calling task's data to the event's queue so it can be removed if needed
|
# Set calling task's data to the event's queue so it can be removed if needed
|
||||||
core.cur_task.data = self.waiting
|
core.cur_task.data = self.waiting
|
||||||
yield
|
yield
|
||||||
@@ -36,27 +36,29 @@ class Event:
|
|||||||
# MicroPython-extension: This can be set from outside the asyncio event loop,
|
# MicroPython-extension: This can be set from outside the asyncio event loop,
|
||||||
# such as other threads, IRQs or scheduler context. Implementation is a stream
|
# such as other threads, IRQs or scheduler context. Implementation is a stream
|
||||||
# that asyncio will poll until a flag is set.
|
# that asyncio will poll until a flag is set.
|
||||||
# Note: Unlike Event, this is self-clearing.
|
# Note: Unlike Event, this is self-clearing after a wait().
|
||||||
try:
|
try:
|
||||||
import uio
|
import uio
|
||||||
|
|
||||||
class ThreadSafeFlag(uio.IOBase):
|
class ThreadSafeFlag(uio.IOBase):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._flag = 0
|
self.state = 0
|
||||||
|
|
||||||
def ioctl(self, req, flags):
|
def ioctl(self, req, flags):
|
||||||
if req == 3: # MP_STREAM_POLL
|
if req == 3: # MP_STREAM_POLL
|
||||||
return self._flag * flags
|
return self.state * flags
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def set(self):
|
def set(self):
|
||||||
self._flag = 1
|
self.state = 1
|
||||||
|
|
||||||
|
def clear(self):
|
||||||
|
self.state = 0
|
||||||
|
|
||||||
async def wait(self):
|
async def wait(self):
|
||||||
if not self._flag:
|
if not self.state:
|
||||||
yield core._io_queue.queue_read(self)
|
yield core._io_queue.queue_read(self)
|
||||||
self._flag = 0
|
self.state = 0
|
||||||
|
|
||||||
|
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -1,49 +1,51 @@
|
|||||||
# MicroPython uasyncio module
|
# MicroPython uasyncio module
|
||||||
# MIT license; Copyright (c) 2019-2020 Damien P. George
|
# MIT license; Copyright (c) 2019-2022 Damien P. George
|
||||||
|
|
||||||
from . import core
|
from . import core
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
async def wait_for(aw, timeout, sleep=core.sleep):
|
||||||
aw = core._promote_to_task(aw)
|
aw = core._promote_to_task(aw)
|
||||||
if timeout is None:
|
if timeout is None:
|
||||||
return await aw
|
return await aw
|
||||||
|
|
||||||
def runner(waiter, aw):
|
|
||||||
nonlocal status, result
|
|
||||||
try:
|
|
||||||
result = await aw
|
|
||||||
s = True
|
|
||||||
except BaseException as er:
|
|
||||||
s = er
|
|
||||||
if status is None:
|
|
||||||
# The waiter is still waiting, set status for it and cancel it.
|
|
||||||
status = s
|
|
||||||
waiter.cancel()
|
|
||||||
|
|
||||||
# Run aw in a separate runner task that manages its exceptions.
|
# Run aw in a separate runner task that manages its exceptions.
|
||||||
status = None
|
runner_task = core.create_task(_run(core.cur_task, aw))
|
||||||
result = None
|
|
||||||
runner_task = core.create_task(runner(core.cur_task, aw))
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Wait for the timeout to elapse.
|
# Wait for the timeout to elapse.
|
||||||
await sleep(timeout)
|
await sleep(timeout)
|
||||||
except core.CancelledError as er:
|
except core.CancelledError as er:
|
||||||
if status is True:
|
status = er.value
|
||||||
# aw completed successfully and cancelled the sleep, so return aw's result.
|
if status is None:
|
||||||
return result
|
|
||||||
elif status is None:
|
|
||||||
# This wait_for was cancelled externally, so cancel aw and re-raise.
|
# This wait_for was cancelled externally, so cancel aw and re-raise.
|
||||||
status = True
|
|
||||||
runner_task.cancel()
|
runner_task.cancel()
|
||||||
raise er
|
raise er
|
||||||
|
elif status is True:
|
||||||
|
# aw completed successfully and cancelled the sleep, so return aw's result.
|
||||||
|
return er.args[1]
|
||||||
else:
|
else:
|
||||||
# aw raised an exception, propagate it out to the caller.
|
# aw raised an exception, propagate it out to the caller.
|
||||||
raise status
|
raise status
|
||||||
|
|
||||||
# The sleep finished before aw, so cancel aw and raise TimeoutError.
|
# The sleep finished before aw, so cancel aw and raise TimeoutError.
|
||||||
status = True
|
|
||||||
runner_task.cancel()
|
runner_task.cancel()
|
||||||
await runner_task
|
await runner_task
|
||||||
raise core.TimeoutError
|
raise core.TimeoutError
|
||||||
@@ -53,22 +55,75 @@ def wait_for_ms(aw, timeout):
|
|||||||
return wait_for(aw, timeout, core.sleep_ms)
|
return wait_for(aw, timeout, core.sleep_ms)
|
||||||
|
|
||||||
|
|
||||||
|
class _Remove:
|
||||||
|
@staticmethod
|
||||||
|
def remove(t):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
async def gather(*aws, return_exceptions=False):
|
async def gather(*aws, return_exceptions=False):
|
||||||
|
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(gather_task)
|
||||||
|
|
||||||
ts = [core._promote_to_task(aw) for aw in aws]
|
ts = [core._promote_to_task(aw) for aw in aws]
|
||||||
for i in range(len(ts)):
|
for i in range(len(ts)):
|
||||||
try:
|
if ts[i].state is not True:
|
||||||
# TODO handle cancel of gather itself
|
# Task is not running, gather not currently supported for this case.
|
||||||
# if ts[i].coro:
|
raise RuntimeError("can't gather")
|
||||||
# iter(ts[i]).waiting.push_head(cur_task)
|
# Register the callback to call when the task is done.
|
||||||
# try:
|
ts[i].state = done
|
||||||
# yield
|
|
||||||
# except CancelledError as er:
|
# Set the state for execution of the gather.
|
||||||
# # cancel all waiting tasks
|
gather_task = core.cur_task
|
||||||
# raise er
|
state = len(ts)
|
||||||
ts[i] = await ts[i]
|
cancel_all = False
|
||||||
except Exception as er:
|
|
||||||
if return_exceptions:
|
# Wait for the a sub-task to need attention.
|
||||||
ts[i] = er
|
gather_task.data = _Remove
|
||||||
else:
|
try:
|
||||||
raise er
|
yield
|
||||||
|
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
|
return ts
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ class Lock:
|
|||||||
raise RuntimeError("Lock not acquired")
|
raise RuntimeError("Lock not acquired")
|
||||||
if self.waiting.peek():
|
if self.waiting.peek():
|
||||||
# Task(s) waiting on lock, schedule next Task
|
# Task(s) waiting on lock, schedule next Task
|
||||||
self.state = self.waiting.pop_head()
|
self.state = self.waiting.pop()
|
||||||
core._task_queue.push_head(self.state)
|
core._task_queue.push(self.state)
|
||||||
else:
|
else:
|
||||||
# No Task waiting so unlock
|
# No Task waiting so unlock
|
||||||
self.state = 0
|
self.state = 0
|
||||||
@@ -31,7 +31,7 @@ class Lock:
|
|||||||
async def acquire(self):
|
async def acquire(self):
|
||||||
if self.state != 0:
|
if self.state != 0:
|
||||||
# Lock unavailable, put the calling Task on the waiting queue
|
# Lock unavailable, put the calling Task on the waiting queue
|
||||||
self.waiting.push_head(core.cur_task)
|
self.waiting.push(core.cur_task)
|
||||||
# Set calling task's data to the lock's queue so it can be removed if needed
|
# Set calling task's data to the lock's queue so it can be removed if needed
|
||||||
core.cur_task.data = self.waiting
|
core.cur_task.data = self.waiting
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
# This list of frozen files doesn't include task.py because that's provided by the C module.
|
# This list of package files doesn't include task.py because that's provided
|
||||||
freeze(
|
# by the C module.
|
||||||
"..",
|
package(
|
||||||
|
"uasyncio",
|
||||||
(
|
(
|
||||||
"uasyncio/__init__.py",
|
"__init__.py",
|
||||||
"uasyncio/core.py",
|
"core.py",
|
||||||
"uasyncio/event.py",
|
"event.py",
|
||||||
"uasyncio/funcs.py",
|
"funcs.py",
|
||||||
"uasyncio/lock.py",
|
"lock.py",
|
||||||
"uasyncio/stream.py",
|
"stream.py",
|
||||||
),
|
),
|
||||||
|
base_path="..",
|
||||||
opt=3,
|
opt=3,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -26,9 +26,21 @@ class Stream:
|
|||||||
# TODO yield?
|
# TODO yield?
|
||||||
self.s.close()
|
self.s.close()
|
||||||
|
|
||||||
async def read(self, n):
|
async def read(self, n=-1):
|
||||||
|
r = b""
|
||||||
|
while True:
|
||||||
|
yield core._io_queue.queue_read(self.s)
|
||||||
|
r2 = self.s.read(n)
|
||||||
|
if r2 is not None:
|
||||||
|
if n >= 0:
|
||||||
|
return r2
|
||||||
|
if not len(r2):
|
||||||
|
return r
|
||||||
|
r += r2
|
||||||
|
|
||||||
|
async def readinto(self, buf):
|
||||||
yield core._io_queue.queue_read(self.s)
|
yield core._io_queue.queue_read(self.s)
|
||||||
return self.s.read(n)
|
return self.s.readinto(buf)
|
||||||
|
|
||||||
async def readexactly(self, n):
|
async def readexactly(self, n):
|
||||||
r = b""
|
r = b""
|
||||||
@@ -52,9 +64,19 @@ class Stream:
|
|||||||
return l
|
return l
|
||||||
|
|
||||||
def write(self, buf):
|
def write(self, buf):
|
||||||
|
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
|
self.out_buf += buf
|
||||||
|
|
||||||
async def drain(self):
|
async def drain(self):
|
||||||
|
if not self.out_buf:
|
||||||
|
# Drain must always yield, so a tight loop of write+drain can't block the scheduler.
|
||||||
|
return await core.sleep_ms(0)
|
||||||
mv = memoryview(self.out_buf)
|
mv = memoryview(self.out_buf)
|
||||||
off = 0
|
off = 0
|
||||||
while off < len(mv):
|
while off < len(mv):
|
||||||
@@ -75,8 +97,8 @@ async def open_connection(host, port):
|
|||||||
from uerrno import EINPROGRESS
|
from uerrno import EINPROGRESS
|
||||||
import usocket as socket
|
import usocket as socket
|
||||||
|
|
||||||
ai = socket.getaddrinfo(host, port)[0] # TODO this is blocking!
|
ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] # TODO this is blocking!
|
||||||
s = socket.socket()
|
s = socket.socket(ai[0], ai[1], ai[2])
|
||||||
s.setblocking(False)
|
s.setblocking(False)
|
||||||
ss = Stream(s)
|
ss = Stream(s)
|
||||||
try:
|
try:
|
||||||
@@ -103,16 +125,7 @@ class Server:
|
|||||||
async def wait_closed(self):
|
async def wait_closed(self):
|
||||||
await self.task
|
await self.task
|
||||||
|
|
||||||
async def _serve(self, cb, host, port, backlog):
|
async def _serve(self, s, cb):
|
||||||
import usocket as socket
|
|
||||||
|
|
||||||
ai = 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(ai[-1])
|
|
||||||
s.listen(backlog)
|
|
||||||
self.task = core.cur_task
|
|
||||||
# Accept incoming connections
|
# Accept incoming connections
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@@ -134,9 +147,20 @@ class Server:
|
|||||||
# Helper function to start a TCP stream server, running as a new task
|
# 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
|
# TODO could use an accept-callback on socket read activity instead of creating a task
|
||||||
async def start_server(cb, host, port, backlog=5):
|
async def start_server(cb, host, port, backlog=5):
|
||||||
s = Server()
|
import usocket as socket
|
||||||
core.create_task(s._serve(cb, host, port, backlog))
|
|
||||||
return s
|
# 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
|
||||||
|
|
||||||
|
|
||||||
################################################################################
|
################################################################################
|
||||||
|
|||||||
@@ -99,19 +99,18 @@ class TaskQueue:
|
|||||||
def peek(self):
|
def peek(self):
|
||||||
return self.heap
|
return self.heap
|
||||||
|
|
||||||
def push_sorted(self, v, key):
|
def push(self, v, key=None):
|
||||||
|
assert v.ph_child is None
|
||||||
|
assert v.ph_next is None
|
||||||
v.data = None
|
v.data = None
|
||||||
v.ph_key = key
|
v.ph_key = key if key is not None else core.ticks()
|
||||||
v.ph_child = None
|
|
||||||
v.ph_next = None
|
|
||||||
self.heap = ph_meld(v, self.heap)
|
self.heap = ph_meld(v, self.heap)
|
||||||
|
|
||||||
def push_head(self, v):
|
def pop(self):
|
||||||
self.push_sorted(v, core.ticks())
|
|
||||||
|
|
||||||
def pop_head(self):
|
|
||||||
v = self.heap
|
v = self.heap
|
||||||
self.heap = ph_pairing(self.heap.ph_child)
|
assert v.ph_next is None
|
||||||
|
self.heap = ph_pairing(v.ph_child)
|
||||||
|
v.ph_child = None
|
||||||
return v
|
return v
|
||||||
|
|
||||||
def remove(self, v):
|
def remove(self, v):
|
||||||
@@ -123,6 +122,7 @@ class Task:
|
|||||||
def __init__(self, coro, globals=None):
|
def __init__(self, coro, globals=None):
|
||||||
self.coro = coro # Coroutine of this Task
|
self.coro = coro # Coroutine of this Task
|
||||||
self.data = None # General data for queue it is waiting on
|
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_key = 0 # Pairing heap
|
||||||
self.ph_child = None # Paring heap
|
self.ph_child = None # Paring heap
|
||||||
self.ph_child_last = None # Paring heap
|
self.ph_child_last = None # Paring heap
|
||||||
@@ -130,30 +130,33 @@ class Task:
|
|||||||
self.ph_rightmost_parent = None # Paring heap
|
self.ph_rightmost_parent = None # Paring heap
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
if self.coro is self:
|
if not self.state:
|
||||||
# Signal that the completed-task has been await'ed on.
|
# Task finished, signal that is has been await'ed on.
|
||||||
self.waiting = None
|
self.state = False
|
||||||
elif not hasattr(self, "waiting"):
|
elif self.state is True:
|
||||||
# Lazily allocated head of linked list of Tasks waiting on completion of this task.
|
# Allocated head of linked list of Tasks waiting on completion of this task.
|
||||||
self.waiting = TaskQueue()
|
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
|
return self
|
||||||
|
|
||||||
def __next__(self):
|
def __next__(self):
|
||||||
if self.coro is self:
|
if not self.state:
|
||||||
# Task finished, raise return value to caller so it can continue.
|
# Task finished, raise return value to caller so it can continue.
|
||||||
raise self.data
|
raise self.data
|
||||||
else:
|
else:
|
||||||
# Put calling task on waiting queue.
|
# Put calling task on waiting queue.
|
||||||
self.waiting.push_head(core.cur_task)
|
self.state.push(core.cur_task)
|
||||||
# Set calling task's data to this task that it waits on, to double-link it.
|
# Set calling task's data to this task that it waits on, to double-link it.
|
||||||
core.cur_task.data = self
|
core.cur_task.data = self
|
||||||
|
|
||||||
def done(self):
|
def done(self):
|
||||||
return self.coro is self
|
return not self.state
|
||||||
|
|
||||||
def cancel(self):
|
def cancel(self):
|
||||||
# Check if task is already finished.
|
# Check if task is already finished.
|
||||||
if self.coro is self:
|
if not self.state:
|
||||||
return False
|
return False
|
||||||
# Can't cancel self (not supported yet).
|
# Can't cancel self (not supported yet).
|
||||||
if self is core.cur_task:
|
if self is core.cur_task:
|
||||||
@@ -165,20 +168,10 @@ class Task:
|
|||||||
if hasattr(self.data, "remove"):
|
if hasattr(self.data, "remove"):
|
||||||
# Not on the main running queue, remove the task from the queue it's on.
|
# Not on the main running queue, remove the task from the queue it's on.
|
||||||
self.data.remove(self)
|
self.data.remove(self)
|
||||||
core._task_queue.push_head(self)
|
core._task_queue.push(self)
|
||||||
elif core.ticks_diff(self.ph_key, core.ticks()) > 0:
|
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.
|
# On the main running queue but scheduled in the future, so bring it forward to now.
|
||||||
core._task_queue.remove(self)
|
core._task_queue.remove(self)
|
||||||
core._task_queue.push_head(self)
|
core._task_queue.push(self)
|
||||||
self.data = core.CancelledError
|
self.data = core.CancelledError
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def throw(self, value):
|
|
||||||
# This task raised an exception which was uncaught; handle that now.
|
|
||||||
# Set the data because it was cleared by the main scheduling loop.
|
|
||||||
self.data = value
|
|
||||||
if not hasattr(self, "waiting"):
|
|
||||||
# Nothing await'ed on the task so call the exception handler.
|
|
||||||
core._exc_context["exception"] = value
|
|
||||||
core._exc_context["future"] = self
|
|
||||||
core.Loop.call_exception_handler(core._exc_context)
|
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
|
import io
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
try:
|
||||||
|
import traceback
|
||||||
|
except ImportError:
|
||||||
|
traceback = None
|
||||||
|
|
||||||
|
|
||||||
class SkipTest(Exception):
|
class SkipTest(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class AssertRaisesContext:
|
class AssertRaisesContext:
|
||||||
|
|
||||||
def __init__(self, exc):
|
def __init__(self, exc):
|
||||||
self.expected = exc
|
self.expected = exc
|
||||||
|
|
||||||
@@ -14,29 +20,98 @@ class AssertRaisesContext:
|
|||||||
return self
|
return self
|
||||||
|
|
||||||
def __exit__(self, exc_type, exc_value, tb):
|
def __exit__(self, exc_type, exc_value, tb):
|
||||||
|
self.exception = exc_value
|
||||||
if exc_type is None:
|
if exc_type is None:
|
||||||
assert False, "%r not raised" % self.expected
|
assert False, "%r not raised" % self.expected
|
||||||
if issubclass(exc_type, self.expected):
|
if issubclass(exc_type, self.expected):
|
||||||
|
# store exception for later retrieval
|
||||||
|
self.exception = exc_value
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
class TestCase:
|
# These are used to provide required context to things like subTest
|
||||||
|
__current_test__ = None
|
||||||
|
__test_result__ = None
|
||||||
|
|
||||||
def fail(self, msg=''):
|
|
||||||
|
class SubtestContext:
|
||||||
|
def __init__(self, msg=None, params=None):
|
||||||
|
self.msg = msg
|
||||||
|
self.params = params
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __exit__(self, *exc_info):
|
||||||
|
if exc_info[0] is not None:
|
||||||
|
# Exception raised
|
||||||
|
global __test_result__, __current_test__
|
||||||
|
test_details = __current_test__
|
||||||
|
if self.msg:
|
||||||
|
test_details += (f" [{self.msg}]",)
|
||||||
|
if self.params:
|
||||||
|
detail = ", ".join(f"{k}={v}" for k, v in self.params.items())
|
||||||
|
test_details += (f" ({detail})",)
|
||||||
|
|
||||||
|
_handle_test_exception(test_details, __test_result__, exc_info, False)
|
||||||
|
# Suppress the exception as we've captured it above
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class NullContext:
|
||||||
|
def __enter__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TestCase:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def addCleanup(self, func, *args, **kwargs):
|
||||||
|
if not hasattr(self, "_cleanups"):
|
||||||
|
self._cleanups = []
|
||||||
|
self._cleanups.append((func, args, kwargs))
|
||||||
|
|
||||||
|
def doCleanups(self):
|
||||||
|
if hasattr(self, "_cleanups"):
|
||||||
|
while self._cleanups:
|
||||||
|
func, args, kwargs = self._cleanups.pop()
|
||||||
|
func(*args, **kwargs)
|
||||||
|
|
||||||
|
def subTest(self, msg=None, **params):
|
||||||
|
return SubtestContext(msg=msg, params=params)
|
||||||
|
|
||||||
|
def skipTest(self, reason):
|
||||||
|
raise SkipTest(reason)
|
||||||
|
|
||||||
|
def fail(self, msg=""):
|
||||||
assert False, msg
|
assert False, msg
|
||||||
|
|
||||||
def assertEqual(self, x, y, msg=''):
|
def assertEqual(self, x, y, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "%r vs (expected) %r" % (x, y)
|
msg = "%r vs (expected) %r" % (x, y)
|
||||||
assert x == y, msg
|
assert x == y, msg
|
||||||
|
|
||||||
def assertNotEqual(self, x, y, msg=''):
|
def assertNotEqual(self, x, y, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "%r not expected to be equal %r" % (x, y)
|
msg = "%r not expected to be equal %r" % (x, y)
|
||||||
assert x != y, msg
|
assert x != y, msg
|
||||||
|
|
||||||
def assertAlmostEqual(self, x, y, places=None, msg='', delta=None):
|
def assertLessEqual(self, x, y, msg=None):
|
||||||
|
if msg is None:
|
||||||
|
msg = "%r is expected to be <= %r" % (x, y)
|
||||||
|
assert x <= y, msg
|
||||||
|
|
||||||
|
def assertGreaterEqual(self, x, y, msg=None):
|
||||||
|
if msg is None:
|
||||||
|
msg = "%r is expected to be >= %r" % (x, y)
|
||||||
|
assert x >= y, msg
|
||||||
|
|
||||||
|
def assertAlmostEqual(self, x, y, places=None, msg="", delta=None):
|
||||||
if x == y:
|
if x == y:
|
||||||
return
|
return
|
||||||
if delta is not None and places is not None:
|
if delta is not None and places is not None:
|
||||||
@@ -46,18 +121,18 @@ class TestCase:
|
|||||||
if abs(x - y) <= delta:
|
if abs(x - y) <= delta:
|
||||||
return
|
return
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = '%r != %r within %r delta' % (x, y, delta)
|
msg = "%r != %r within %r delta" % (x, y, delta)
|
||||||
else:
|
else:
|
||||||
if places is None:
|
if places is None:
|
||||||
places = 7
|
places = 7
|
||||||
if round(abs(y-x), places) == 0:
|
if round(abs(y - x), places) == 0:
|
||||||
return
|
return
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = '%r != %r within %r places' % (x, y, places)
|
msg = "%r != %r within %r places" % (x, y, places)
|
||||||
|
|
||||||
assert False, msg
|
assert False, msg
|
||||||
|
|
||||||
def assertNotAlmostEqual(self, x, y, places=None, msg='', delta=None):
|
def assertNotAlmostEqual(self, x, y, places=None, msg="", delta=None):
|
||||||
if delta is not None and places is not None:
|
if delta is not None and places is not None:
|
||||||
raise TypeError("specify delta or places not both")
|
raise TypeError("specify delta or places not both")
|
||||||
|
|
||||||
@@ -65,53 +140,53 @@ class TestCase:
|
|||||||
if not (x == y) and abs(x - y) > delta:
|
if not (x == y) and abs(x - y) > delta:
|
||||||
return
|
return
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = '%r == %r within %r delta' % (x, y, delta)
|
msg = "%r == %r within %r delta" % (x, y, delta)
|
||||||
else:
|
else:
|
||||||
if places is None:
|
if places is None:
|
||||||
places = 7
|
places = 7
|
||||||
if not (x == y) and round(abs(y-x), places) != 0:
|
if not (x == y) and round(abs(y - x), places) != 0:
|
||||||
return
|
return
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = '%r == %r within %r places' % (x, y, places)
|
msg = "%r == %r within %r places" % (x, y, places)
|
||||||
|
|
||||||
assert False, msg
|
assert False, msg
|
||||||
|
|
||||||
def assertIs(self, x, y, msg=''):
|
def assertIs(self, x, y, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "%r is not %r" % (x, y)
|
msg = "%r is not %r" % (x, y)
|
||||||
assert x is y, msg
|
assert x is y, msg
|
||||||
|
|
||||||
def assertIsNot(self, x, y, msg=''):
|
def assertIsNot(self, x, y, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "%r is %r" % (x, y)
|
msg = "%r is %r" % (x, y)
|
||||||
assert x is not y, msg
|
assert x is not y, msg
|
||||||
|
|
||||||
def assertIsNone(self, x, msg=''):
|
def assertIsNone(self, x, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "%r is not None" % x
|
msg = "%r is not None" % x
|
||||||
assert x is None, msg
|
assert x is None, msg
|
||||||
|
|
||||||
def assertIsNotNone(self, x, msg=''):
|
def assertIsNotNone(self, x, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "%r is None" % x
|
msg = "%r is None" % x
|
||||||
assert x is not None, msg
|
assert x is not None, msg
|
||||||
|
|
||||||
def assertTrue(self, x, msg=''):
|
def assertTrue(self, x, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "Expected %r to be True" % x
|
msg = "Expected %r to be True" % x
|
||||||
assert x, msg
|
assert x, msg
|
||||||
|
|
||||||
def assertFalse(self, x, msg=''):
|
def assertFalse(self, x, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "Expected %r to be False" % x
|
msg = "Expected %r to be False" % x
|
||||||
assert not x, msg
|
assert not x, msg
|
||||||
|
|
||||||
def assertIn(self, x, y, msg=''):
|
def assertIn(self, x, y, msg=""):
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "Expected %r to be in %r" % (x, y)
|
msg = "Expected %r to be in %r" % (x, y)
|
||||||
assert x in y, msg
|
assert x in y, msg
|
||||||
|
|
||||||
def assertIsInstance(self, x, y, msg=''):
|
def assertIsInstance(self, x, y, msg=""):
|
||||||
assert isinstance(x, y), msg
|
assert isinstance(x, y), msg
|
||||||
|
|
||||||
def assertRaises(self, exc, func=None, *args, **kwargs):
|
def assertRaises(self, exc, func=None, *args, **kwargs):
|
||||||
@@ -120,12 +195,15 @@ class TestCase:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
func(*args, **kwargs)
|
func(*args, **kwargs)
|
||||||
assert False, "%r not raised" % exc
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if isinstance(e, exc):
|
if isinstance(e, exc):
|
||||||
return
|
return
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
assert False, "%r not raised" % exc
|
||||||
|
|
||||||
|
def assertWarns(self, warn):
|
||||||
|
return NullContext()
|
||||||
|
|
||||||
|
|
||||||
def skip(msg):
|
def skip(msg):
|
||||||
@@ -133,92 +211,252 @@ def skip(msg):
|
|||||||
# We just replace original fun with _inner
|
# We just replace original fun with _inner
|
||||||
def _inner(self):
|
def _inner(self):
|
||||||
raise SkipTest(msg)
|
raise SkipTest(msg)
|
||||||
|
|
||||||
return _inner
|
return _inner
|
||||||
|
|
||||||
return _decor
|
return _decor
|
||||||
|
|
||||||
|
|
||||||
def skipIf(cond, msg):
|
def skipIf(cond, msg):
|
||||||
if not cond:
|
if not cond:
|
||||||
return lambda x: x
|
return lambda x: x
|
||||||
return skip(msg)
|
return skip(msg)
|
||||||
|
|
||||||
|
|
||||||
def skipUnless(cond, msg):
|
def skipUnless(cond, msg):
|
||||||
if cond:
|
if cond:
|
||||||
return lambda x: x
|
return lambda x: x
|
||||||
return skip(msg)
|
return skip(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def expectedFailure(test):
|
||||||
|
def test_exp_fail(*args, **kwargs):
|
||||||
|
try:
|
||||||
|
test(*args, **kwargs)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
assert False, "unexpected success"
|
||||||
|
|
||||||
|
return test_exp_fail
|
||||||
|
|
||||||
|
|
||||||
class TestSuite:
|
class TestSuite:
|
||||||
def __init__(self):
|
def __init__(self, name=""):
|
||||||
self.tests = []
|
self._tests = []
|
||||||
|
self.name = name
|
||||||
|
|
||||||
def addTest(self, cls):
|
def addTest(self, cls):
|
||||||
self.tests.append(cls)
|
self._tests.append(cls)
|
||||||
|
|
||||||
|
def run(self, result):
|
||||||
|
for c in self._tests:
|
||||||
|
_run_suite(c, result, self.name)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _load_module(self, mod):
|
||||||
|
for tn in dir(mod):
|
||||||
|
c = getattr(mod, tn)
|
||||||
|
if isinstance(c, object) and isinstance(c, type) and issubclass(c, TestCase):
|
||||||
|
self.addTest(c)
|
||||||
|
elif tn.startswith("test") and callable(c):
|
||||||
|
self.addTest(c)
|
||||||
|
|
||||||
|
|
||||||
class TestRunner:
|
class TestRunner:
|
||||||
def run(self, suite):
|
def run(self, suite: TestSuite):
|
||||||
res = TestResult()
|
res = TestResult()
|
||||||
for c in suite.tests:
|
suite.run(res)
|
||||||
run_class(c, res)
|
|
||||||
|
|
||||||
|
res.printErrors()
|
||||||
|
print("----------------------------------------------------------------------")
|
||||||
print("Ran %d tests\n" % res.testsRun)
|
print("Ran %d tests\n" % res.testsRun)
|
||||||
if res.failuresNum > 0 or res.errorsNum > 0:
|
if res.failuresNum > 0 or res.errorsNum > 0:
|
||||||
print("FAILED (failures=%d, errors=%d)" % (res.failuresNum, res.errorsNum))
|
print("FAILED (failures=%d, errors=%d)" % (res.failuresNum, res.errorsNum))
|
||||||
else:
|
else:
|
||||||
msg = "OK"
|
msg = "OK"
|
||||||
if res.skippedNum > 0:
|
if res.skippedNum > 0:
|
||||||
msg += " (%d skipped)" % res.skippedNum
|
msg += " (skipped=%d)" % res.skippedNum
|
||||||
print(msg)
|
print(msg)
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
TextTestRunner = TestRunner
|
||||||
|
|
||||||
|
|
||||||
class TestResult:
|
class TestResult:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.errorsNum = 0
|
self.errorsNum = 0
|
||||||
self.failuresNum = 0
|
self.failuresNum = 0
|
||||||
self.skippedNum = 0
|
self.skippedNum = 0
|
||||||
self.testsRun = 0
|
self.testsRun = 0
|
||||||
|
self.errors = []
|
||||||
|
self.failures = []
|
||||||
|
self.skipped = []
|
||||||
|
self._newFailures = 0
|
||||||
|
|
||||||
def wasSuccessful(self):
|
def wasSuccessful(self):
|
||||||
return self.errorsNum == 0 and self.failuresNum == 0
|
return self.errorsNum == 0 and self.failuresNum == 0
|
||||||
|
|
||||||
# TODO: Uncompliant
|
def printErrors(self):
|
||||||
def run_class(c, test_result):
|
print()
|
||||||
o = c()
|
self.printErrorList(self.errors)
|
||||||
|
self.printErrorList(self.failures)
|
||||||
|
|
||||||
|
def printErrorList(self, lst):
|
||||||
|
sep = "----------------------------------------------------------------------"
|
||||||
|
for c, e in lst:
|
||||||
|
detail = " ".join((str(i) for i in c))
|
||||||
|
print("======================================================================")
|
||||||
|
print(f"FAIL: {detail}")
|
||||||
|
print(sep)
|
||||||
|
print(e)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
# Format is compatible with CPython.
|
||||||
|
return "<unittest.result.TestResult run=%d errors=%d failures=%d>" % (
|
||||||
|
self.testsRun,
|
||||||
|
self.errorsNum,
|
||||||
|
self.failuresNum,
|
||||||
|
)
|
||||||
|
|
||||||
|
def __add__(self, other):
|
||||||
|
self.errorsNum += other.errorsNum
|
||||||
|
self.failuresNum += other.failuresNum
|
||||||
|
self.skippedNum += other.skippedNum
|
||||||
|
self.testsRun += other.testsRun
|
||||||
|
self.errors.extend(other.errors)
|
||||||
|
self.failures.extend(other.failures)
|
||||||
|
self.skipped.extend(other.skipped)
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
def _capture_exc(exc, exc_traceback):
|
||||||
|
buf = io.StringIO()
|
||||||
|
if hasattr(sys, "print_exception"):
|
||||||
|
sys.print_exception(exc, buf)
|
||||||
|
elif traceback is not None:
|
||||||
|
traceback.print_exception(None, exc, exc_traceback, file=buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_test_exception(
|
||||||
|
current_test: tuple, test_result: TestResult, exc_info: tuple, verbose=True
|
||||||
|
):
|
||||||
|
exc = exc_info[1]
|
||||||
|
traceback = exc_info[2]
|
||||||
|
ex_str = _capture_exc(exc, traceback)
|
||||||
|
if isinstance(exc, AssertionError):
|
||||||
|
test_result.failuresNum += 1
|
||||||
|
test_result.failures.append((current_test, ex_str))
|
||||||
|
if verbose:
|
||||||
|
print(" FAIL")
|
||||||
|
else:
|
||||||
|
test_result.errorsNum += 1
|
||||||
|
test_result.errors.append((current_test, ex_str))
|
||||||
|
if verbose:
|
||||||
|
print(" ERROR")
|
||||||
|
test_result._newFailures += 1
|
||||||
|
|
||||||
|
|
||||||
|
def _run_suite(c, test_result: TestResult, suite_name=""):
|
||||||
|
if isinstance(c, TestSuite):
|
||||||
|
c.run(test_result)
|
||||||
|
return
|
||||||
|
|
||||||
|
if isinstance(c, type):
|
||||||
|
o = c()
|
||||||
|
else:
|
||||||
|
o = c
|
||||||
|
set_up_class = getattr(o, "setUpClass", lambda: None)
|
||||||
|
tear_down_class = getattr(o, "tearDownClass", lambda: None)
|
||||||
set_up = getattr(o, "setUp", lambda: None)
|
set_up = getattr(o, "setUp", lambda: None)
|
||||||
tear_down = getattr(o, "tearDown", lambda: None)
|
tear_down = getattr(o, "tearDown", lambda: None)
|
||||||
for name in dir(o):
|
exceptions = []
|
||||||
if name.startswith("test"):
|
try:
|
||||||
print("%s (%s) ..." % (name, c.__qualname__), end="")
|
suite_name += "." + c.__qualname__
|
||||||
m = getattr(o, name)
|
except AttributeError:
|
||||||
set_up()
|
pass
|
||||||
try:
|
|
||||||
test_result.testsRun += 1
|
def run_one(test_function):
|
||||||
m()
|
global __test_result__, __current_test__
|
||||||
print(" ok")
|
print("%s (%s) ..." % (name, suite_name), end="")
|
||||||
except SkipTest as e:
|
set_up()
|
||||||
print(" skipped:", e.args[0])
|
__test_result__ = test_result
|
||||||
test_result.skippedNum += 1
|
test_container = f"({suite_name})"
|
||||||
except:
|
__current_test__ = (name, test_container)
|
||||||
|
try:
|
||||||
|
test_result._newFailures = 0
|
||||||
|
test_result.testsRun += 1
|
||||||
|
test_function()
|
||||||
|
# No exception occurred, test passed
|
||||||
|
if test_result._newFailures:
|
||||||
print(" FAIL")
|
print(" FAIL")
|
||||||
test_result.failuresNum += 1
|
else:
|
||||||
# Uncomment to investigate failure in detail
|
print(" ok")
|
||||||
#raise
|
except SkipTest as e:
|
||||||
continue
|
reason = e.args[0]
|
||||||
finally:
|
print(" skipped:", reason)
|
||||||
tear_down()
|
test_result.skippedNum += 1
|
||||||
|
test_result.skipped.append((name, c, reason))
|
||||||
|
except Exception as ex:
|
||||||
|
_handle_test_exception(
|
||||||
|
current_test=(name, c), test_result=test_result, exc_info=(type(ex), ex, None)
|
||||||
|
)
|
||||||
|
# Uncomment to investigate failure in detail
|
||||||
|
# raise
|
||||||
|
finally:
|
||||||
|
__test_result__ = None
|
||||||
|
__current_test__ = None
|
||||||
|
tear_down()
|
||||||
|
try:
|
||||||
|
o.doCleanups()
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
set_up_class()
|
||||||
|
try:
|
||||||
|
if hasattr(o, "runTest"):
|
||||||
|
name = str(o)
|
||||||
|
run_one(o.runTest)
|
||||||
|
return
|
||||||
|
|
||||||
|
for name in dir(o):
|
||||||
|
if name.startswith("test"):
|
||||||
|
m = getattr(o, name)
|
||||||
|
if not callable(m):
|
||||||
|
continue
|
||||||
|
run_one(m)
|
||||||
|
|
||||||
|
if callable(o):
|
||||||
|
name = o.__name__
|
||||||
|
run_one(o)
|
||||||
|
finally:
|
||||||
|
tear_down_class()
|
||||||
|
|
||||||
|
return exceptions
|
||||||
|
|
||||||
|
|
||||||
def main(module="__main__"):
|
# This supports either:
|
||||||
def test_cases(m):
|
#
|
||||||
for tn in dir(m):
|
# >>> import mytest
|
||||||
c = getattr(m, tn)
|
# >>> unitttest.main(mytest)
|
||||||
if isinstance(c, object) and isinstance(c, type) and issubclass(c, TestCase):
|
#
|
||||||
yield c
|
# >>> unittest.main("mytest")
|
||||||
|
#
|
||||||
|
# Or, a script that ends with:
|
||||||
|
# if __name__ == "__main__":
|
||||||
|
# unittest.main()
|
||||||
|
# e.g. run via `mpremote run mytest.py`
|
||||||
|
def main(module="__main__", testRunner=None):
|
||||||
|
if testRunner is None:
|
||||||
|
testRunner = TestRunner()
|
||||||
|
elif isinstance(testRunner, type):
|
||||||
|
testRunner = testRunner()
|
||||||
|
|
||||||
m = __import__(module)
|
if isinstance(module, str):
|
||||||
suite = TestSuite()
|
module = __import__(module)
|
||||||
for c in test_cases(m):
|
suite = TestSuite(module.__name__)
|
||||||
suite.addTest(c)
|
suite._load_module(module)
|
||||||
runner = TestRunner()
|
return testRunner.run(suite)
|
||||||
result = runner.run(suite)
|
|
||||||
# Terminate with non zero return code in case of failures
|
|
||||||
sys.exit(result.failuresNum > 0)
|
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
def warn(msg, cat=None, stacklevel=1):
|
|
||||||
print("%s: %s" % ("Warning" if cat is None else cat.__name__, msg))
|
|
||||||
31
setup.cfg
@@ -1,6 +1,6 @@
|
|||||||
[metadata]
|
[metadata]
|
||||||
name = microdot
|
name = microdot
|
||||||
version = 1.0.0
|
version = 1.2.3
|
||||||
author = Miguel Grinberg
|
author = Miguel Grinberg
|
||||||
author_email = miguel.grinberg@gmail.com
|
author_email = miguel.grinberg@gmail.com
|
||||||
description = The impossibly small web framework for MicroPython
|
description = The impossibly small web framework for MicroPython
|
||||||
@@ -22,13 +22,22 @@ zip_safe = False
|
|||||||
include_package_data = True
|
include_package_data = True
|
||||||
package_dir =
|
package_dir =
|
||||||
= src
|
= src
|
||||||
py_modules =
|
packages = find:
|
||||||
microdot
|
|
||||||
microdot_asyncio
|
[options.packages.find]
|
||||||
microdot_utemplate
|
where = src
|
||||||
microdot_jinja
|
|
||||||
microdot_session
|
#py_modules =
|
||||||
microdot_test_client
|
# microdot
|
||||||
microdot_asyncio_test_client
|
# microdot_asyncio
|
||||||
microdot_wsgi
|
# microdot_utemplate
|
||||||
microdot_asgi
|
# microdot_jinja
|
||||||
|
# microdot_session
|
||||||
|
# microdot_websocket
|
||||||
|
# microdot_websocket_alt
|
||||||
|
# microdot_asyncio_websocket
|
||||||
|
# microdot_test_client
|
||||||
|
# microdot_asyncio_test_client
|
||||||
|
# microdot_wsgi
|
||||||
|
# microdot_asgi
|
||||||
|
# microdot_asgi_websocket
|
||||||
|
|||||||
293
src/microdot.py
@@ -43,20 +43,29 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
socket_timeout_error = OSError
|
||||||
try:
|
try:
|
||||||
import usocket as socket
|
import usocket as socket
|
||||||
except ImportError:
|
except ImportError:
|
||||||
try:
|
try:
|
||||||
import socket
|
import socket
|
||||||
|
socket_timeout_error = socket.timeout
|
||||||
except ImportError: # pragma: no cover
|
except ImportError: # pragma: no cover
|
||||||
socket = None
|
socket = None
|
||||||
|
|
||||||
|
MUTED_SOCKET_ERRORS = [
|
||||||
|
32, # Broken pipe
|
||||||
|
54, # Connection reset by peer
|
||||||
|
104, # Connection reset by peer
|
||||||
|
128, # Operation on closed socket
|
||||||
|
]
|
||||||
|
|
||||||
def urldecode(string):
|
|
||||||
string = string.replace('+', ' ')
|
def urldecode_str(s):
|
||||||
parts = string.split('%')
|
s = s.replace('+', ' ')
|
||||||
|
parts = s.split('%')
|
||||||
if len(parts) == 1:
|
if len(parts) == 1:
|
||||||
return string
|
return s
|
||||||
result = [parts[0]]
|
result = [parts[0]]
|
||||||
for item in parts[1:]:
|
for item in parts[1:]:
|
||||||
if item == '':
|
if item == '':
|
||||||
@@ -68,6 +77,109 @@ def urldecode(string):
|
|||||||
return ''.join(result)
|
return ''.join(result)
|
||||||
|
|
||||||
|
|
||||||
|
def urldecode_bytes(s):
|
||||||
|
s = s.replace(b'+', b' ')
|
||||||
|
parts = s.split(b'%')
|
||||||
|
if len(parts) == 1:
|
||||||
|
return s.decode()
|
||||||
|
result = [parts[0]]
|
||||||
|
for item in parts[1:]:
|
||||||
|
if item == b'':
|
||||||
|
result.append(b'%')
|
||||||
|
else:
|
||||||
|
code = item[:2]
|
||||||
|
result.append(bytes([int(code, 16)]))
|
||||||
|
result.append(item[2:])
|
||||||
|
return b''.join(result).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def urlencode(s):
|
||||||
|
return s.replace('+', '%2B').replace(' ', '+').replace(
|
||||||
|
'%', '%25').replace('?', '%3F').replace('#', '%23').replace(
|
||||||
|
'&', '%26').replace('=', '%3D')
|
||||||
|
|
||||||
|
|
||||||
|
class NoCaseDict(dict):
|
||||||
|
"""A subclass of dictionary that holds case-insensitive keys.
|
||||||
|
|
||||||
|
:param initial_dict: an initial dictionary of key/value pairs to
|
||||||
|
initialize this object with.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
>>> d = NoCaseDict()
|
||||||
|
>>> d['Content-Type'] = 'text/html'
|
||||||
|
>>> print(d['Content-Type'])
|
||||||
|
text/html
|
||||||
|
>>> print(d['content-type'])
|
||||||
|
text/html
|
||||||
|
>>> print(d['CONTENT-TYPE'])
|
||||||
|
text/html
|
||||||
|
>>> del d['cOnTeNt-TyPe']
|
||||||
|
>>> print(d)
|
||||||
|
{}
|
||||||
|
"""
|
||||||
|
def __init__(self, initial_dict=None):
|
||||||
|
super().__init__(initial_dict or {})
|
||||||
|
self.keymap = {k.lower(): k for k in self.keys() if k.lower() != k}
|
||||||
|
|
||||||
|
def __setitem__(self, key, value):
|
||||||
|
kl = key.lower()
|
||||||
|
key = self.keymap.get(kl, key)
|
||||||
|
if kl != key:
|
||||||
|
self.keymap[kl] = key
|
||||||
|
super().__setitem__(key, value)
|
||||||
|
|
||||||
|
def __getitem__(self, key):
|
||||||
|
kl = key.lower()
|
||||||
|
return super().__getitem__(self.keymap.get(kl, kl))
|
||||||
|
|
||||||
|
def __delitem__(self, key):
|
||||||
|
kl = key.lower()
|
||||||
|
super().__delitem__(self.keymap.get(kl, kl))
|
||||||
|
|
||||||
|
def __contains__(self, key):
|
||||||
|
kl = key.lower()
|
||||||
|
return self.keymap.get(kl, kl) in self.keys()
|
||||||
|
|
||||||
|
def get(self, key, default=None):
|
||||||
|
kl = key.lower()
|
||||||
|
return super().get(self.keymap.get(kl, kl), default)
|
||||||
|
|
||||||
|
|
||||||
|
def mro(cls): # pragma: no cover
|
||||||
|
"""Return the method resolution order of a class.
|
||||||
|
|
||||||
|
This is a helper function that returns the method resolution order of a
|
||||||
|
class. It is used by Microdot to find the best error handler to invoke for
|
||||||
|
the raised exception.
|
||||||
|
|
||||||
|
In CPython, this function returns the ``__mro__`` attribute of the class.
|
||||||
|
In MicroPython, this function implements a recursive depth-first scanning
|
||||||
|
of the class hierarchy.
|
||||||
|
"""
|
||||||
|
if hasattr(cls, 'mro'):
|
||||||
|
return cls.__mro__
|
||||||
|
|
||||||
|
def _mro(cls):
|
||||||
|
m = [cls]
|
||||||
|
for base in cls.__bases__:
|
||||||
|
m += _mro(base)
|
||||||
|
return m
|
||||||
|
|
||||||
|
mro_list = _mro(cls)
|
||||||
|
|
||||||
|
# If a class appears multiple times (due to multiple inheritance) remove
|
||||||
|
# all but the last occurence. This matches the method resolution order
|
||||||
|
# of MicroPython, but not CPython.
|
||||||
|
mro_pruned = []
|
||||||
|
for i in range(len(mro_list)):
|
||||||
|
base = mro_list.pop(0)
|
||||||
|
if base not in mro_list:
|
||||||
|
mro_pruned.append(base)
|
||||||
|
return mro_pruned
|
||||||
|
|
||||||
|
|
||||||
class MultiDict(dict):
|
class MultiDict(dict):
|
||||||
"""A subclass of dictionary that can hold multiple values for the same
|
"""A subclass of dictionary that can hold multiple values for the same
|
||||||
key. It is used to hold key/value pairs decoded from query strings and
|
key. It is used to hold key/value pairs decoded from query strings and
|
||||||
@@ -190,17 +302,24 @@ class Request():
|
|||||||
#: Request.max_readline = 16 * 1024 # 16KB lines allowed
|
#: Request.max_readline = 16 * 1024 # 16KB lines allowed
|
||||||
max_readline = 2 * 1024
|
max_readline = 2 * 1024
|
||||||
|
|
||||||
|
#: Specify a suggested read timeout to use when reading the request. Set to
|
||||||
|
#: 0 to disable the use of a timeout. This timeout should be considered a
|
||||||
|
#: suggestion only, as some platforms may not support it.
|
||||||
|
socket_read_timeout = 0.1
|
||||||
|
|
||||||
class G:
|
class G:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def __init__(self, app, client_addr, method, url, http_version, headers,
|
def __init__(self, app, client_addr, method, url, http_version, headers,
|
||||||
body=None, stream=None):
|
body=None, stream=None, sock=None):
|
||||||
#: The application instance to which this request belongs.
|
#: The application instance to which this request belongs.
|
||||||
self.app = app
|
self.app = app
|
||||||
#: The address of the client, as a tuple (host, port).
|
#: The address of the client, as a tuple (host, port).
|
||||||
self.client_addr = client_addr
|
self.client_addr = client_addr
|
||||||
#: The HTTP method of the request.
|
#: The HTTP method of the request.
|
||||||
self.method = method
|
self.method = method
|
||||||
|
#: The request URL, including the path and query string.
|
||||||
|
self.url = url
|
||||||
#: The path portion of the URL.
|
#: The path portion of the URL.
|
||||||
self.path = url
|
self.path = url
|
||||||
#: The query string portion of the URL.
|
#: The query string portion of the URL.
|
||||||
@@ -225,33 +344,34 @@ class Request():
|
|||||||
self.path, self.query_string = self.path.split('?', 1)
|
self.path, self.query_string = self.path.split('?', 1)
|
||||||
self.args = self._parse_urlencoded(self.query_string)
|
self.args = self._parse_urlencoded(self.query_string)
|
||||||
|
|
||||||
for header, value in self.headers.items():
|
if 'Content-Length' in self.headers:
|
||||||
header = header.lower()
|
self.content_length = int(self.headers['Content-Length'])
|
||||||
if header == 'content-length':
|
if 'Content-Type' in self.headers:
|
||||||
self.content_length = int(value)
|
self.content_type = self.headers['Content-Type']
|
||||||
elif header == 'content-type':
|
if 'Cookie' in self.headers:
|
||||||
self.content_type = value
|
for cookie in self.headers['Cookie'].split(';'):
|
||||||
elif header == 'cookie':
|
name, value = cookie.strip().split('=', 1)
|
||||||
for cookie in value.split(';'):
|
self.cookies[name] = value
|
||||||
name, value = cookie.strip().split('=', 1)
|
|
||||||
self.cookies[name] = value
|
|
||||||
|
|
||||||
self._body = body
|
self._body = body
|
||||||
self.body_used = False
|
self.body_used = False
|
||||||
self._stream = stream
|
self._stream = stream
|
||||||
self.stream_used = False
|
self.stream_used = False
|
||||||
|
self.sock = sock
|
||||||
self._json = None
|
self._json = None
|
||||||
self._form = None
|
self._form = None
|
||||||
self.after_request_handlers = []
|
self.after_request_handlers = []
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create(app, client_stream, client_addr):
|
def create(app, client_stream, client_addr, client_sock=None):
|
||||||
"""Create a request object.
|
"""Create a request object.
|
||||||
|
|
||||||
|
|
||||||
:param app: The Microdot application instance.
|
:param app: The Microdot application instance.
|
||||||
:param client_stream: An input stream from where the request data can
|
:param client_stream: An input stream from where the request data can
|
||||||
be read.
|
be read.
|
||||||
:param client_addr: The address of the client, as a tuple.
|
:param client_addr: The address of the client, as a tuple.
|
||||||
|
:param client_sock: The low-level socket associated with the request.
|
||||||
|
|
||||||
This method returns a newly created ``Request`` object.
|
This method returns a newly created ``Request`` object.
|
||||||
"""
|
"""
|
||||||
@@ -263,7 +383,7 @@ class Request():
|
|||||||
http_version = http_version.split('/', 1)[1]
|
http_version = http_version.split('/', 1)[1]
|
||||||
|
|
||||||
# headers
|
# headers
|
||||||
headers = {}
|
headers = NoCaseDict()
|
||||||
while True:
|
while True:
|
||||||
line = Request._safe_readline(client_stream).strip().decode()
|
line = Request._safe_readline(client_stream).strip().decode()
|
||||||
if line == '':
|
if line == '':
|
||||||
@@ -273,13 +393,19 @@ class Request():
|
|||||||
headers[header] = value
|
headers[header] = value
|
||||||
|
|
||||||
return Request(app, client_addr, method, url, http_version, headers,
|
return Request(app, client_addr, method, url, http_version, headers,
|
||||||
stream=client_stream)
|
stream=client_stream, sock=client_sock)
|
||||||
|
|
||||||
def _parse_urlencoded(self, urlencoded):
|
def _parse_urlencoded(self, urlencoded):
|
||||||
data = MultiDict()
|
data = MultiDict()
|
||||||
if urlencoded:
|
if len(urlencoded) > 0:
|
||||||
for k, v in [pair.split('=', 1) for pair in urlencoded.split('&')]:
|
if isinstance(urlencoded, str):
|
||||||
data[urldecode(k)] = urldecode(v)
|
for k, v in [pair.split('=', 1)
|
||||||
|
for pair in urlencoded.split('&')]:
|
||||||
|
data[urldecode_str(k)] = urldecode_str(v)
|
||||||
|
elif isinstance(urlencoded, bytes): # pragma: no branch
|
||||||
|
for k, v in [pair.split(b'=', 1)
|
||||||
|
for pair in urlencoded.split(b'&')]:
|
||||||
|
data[urldecode_bytes(k)] = urldecode_bytes(v)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -332,7 +458,7 @@ class Request():
|
|||||||
mime_type = self.content_type.split(';')[0]
|
mime_type = self.content_type.split(';')[0]
|
||||||
if mime_type != 'application/x-www-form-urlencoded':
|
if mime_type != 'application/x-www-form-urlencoded':
|
||||||
return None
|
return None
|
||||||
self._form = self._parse_urlencoded(self.body.decode())
|
self._form = self._parse_urlencoded(self.body)
|
||||||
return self._form
|
return self._form
|
||||||
|
|
||||||
def after_request(self, f):
|
def after_request(self, f):
|
||||||
@@ -353,6 +479,9 @@ class Request():
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
return 'Hello, World!'
|
return 'Hello, World!'
|
||||||
|
|
||||||
|
Note that the function is not called if the request handler raises an
|
||||||
|
exception and an error response is returned instead.
|
||||||
"""
|
"""
|
||||||
self.after_request_handlers.append(f)
|
self.after_request_handlers.append(f)
|
||||||
return f
|
return f
|
||||||
@@ -396,16 +525,20 @@ class Response():
|
|||||||
#: ``Content-Type`` header.
|
#: ``Content-Type`` header.
|
||||||
default_content_type = 'text/plain'
|
default_content_type = 'text/plain'
|
||||||
|
|
||||||
|
#: Special response used to signal that a response does not need to be
|
||||||
|
#: written to the client. Used to exit WebSocket connections cleanly.
|
||||||
|
already_handled = None
|
||||||
|
|
||||||
def __init__(self, body='', status_code=200, headers=None, reason=None):
|
def __init__(self, body='', status_code=200, headers=None, reason=None):
|
||||||
if body is None and status_code == 200:
|
if body is None and status_code == 200:
|
||||||
body = ''
|
body = ''
|
||||||
status_code = 204
|
status_code = 204
|
||||||
self.status_code = status_code
|
self.status_code = status_code
|
||||||
self.headers = headers.copy() if headers else {}
|
self.headers = NoCaseDict(headers or {})
|
||||||
self.reason = reason
|
self.reason = reason
|
||||||
if isinstance(body, (dict, list)):
|
if isinstance(body, (dict, list)):
|
||||||
self.body = json.dumps(body).encode()
|
self.body = json.dumps(body).encode()
|
||||||
self.headers['Content-Type'] = 'application/json'
|
self.headers['Content-Type'] = 'application/json; charset=UTF-8'
|
||||||
elif isinstance(body, str):
|
elif isinstance(body, str):
|
||||||
self.body = body.encode()
|
self.body = body.encode()
|
||||||
else:
|
else:
|
||||||
@@ -454,6 +587,8 @@ class Response():
|
|||||||
self.headers['Content-Length'] = str(len(self.body))
|
self.headers['Content-Length'] = str(len(self.body))
|
||||||
if 'Content-Type' not in self.headers:
|
if 'Content-Type' not in self.headers:
|
||||||
self.headers['Content-Type'] = self.default_content_type
|
self.headers['Content-Type'] = self.default_content_type
|
||||||
|
if 'charset=' not in self.headers['Content-Type']:
|
||||||
|
self.headers['Content-Type'] += '; charset=UTF-8'
|
||||||
|
|
||||||
def write(self, stream):
|
def write(self, stream):
|
||||||
self.complete()
|
self.complete()
|
||||||
@@ -482,7 +617,7 @@ class Response():
|
|||||||
if can_flush: # pragma: no cover
|
if can_flush: # pragma: no cover
|
||||||
stream.flush()
|
stream.flush()
|
||||||
except OSError as exc: # pragma: no cover
|
except OSError as exc: # pragma: no cover
|
||||||
if exc.errno == 32: # errno.EPIPE
|
if exc.errno in MUTED_SOCKET_ERRORS:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
@@ -594,6 +729,15 @@ class URLPattern():
|
|||||||
return args
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
class HTTPException(Exception):
|
||||||
|
def __init__(self, status_code, reason=None):
|
||||||
|
self.status_code = status_code
|
||||||
|
self.reason = reason or str(status_code) + ' error'
|
||||||
|
|
||||||
|
def __repr__(self): # pragma: no cover
|
||||||
|
return 'HTTPException: {}'.format(self.status_code)
|
||||||
|
|
||||||
|
|
||||||
class Microdot():
|
class Microdot():
|
||||||
"""An HTTP application class.
|
"""An HTTP application class.
|
||||||
|
|
||||||
@@ -612,6 +756,7 @@ class Microdot():
|
|||||||
self.url_map = []
|
self.url_map = []
|
||||||
self.before_request_handlers = []
|
self.before_request_handlers = []
|
||||||
self.after_request_handlers = []
|
self.after_request_handlers = []
|
||||||
|
self.after_error_request_handlers = []
|
||||||
self.error_handlers = {}
|
self.error_handlers = {}
|
||||||
self.shutdown_requested = False
|
self.shutdown_requested = False
|
||||||
self.debug = False
|
self.debug = False
|
||||||
@@ -773,6 +918,24 @@ class Microdot():
|
|||||||
self.after_request_handlers.append(f)
|
self.after_request_handlers.append(f)
|
||||||
return f
|
return f
|
||||||
|
|
||||||
|
def after_error_request(self, f):
|
||||||
|
"""Decorator to register a function to run after an error response is
|
||||||
|
generated. The decorated function must take two arguments, the request
|
||||||
|
and response objects. The return value of the function must be an
|
||||||
|
updated response object. The handler is invoked for error responses
|
||||||
|
generated by Microdot, as well as those returned by application-defined
|
||||||
|
error handlers.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
@app.after_error_request
|
||||||
|
def func(request, response):
|
||||||
|
# ...
|
||||||
|
return response
|
||||||
|
"""
|
||||||
|
self.after_error_request_handlers.append(f)
|
||||||
|
return f
|
||||||
|
|
||||||
def errorhandler(self, status_code_or_exception_class):
|
def errorhandler(self, status_code_or_exception_class):
|
||||||
"""Decorator to register a function as an error handler. Error handler
|
"""Decorator to register a function as an error handler. Error handler
|
||||||
functions for numeric HTTP status codes must accept a single argument,
|
functions for numeric HTTP status codes must accept a single argument,
|
||||||
@@ -813,10 +976,34 @@ class Microdot():
|
|||||||
self.before_request_handlers.append(handler)
|
self.before_request_handlers.append(handler)
|
||||||
for handler in subapp.after_request_handlers:
|
for handler in subapp.after_request_handlers:
|
||||||
self.after_request_handlers.append(handler)
|
self.after_request_handlers.append(handler)
|
||||||
|
for handler in subapp.after_error_request_handlers:
|
||||||
|
self.after_error_request_handlers.append(handler)
|
||||||
for status_code, handler in subapp.error_handlers.items():
|
for status_code, handler in subapp.error_handlers.items():
|
||||||
self.error_handlers[status_code] = handler
|
self.error_handlers[status_code] = handler
|
||||||
|
|
||||||
def run(self, host='0.0.0.0', port=5000, debug=False):
|
@staticmethod
|
||||||
|
def abort(status_code, reason=None):
|
||||||
|
"""Abort the current request and return an error response with the
|
||||||
|
given status code.
|
||||||
|
|
||||||
|
:param status_code: The numeric status code of the response.
|
||||||
|
:param reason: The reason for the response, which is included in the
|
||||||
|
response body.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
from microdot import abort
|
||||||
|
|
||||||
|
@app.route('/users/<int:id>')
|
||||||
|
def get_user(id):
|
||||||
|
user = get_user_by_id(id)
|
||||||
|
if user is None:
|
||||||
|
abort(404)
|
||||||
|
return user.to_dict()
|
||||||
|
"""
|
||||||
|
raise HTTPException(status_code, reason)
|
||||||
|
|
||||||
|
def run(self, host='0.0.0.0', port=5000, debug=False, ssl=None):
|
||||||
"""Start the web server. This function does not normally return, as
|
"""Start the web server. This function does not normally return, as
|
||||||
the server enters an endless listening loop. The :func:`shutdown`
|
the server enters an endless listening loop. The :func:`shutdown`
|
||||||
function provides a method for terminating the server gracefully.
|
function provides a method for terminating the server gracefully.
|
||||||
@@ -832,6 +1019,8 @@ class Microdot():
|
|||||||
port 5000.
|
port 5000.
|
||||||
:param debug: If ``True``, the server logs debugging information. The
|
:param debug: If ``True``, the server logs debugging information. The
|
||||||
default is ``False``.
|
default is ``False``.
|
||||||
|
:param ssl: An ``SSLContext`` instance or ``None`` if the server should
|
||||||
|
not use TLS. The default is ``None``.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
@@ -859,6 +1048,9 @@ class Microdot():
|
|||||||
self.server.bind(addr)
|
self.server.bind(addr)
|
||||||
self.server.listen(5)
|
self.server.listen(5)
|
||||||
|
|
||||||
|
if ssl:
|
||||||
|
self.server = ssl.wrap_socket(self.server, server_side=True)
|
||||||
|
|
||||||
while not self.shutdown_requested:
|
while not self.shutdown_requested:
|
||||||
try:
|
try:
|
||||||
sock, addr = self.server.accept()
|
sock, addr = self.server.accept()
|
||||||
@@ -866,8 +1058,11 @@ class Microdot():
|
|||||||
if exc.errno == errno.ECONNABORTED:
|
if exc.errno == errno.ECONNABORTED:
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
raise
|
print_exception(exc)
|
||||||
create_thread(self.handle_request, sock, addr)
|
except Exception as exc: # pragma: no cover
|
||||||
|
print_exception(exc)
|
||||||
|
else:
|
||||||
|
create_thread(self.handle_request, sock, addr)
|
||||||
|
|
||||||
def shutdown(self):
|
def shutdown(self):
|
||||||
"""Request a server shutdown. The server will then exit its request
|
"""Request a server shutdown. The server will then exit its request
|
||||||
@@ -897,25 +1092,35 @@ class Microdot():
|
|||||||
return f
|
return f
|
||||||
|
|
||||||
def handle_request(self, sock, addr):
|
def handle_request(self, sock, addr):
|
||||||
|
if Request.socket_read_timeout and \
|
||||||
|
hasattr(sock, 'settimeout'): # pragma: no cover
|
||||||
|
sock.settimeout(Request.socket_read_timeout)
|
||||||
if not hasattr(sock, 'readline'): # pragma: no cover
|
if not hasattr(sock, 'readline'): # pragma: no cover
|
||||||
stream = sock.makefile("rwb")
|
stream = sock.makefile("rwb")
|
||||||
else:
|
else:
|
||||||
stream = sock
|
stream = sock
|
||||||
|
|
||||||
req = None
|
req = None
|
||||||
|
res = None
|
||||||
try:
|
try:
|
||||||
req = Request.create(self, stream, addr)
|
req = Request.create(self, stream, addr, sock)
|
||||||
|
res = self.dispatch_request(req)
|
||||||
|
except socket_timeout_error as exc: # pragma: no cover
|
||||||
|
if exc.errno and exc.errno not in [60, 110]:
|
||||||
|
print_exception(exc) # not a timeout
|
||||||
except Exception as exc: # pragma: no cover
|
except Exception as exc: # pragma: no cover
|
||||||
print_exception(exc)
|
print_exception(exc)
|
||||||
res = self.dispatch_request(req)
|
|
||||||
res.write(stream)
|
|
||||||
try:
|
try:
|
||||||
|
if res and res != Response.already_handled: # pragma: no branch
|
||||||
|
res.write(stream)
|
||||||
stream.close()
|
stream.close()
|
||||||
except OSError as exc: # pragma: no cover
|
except OSError as exc: # pragma: no cover
|
||||||
if exc.errno == 32: # errno.EPIPE
|
if exc.errno in MUTED_SOCKET_ERRORS:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise
|
print_exception(exc)
|
||||||
|
except Exception as exc: # pragma: no cover
|
||||||
|
print_exception(exc)
|
||||||
if stream != sock: # pragma: no cover
|
if stream != sock: # pragma: no cover
|
||||||
sock.close()
|
sock.close()
|
||||||
if self.shutdown_requested: # pragma: no cover
|
if self.shutdown_requested: # pragma: no cover
|
||||||
@@ -926,6 +1131,7 @@ class Microdot():
|
|||||||
status_code=res.status_code))
|
status_code=res.status_code))
|
||||||
|
|
||||||
def dispatch_request(self, req):
|
def dispatch_request(self, req):
|
||||||
|
after_request_handled = False
|
||||||
if req:
|
if req:
|
||||||
if req.content_length > req.max_content_length:
|
if req.content_length > req.max_content_length:
|
||||||
if 413 in self.error_handlers:
|
if 413 in self.error_handlers:
|
||||||
@@ -958,16 +1164,30 @@ class Microdot():
|
|||||||
res = handler(req, res) or res
|
res = handler(req, res) or res
|
||||||
for handler in req.after_request_handlers:
|
for handler in req.after_request_handlers:
|
||||||
res = handler(req, res) or res
|
res = handler(req, res) or res
|
||||||
|
after_request_handled = True
|
||||||
elif f in self.error_handlers:
|
elif f in self.error_handlers:
|
||||||
res = self.error_handlers[f](req)
|
res = self.error_handlers[f](req)
|
||||||
else:
|
else:
|
||||||
res = 'Not found', f
|
res = 'Not found', f
|
||||||
|
except HTTPException as exc:
|
||||||
|
if exc.status_code in self.error_handlers:
|
||||||
|
res = self.error_handlers[exc.status_code](req)
|
||||||
|
else:
|
||||||
|
res = exc.reason, exc.status_code
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print_exception(exc)
|
print_exception(exc)
|
||||||
|
exc_class = None
|
||||||
res = None
|
res = None
|
||||||
if exc.__class__ in self.error_handlers:
|
if exc.__class__ in self.error_handlers:
|
||||||
|
exc_class = exc.__class__
|
||||||
|
else:
|
||||||
|
for c in mro(exc.__class__)[1:]:
|
||||||
|
if c in self.error_handlers:
|
||||||
|
exc_class = c
|
||||||
|
break
|
||||||
|
if exc_class:
|
||||||
try:
|
try:
|
||||||
res = self.error_handlers[exc.__class__](req, exc)
|
res = self.error_handlers[exc_class](req, exc)
|
||||||
except Exception as exc2: # pragma: no cover
|
except Exception as exc2: # pragma: no cover
|
||||||
print_exception(exc2)
|
print_exception(exc2)
|
||||||
if res is None:
|
if res is None:
|
||||||
@@ -985,8 +1205,13 @@ class Microdot():
|
|||||||
res = Response(*res)
|
res = Response(*res)
|
||||||
elif not isinstance(res, Response):
|
elif not isinstance(res, Response):
|
||||||
res = Response(res)
|
res = Response(res)
|
||||||
|
if not after_request_handled:
|
||||||
|
for handler in self.after_error_request_handlers:
|
||||||
|
res = handler(req, res) or res
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
abort = Microdot.abort
|
||||||
|
Response.already_handled = Response()
|
||||||
redirect = Response.redirect
|
redirect = Response.redirect
|
||||||
send_file = Response.send_file
|
send_file = Response.send_file
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import signal
|
|||||||
from microdot_asyncio import * # noqa: F401, F403
|
from microdot_asyncio import * # noqa: F401, F403
|
||||||
from microdot_asyncio import Microdot as BaseMicrodot
|
from microdot_asyncio import Microdot as BaseMicrodot
|
||||||
from microdot_asyncio import Request
|
from microdot_asyncio import Request
|
||||||
|
from microdot import NoCaseDict
|
||||||
|
|
||||||
|
|
||||||
class _BodyStream: # pragma: no cover
|
class _BodyStream: # pragma: no cover
|
||||||
@@ -50,19 +51,18 @@ class Microdot(BaseMicrodot):
|
|||||||
|
|
||||||
async def asgi_app(self, scope, receive, send):
|
async def asgi_app(self, scope, receive, send):
|
||||||
"""An ASGI application."""
|
"""An ASGI application."""
|
||||||
if scope['type'] != 'http': # pragma: no cover
|
if scope['type'] not in ['http', 'websocket']: # pragma: no cover
|
||||||
return
|
return
|
||||||
path = scope['path']
|
path = scope['path']
|
||||||
if 'query_string' in scope and scope['query_string']:
|
if 'query_string' in scope and scope['query_string']:
|
||||||
path += '?' + scope['query_string'].decode()
|
path += '?' + scope['query_string'].decode()
|
||||||
headers = {}
|
headers = NoCaseDict()
|
||||||
content_length = 0
|
content_length = 0
|
||||||
for key, value in scope.get('headers', []):
|
for key, value in scope.get('headers', []):
|
||||||
headers[key] = value
|
headers[key] = value
|
||||||
if key.lower() == 'content-length':
|
if key.lower() == 'content-length':
|
||||||
content_length = int(value)
|
content_length = int(value)
|
||||||
|
|
||||||
body = b''
|
|
||||||
if content_length and content_length <= Request.max_body_length:
|
if content_length and content_length <= Request.max_body_length:
|
||||||
body = b''
|
body = b''
|
||||||
more = True
|
more = True
|
||||||
@@ -78,12 +78,13 @@ class Microdot(BaseMicrodot):
|
|||||||
req = Request(
|
req = Request(
|
||||||
self,
|
self,
|
||||||
(scope['client'][0], scope['client'][1]),
|
(scope['client'][0], scope['client'][1]),
|
||||||
scope['method'],
|
scope.get('method', 'GET'),
|
||||||
path,
|
path,
|
||||||
'HTTP/' + scope['http_version'],
|
'HTTP/' + scope['http_version'],
|
||||||
headers,
|
headers,
|
||||||
body=body,
|
body=body,
|
||||||
stream=stream)
|
stream=stream,
|
||||||
|
sock=(receive, send))
|
||||||
req.asgi_scope = scope
|
req.asgi_scope = scope
|
||||||
|
|
||||||
res = await self.dispatch_request(req)
|
res = await self.dispatch_request(req)
|
||||||
@@ -92,10 +93,13 @@ class Microdot(BaseMicrodot):
|
|||||||
header_list = []
|
header_list = []
|
||||||
for name, value in res.headers.items():
|
for name, value in res.headers.items():
|
||||||
if not isinstance(value, list):
|
if not isinstance(value, list):
|
||||||
header_list.append((name, value))
|
header_list.append((name.lower().encode(), value.encode()))
|
||||||
else:
|
else:
|
||||||
for v in value:
|
for v in value:
|
||||||
header_list.append((name, v))
|
header_list.append((name.lower().encode(), v.encode()))
|
||||||
|
|
||||||
|
if scope['type'] != 'http': # pragma: no cover
|
||||||
|
return
|
||||||
|
|
||||||
await send({'type': 'http.response.start',
|
await send({'type': 'http.response.start',
|
||||||
'status': res.status_code,
|
'status': res.status_code,
|
||||||
|
|||||||
86
src/microdot_asgi_websocket.py
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
from microdot_asyncio import Response, abort
|
||||||
|
from microdot_websocket import WebSocket as BaseWebSocket
|
||||||
|
|
||||||
|
|
||||||
|
class WebSocket(BaseWebSocket):
|
||||||
|
async def handshake(self):
|
||||||
|
connect = await self.request.sock[0]()
|
||||||
|
if connect['type'] != 'websocket.connect':
|
||||||
|
abort(400)
|
||||||
|
await self.request.sock[1]({'type': 'websocket.accept'})
|
||||||
|
|
||||||
|
async def receive(self):
|
||||||
|
message = await self.request.sock[0]()
|
||||||
|
if message['type'] == 'websocket.disconnect':
|
||||||
|
raise OSError(32, 'Websocket connection closed')
|
||||||
|
elif message['type'] != 'websocket.receive':
|
||||||
|
raise OSError(32, 'Websocket message type not supported')
|
||||||
|
return message.get('bytes', message.get('text'))
|
||||||
|
|
||||||
|
async def send(self, data):
|
||||||
|
if isinstance(data, str):
|
||||||
|
await self.request.sock[1](
|
||||||
|
{'type': 'websocket.send', 'text': data})
|
||||||
|
else:
|
||||||
|
await self.request.sock[1](
|
||||||
|
{'type': 'websocket.send', 'bytes': data})
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if not self.closed:
|
||||||
|
self.closed = True
|
||||||
|
try:
|
||||||
|
await self.request.sock[1]({'type': 'websocket.close'})
|
||||||
|
except: # noqa E722
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def websocket_upgrade(request):
|
||||||
|
"""Upgrade a request handler to a websocket connection.
|
||||||
|
|
||||||
|
This function can be called directly inside a route function to process a
|
||||||
|
WebSocket upgrade handshake, for example after the user's credentials are
|
||||||
|
verified. The function returns the websocket object::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
async def echo(request):
|
||||||
|
if not (await authenticate_user(request)):
|
||||||
|
abort(401)
|
||||||
|
ws = await websocket_upgrade(request)
|
||||||
|
while True:
|
||||||
|
message = await ws.receive()
|
||||||
|
await ws.send(message)
|
||||||
|
"""
|
||||||
|
ws = WebSocket(request)
|
||||||
|
await ws.handshake()
|
||||||
|
|
||||||
|
@request.after_request
|
||||||
|
async def after_request(request, response):
|
||||||
|
return Response.already_handled
|
||||||
|
|
||||||
|
return ws
|
||||||
|
|
||||||
|
|
||||||
|
def with_websocket(f):
|
||||||
|
"""Decorator to make a route a WebSocket endpoint.
|
||||||
|
|
||||||
|
This decorator is used to define a route that accepts websocket
|
||||||
|
connections. The route then receives a websocket object as a second
|
||||||
|
argument that it can use to send and receive messages::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
message = await ws.receive()
|
||||||
|
await ws.send(message)
|
||||||
|
"""
|
||||||
|
async def wrapper(request, *args, **kwargs):
|
||||||
|
ws = await websocket_upgrade(request)
|
||||||
|
try:
|
||||||
|
await f(request, ws, *args, **kwargs)
|
||||||
|
except OSError as exc:
|
||||||
|
if exc.errno != 32 and exc.errno != 54:
|
||||||
|
raise
|
||||||
|
await ws.close()
|
||||||
|
return ''
|
||||||
|
return wrapper
|
||||||
@@ -17,9 +17,13 @@ except ImportError:
|
|||||||
import io
|
import io
|
||||||
|
|
||||||
from microdot import Microdot as BaseMicrodot
|
from microdot import Microdot as BaseMicrodot
|
||||||
from microdot import print_exception
|
from microdot import mro
|
||||||
|
from microdot import NoCaseDict
|
||||||
from microdot import Request as BaseRequest
|
from microdot import Request as BaseRequest
|
||||||
from microdot import Response as BaseResponse
|
from microdot import Response as BaseResponse
|
||||||
|
from microdot import print_exception
|
||||||
|
from microdot import HTTPException
|
||||||
|
from microdot import MUTED_SOCKET_ERRORS
|
||||||
|
|
||||||
|
|
||||||
def _iscoroutine(coro):
|
def _iscoroutine(coro):
|
||||||
@@ -42,33 +46,41 @@ class _AsyncBytesIO:
|
|||||||
async def readuntil(self, separator=b'\n'): # pragma: no cover
|
async def readuntil(self, separator=b'\n'): # pragma: no cover
|
||||||
return self.stream.readuntil(separator=separator)
|
return self.stream.readuntil(separator=separator)
|
||||||
|
|
||||||
|
async def awrite(self, data): # pragma: no cover
|
||||||
|
return self.stream.write(data)
|
||||||
|
|
||||||
|
async def aclose(self): # pragma: no cover
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Request(BaseRequest):
|
class Request(BaseRequest):
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def create(app, client_stream, client_addr):
|
async def create(app, client_reader, client_writer, client_addr):
|
||||||
"""Create a request object.
|
"""Create a request object.
|
||||||
|
|
||||||
:param app: The Microdot application instance.
|
:param app: The Microdot application instance.
|
||||||
:param client_stream: An input stream from where the request data can
|
:param client_reader: An input stream from where the request data can
|
||||||
be read.
|
be read.
|
||||||
|
:param client_writer: An output stream where the response data can be
|
||||||
|
written.
|
||||||
:param client_addr: The address of the client, as a tuple.
|
:param client_addr: The address of the client, as a tuple.
|
||||||
|
|
||||||
This method is a coroutine. It returns a newly created ``Request``
|
This method is a coroutine. It returns a newly created ``Request``
|
||||||
object.
|
object.
|
||||||
"""
|
"""
|
||||||
# request line
|
# request line
|
||||||
line = (await Request._safe_readline(client_stream)).strip().decode()
|
line = (await Request._safe_readline(client_reader)).strip().decode()
|
||||||
if not line:
|
if not line:
|
||||||
return None
|
return None
|
||||||
method, url, http_version = line.split()
|
method, url, http_version = line.split()
|
||||||
http_version = http_version.split('/', 1)[1]
|
http_version = http_version.split('/', 1)[1]
|
||||||
|
|
||||||
# headers
|
# headers
|
||||||
headers = {}
|
headers = NoCaseDict()
|
||||||
content_length = 0
|
content_length = 0
|
||||||
while True:
|
while True:
|
||||||
line = (await Request._safe_readline(
|
line = (await Request._safe_readline(
|
||||||
client_stream)).strip().decode()
|
client_reader)).strip().decode()
|
||||||
if line == '':
|
if line == '':
|
||||||
break
|
break
|
||||||
header, value = line.split(':', 1)
|
header, value = line.split(':', 1)
|
||||||
@@ -80,14 +92,15 @@ class Request(BaseRequest):
|
|||||||
# body
|
# body
|
||||||
body = b''
|
body = b''
|
||||||
if content_length and content_length <= Request.max_body_length:
|
if content_length and content_length <= Request.max_body_length:
|
||||||
body = await client_stream.readexactly(content_length)
|
body = await client_reader.readexactly(content_length)
|
||||||
stream = None
|
stream = None
|
||||||
else:
|
else:
|
||||||
body = b''
|
body = b''
|
||||||
stream = client_stream
|
stream = client_reader
|
||||||
|
|
||||||
return Request(app, client_addr, method, url, http_version, headers,
|
return Request(app, client_addr, method, url, http_version, headers,
|
||||||
body=body, stream=stream)
|
body=body, stream=stream,
|
||||||
|
sock=(client_reader, client_writer))
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def stream(self):
|
def stream(self):
|
||||||
@@ -118,31 +131,33 @@ class Response(BaseResponse):
|
|||||||
default is "OK" for responses with a 200 status code and
|
default is "OK" for responses with a 200 status code and
|
||||||
"N/A" for any other status codes.
|
"N/A" for any other status codes.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
async def write(self, stream):
|
async def write(self, stream):
|
||||||
self.complete()
|
self.complete()
|
||||||
|
|
||||||
# status code
|
|
||||||
reason = self.reason if self.reason is not None else \
|
|
||||||
('OK' if self.status_code == 200 else 'N/A')
|
|
||||||
await stream.awrite('HTTP/1.0 {status_code} {reason}\r\n'.format(
|
|
||||||
status_code=self.status_code, reason=reason).encode())
|
|
||||||
|
|
||||||
# headers
|
|
||||||
for header, value in self.headers.items():
|
|
||||||
values = value if isinstance(value, list) else [value]
|
|
||||||
for value in values:
|
|
||||||
await stream.awrite('{header}: {value}\r\n'.format(
|
|
||||||
header=header, value=value).encode())
|
|
||||||
await stream.awrite(b'\r\n')
|
|
||||||
|
|
||||||
# body
|
|
||||||
try:
|
try:
|
||||||
|
# status code
|
||||||
|
reason = self.reason if self.reason is not None else \
|
||||||
|
('OK' if self.status_code == 200 else 'N/A')
|
||||||
|
await stream.awrite('HTTP/1.0 {status_code} {reason}\r\n'.format(
|
||||||
|
status_code=self.status_code, reason=reason).encode())
|
||||||
|
|
||||||
|
# headers
|
||||||
|
for header, value in self.headers.items():
|
||||||
|
values = value if isinstance(value, list) else [value]
|
||||||
|
for value in values:
|
||||||
|
await stream.awrite('{header}: {value}\r\n'.format(
|
||||||
|
header=header, value=value).encode())
|
||||||
|
await stream.awrite(b'\r\n')
|
||||||
|
|
||||||
|
# body
|
||||||
async for body in self.body_iter():
|
async for body in self.body_iter():
|
||||||
if isinstance(body, str): # pragma: no cover
|
if isinstance(body, str): # pragma: no cover
|
||||||
body = body.encode()
|
body = body.encode()
|
||||||
await stream.awrite(body)
|
await stream.awrite(body)
|
||||||
except OSError as exc: # pragma: no cover
|
except OSError as exc: # pragma: no cover
|
||||||
if exc.errno == 32 or exc.args[0] == 'Connection lost':
|
if exc.errno in MUTED_SOCKET_ERRORS or \
|
||||||
|
exc.args[0] == 'Connection lost':
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
@@ -194,7 +209,8 @@ class Response(BaseResponse):
|
|||||||
|
|
||||||
|
|
||||||
class Microdot(BaseMicrodot):
|
class Microdot(BaseMicrodot):
|
||||||
async def start_server(self, host='0.0.0.0', port=5000, debug=False):
|
async def start_server(self, host='0.0.0.0', port=5000, debug=False,
|
||||||
|
ssl=None):
|
||||||
"""Start the Microdot web server as a coroutine. This coroutine does
|
"""Start the Microdot web server as a coroutine. This coroutine does
|
||||||
not normally return, as the server enters an endless listening loop.
|
not normally return, as the server enters an endless listening loop.
|
||||||
The :func:`shutdown` function provides a method for terminating the
|
The :func:`shutdown` function provides a method for terminating the
|
||||||
@@ -211,6 +227,8 @@ class Microdot(BaseMicrodot):
|
|||||||
port 5000.
|
port 5000.
|
||||||
:param debug: If ``True``, the server logs debugging information. The
|
:param debug: If ``True``, the server logs debugging information. The
|
||||||
default is ``False``.
|
default is ``False``.
|
||||||
|
:param ssl: An ``SSLContext`` instance or ``None`` if the server should
|
||||||
|
not use TLS. The default is ``None``.
|
||||||
|
|
||||||
This method is a coroutine.
|
This method is a coroutine.
|
||||||
|
|
||||||
@@ -253,7 +271,12 @@ class Microdot(BaseMicrodot):
|
|||||||
print('Starting async server on {host}:{port}...'.format(
|
print('Starting async server on {host}:{port}...'.format(
|
||||||
host=host, port=port))
|
host=host, port=port))
|
||||||
|
|
||||||
self.server = await asyncio.start_server(serve, host, port)
|
try:
|
||||||
|
self.server = await asyncio.start_server(serve, host, port,
|
||||||
|
ssl=ssl)
|
||||||
|
except TypeError:
|
||||||
|
self.server = await asyncio.start_server(serve, host, port)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
await self.server.wait_closed()
|
await self.server.wait_closed()
|
||||||
@@ -263,7 +286,7 @@ class Microdot(BaseMicrodot):
|
|||||||
# wait a bit and try again
|
# wait a bit and try again
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
def run(self, host='0.0.0.0', port=5000, debug=False):
|
def run(self, host='0.0.0.0', port=5000, debug=False, ssl=None):
|
||||||
"""Start the web server. This function does not normally return, as
|
"""Start the web server. This function does not normally return, as
|
||||||
the server enters an endless listening loop. The :func:`shutdown`
|
the server enters an endless listening loop. The :func:`shutdown`
|
||||||
function provides a method for terminating the server gracefully.
|
function provides a method for terminating the server gracefully.
|
||||||
@@ -279,6 +302,8 @@ class Microdot(BaseMicrodot):
|
|||||||
port 5000.
|
port 5000.
|
||||||
:param debug: If ``True``, the server logs debugging information. The
|
:param debug: If ``True``, the server logs debugging information. The
|
||||||
default is ``False``.
|
default is ``False``.
|
||||||
|
:param ssl: An ``SSLContext`` instance or ``None`` if the server should
|
||||||
|
not use TLS. The default is ``None``.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
@@ -292,7 +317,8 @@ class Microdot(BaseMicrodot):
|
|||||||
|
|
||||||
app.run(debug=True)
|
app.run(debug=True)
|
||||||
"""
|
"""
|
||||||
asyncio.run(self.start_server(host=host, port=port, debug=debug))
|
asyncio.run(self.start_server(host=host, port=port, debug=debug,
|
||||||
|
ssl=ssl))
|
||||||
|
|
||||||
def shutdown(self):
|
def shutdown(self):
|
||||||
self.server.close()
|
self.server.close()
|
||||||
@@ -300,17 +326,18 @@ class Microdot(BaseMicrodot):
|
|||||||
async def handle_request(self, reader, writer):
|
async def handle_request(self, reader, writer):
|
||||||
req = None
|
req = None
|
||||||
try:
|
try:
|
||||||
req = await Request.create(self, reader,
|
req = await Request.create(self, reader, writer,
|
||||||
writer.get_extra_info('peername'))
|
writer.get_extra_info('peername'))
|
||||||
except Exception as exc: # pragma: no cover
|
except Exception as exc: # pragma: no cover
|
||||||
print_exception(exc)
|
print_exception(exc)
|
||||||
|
|
||||||
res = await self.dispatch_request(req)
|
res = await self.dispatch_request(req)
|
||||||
await res.write(writer)
|
if res != Response.already_handled: # pragma: no branch
|
||||||
|
await res.write(writer)
|
||||||
try:
|
try:
|
||||||
await writer.aclose()
|
await writer.aclose()
|
||||||
except OSError as exc: # pragma: no cover
|
except OSError as exc: # pragma: no cover
|
||||||
if exc.errno == 32: # errno.EPIPE
|
if exc.errno in MUTED_SOCKET_ERRORS:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
@@ -320,6 +347,7 @@ class Microdot(BaseMicrodot):
|
|||||||
status_code=res.status_code))
|
status_code=res.status_code))
|
||||||
|
|
||||||
async def dispatch_request(self, req):
|
async def dispatch_request(self, req):
|
||||||
|
after_request_handled = False
|
||||||
if req:
|
if req:
|
||||||
if req.content_length > req.max_content_length:
|
if req.content_length > req.max_content_length:
|
||||||
if 413 in self.error_handlers:
|
if 413 in self.error_handlers:
|
||||||
@@ -354,19 +382,34 @@ class Microdot(BaseMicrodot):
|
|||||||
res = await self._invoke_handler(
|
res = await self._invoke_handler(
|
||||||
handler, req, res) or res
|
handler, req, res) or res
|
||||||
for handler in req.after_request_handlers:
|
for handler in req.after_request_handlers:
|
||||||
res = await handler(req, res) or res
|
res = await self._invoke_handler(
|
||||||
|
handler, req, res) or res
|
||||||
|
after_request_handled = True
|
||||||
elif f in self.error_handlers:
|
elif f in self.error_handlers:
|
||||||
res = await self._invoke_handler(
|
res = await self._invoke_handler(
|
||||||
self.error_handlers[f], req)
|
self.error_handlers[f], req)
|
||||||
else:
|
else:
|
||||||
res = 'Not found', f
|
res = 'Not found', f
|
||||||
|
except HTTPException as exc:
|
||||||
|
if exc.status_code in self.error_handlers:
|
||||||
|
res = self.error_handlers[exc.status_code](req)
|
||||||
|
else:
|
||||||
|
res = exc.reason, exc.status_code
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print_exception(exc)
|
print_exception(exc)
|
||||||
|
exc_class = None
|
||||||
res = None
|
res = None
|
||||||
if exc.__class__ in self.error_handlers:
|
if exc.__class__ in self.error_handlers:
|
||||||
|
exc_class = exc.__class__
|
||||||
|
else:
|
||||||
|
for c in mro(exc.__class__)[1:]:
|
||||||
|
if c in self.error_handlers:
|
||||||
|
exc_class = c
|
||||||
|
break
|
||||||
|
if exc_class:
|
||||||
try:
|
try:
|
||||||
res = await self._invoke_handler(
|
res = await self._invoke_handler(
|
||||||
self.error_handlers[exc.__class__], req, exc)
|
self.error_handlers[exc_class], req, exc)
|
||||||
except Exception as exc2: # pragma: no cover
|
except Exception as exc2: # pragma: no cover
|
||||||
print_exception(exc2)
|
print_exception(exc2)
|
||||||
if res is None:
|
if res is None:
|
||||||
@@ -384,6 +427,10 @@ class Microdot(BaseMicrodot):
|
|||||||
res = Response(*res)
|
res = Response(*res)
|
||||||
elif not isinstance(res, Response):
|
elif not isinstance(res, Response):
|
||||||
res = Response(res)
|
res = Response(res)
|
||||||
|
if not after_request_handled:
|
||||||
|
for handler in self.after_error_request_handlers:
|
||||||
|
res = await self._invoke_handler(
|
||||||
|
handler, req, res) or res
|
||||||
return res
|
return res
|
||||||
|
|
||||||
async def _invoke_handler(self, f_or_coro, *args, **kwargs):
|
async def _invoke_handler(self, f_or_coro, *args, **kwargs):
|
||||||
@@ -393,5 +440,7 @@ class Microdot(BaseMicrodot):
|
|||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
|
abort = Microdot.abort
|
||||||
|
Response.already_handled = Response()
|
||||||
redirect = Response.redirect
|
redirect = Response.redirect
|
||||||
send_file = Response.send_file
|
send_file = Response.send_file
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
from microdot_asyncio import Request, _AsyncBytesIO
|
from microdot_asyncio import Request, Response, _AsyncBytesIO
|
||||||
from microdot_test_client import TestClient as BaseTestClient, \
|
from microdot_test_client import TestClient as BaseTestClient, \
|
||||||
TestResponse as BaseTestResponse
|
TestResponse as BaseTestResponse
|
||||||
|
try:
|
||||||
|
from microdot_asyncio_websocket import WebSocket
|
||||||
|
except: # pragma: no cover # noqa: E722
|
||||||
|
WebSocket = None
|
||||||
|
|
||||||
|
|
||||||
class TestResponse(BaseTestResponse):
|
class TestResponse(BaseTestResponse):
|
||||||
@@ -17,7 +21,7 @@ class TestResponse(BaseTestResponse):
|
|||||||
|
|
||||||
async def _initialize_body(self, res):
|
async def _initialize_body(self, res):
|
||||||
self.body = b''
|
self.body = b''
|
||||||
async for body in res.body_iter():
|
async for body in res.body_iter(): # pragma: no branch
|
||||||
if isinstance(body, str):
|
if isinstance(body, str):
|
||||||
body = body.encode()
|
body = body.encode()
|
||||||
self.body += body
|
self.body += body
|
||||||
@@ -47,15 +51,24 @@ class TestClient(BaseTestClient):
|
|||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
assert res.text == 'Hello, World!'
|
assert res.text == 'Hello, World!'
|
||||||
"""
|
"""
|
||||||
async def request(self, method, path, headers=None, body=None):
|
async def request(self, method, path, headers=None, body=None, sock=None):
|
||||||
headers = headers or {}
|
headers = headers or {}
|
||||||
body, headers = self._process_body(body, headers)
|
body, headers = self._process_body(body, headers)
|
||||||
cookies, headers = self._process_cookies(headers)
|
cookies, headers = self._process_cookies(headers)
|
||||||
request_bytes = self._render_request(method, path, headers, body)
|
request_bytes = self._render_request(method, path, headers, body)
|
||||||
|
if sock:
|
||||||
|
reader = sock[0]
|
||||||
|
reader.buffer = request_bytes
|
||||||
|
writer = sock[1]
|
||||||
|
else:
|
||||||
|
reader = _AsyncBytesIO(request_bytes)
|
||||||
|
writer = _AsyncBytesIO(b'')
|
||||||
|
|
||||||
req = await Request.create(self.app, _AsyncBytesIO(request_bytes),
|
req = await Request.create(self.app, reader, writer,
|
||||||
('127.0.0.1', 1234))
|
('127.0.0.1', 1234))
|
||||||
res = await self.app.dispatch_request(req)
|
res = await self.app.dispatch_request(req)
|
||||||
|
if res == Response.already_handled:
|
||||||
|
return None
|
||||||
res.complete()
|
res.complete()
|
||||||
|
|
||||||
self._update_cookies(res)
|
self._update_cookies(res)
|
||||||
@@ -124,3 +137,72 @@ class TestClient(BaseTestClient):
|
|||||||
:class:`TestResponse <microdot_test_client.TestResponse>` object.
|
:class:`TestResponse <microdot_test_client.TestResponse>` object.
|
||||||
"""
|
"""
|
||||||
return await self.request('DELETE', path, headers=headers)
|
return await self.request('DELETE', path, headers=headers)
|
||||||
|
|
||||||
|
async def websocket(self, path, client, headers=None):
|
||||||
|
"""Send a websocket connection request to the application.
|
||||||
|
|
||||||
|
:param path: The request URL.
|
||||||
|
:param client: A generator function that yields client messages.
|
||||||
|
:param headers: A dictionary of headers to send with the request.
|
||||||
|
"""
|
||||||
|
gen = client()
|
||||||
|
|
||||||
|
class FakeWebSocket:
|
||||||
|
def __init__(self):
|
||||||
|
self.started = False
|
||||||
|
self.closed = False
|
||||||
|
self.buffer = b''
|
||||||
|
|
||||||
|
async def _next(self, data=None):
|
||||||
|
try:
|
||||||
|
data = (await gen.asend(data)) if hasattr(gen, 'asend') \
|
||||||
|
else gen.send(data)
|
||||||
|
except (StopIteration, StopAsyncIteration):
|
||||||
|
if not self.closed:
|
||||||
|
self.closed = True
|
||||||
|
raise OSError(32, 'Websocket connection closed')
|
||||||
|
return # pragma: no cover
|
||||||
|
opcode = WebSocket.TEXT if isinstance(data, str) \
|
||||||
|
else WebSocket.BINARY
|
||||||
|
return WebSocket._encode_websocket_frame(opcode, data)
|
||||||
|
|
||||||
|
async def read(self, n):
|
||||||
|
if not self.buffer:
|
||||||
|
self.started = True
|
||||||
|
self.buffer = await self._next()
|
||||||
|
data = self.buffer[:n]
|
||||||
|
self.buffer = self.buffer[n:]
|
||||||
|
return data
|
||||||
|
|
||||||
|
async def readexactly(self, n): # pragma: no cover
|
||||||
|
return await self.read(n)
|
||||||
|
|
||||||
|
async def readline(self):
|
||||||
|
line = b''
|
||||||
|
while True:
|
||||||
|
line += await self.read(1)
|
||||||
|
if line[-1] in [b'\n', 10]:
|
||||||
|
break
|
||||||
|
return line
|
||||||
|
|
||||||
|
async def awrite(self, data):
|
||||||
|
if self.started:
|
||||||
|
h = WebSocket._parse_frame_header(data[0:2])
|
||||||
|
if h[3] < 0:
|
||||||
|
data = data[2 - h[3]:]
|
||||||
|
else:
|
||||||
|
data = data[2:]
|
||||||
|
if h[1] == WebSocket.TEXT:
|
||||||
|
data = data.decode()
|
||||||
|
self.buffer = await self._next(data)
|
||||||
|
|
||||||
|
ws_headers = {
|
||||||
|
'Upgrade': 'websocket',
|
||||||
|
'Connection': 'Upgrade',
|
||||||
|
'Sec-WebSocket-Version': '13',
|
||||||
|
'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
|
||||||
|
}
|
||||||
|
ws_headers.update(headers or {})
|
||||||
|
sock = FakeWebSocket()
|
||||||
|
return await self.request('GET', path, headers=ws_headers,
|
||||||
|
sock=(sock, sock))
|
||||||
|
|||||||
103
src/microdot_asyncio_websocket.py
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
from microdot_asyncio import Response
|
||||||
|
from microdot_websocket import WebSocket as BaseWebSocket
|
||||||
|
|
||||||
|
|
||||||
|
class WebSocket(BaseWebSocket):
|
||||||
|
async def handshake(self):
|
||||||
|
response = self._handshake_response()
|
||||||
|
await self.request.sock[1].awrite(
|
||||||
|
b'HTTP/1.1 101 Switching Protocols\r\n')
|
||||||
|
await self.request.sock[1].awrite(b'Upgrade: websocket\r\n')
|
||||||
|
await self.request.sock[1].awrite(b'Connection: Upgrade\r\n')
|
||||||
|
await self.request.sock[1].awrite(
|
||||||
|
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
||||||
|
|
||||||
|
async def receive(self):
|
||||||
|
while True:
|
||||||
|
opcode, payload = await self._read_frame()
|
||||||
|
send_opcode, data = self._process_websocket_frame(opcode, payload)
|
||||||
|
if send_opcode: # pragma: no cover
|
||||||
|
await self.send(send_opcode, data)
|
||||||
|
elif data: # pragma: no branch
|
||||||
|
return data
|
||||||
|
|
||||||
|
async def send(self, data, opcode=None):
|
||||||
|
frame = self._encode_websocket_frame(
|
||||||
|
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
|
||||||
|
data)
|
||||||
|
await self.request.sock[1].awrite(frame)
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if not self.closed: # pragma: no cover
|
||||||
|
self.closed = True
|
||||||
|
await self.send(b'', self.CLOSE)
|
||||||
|
|
||||||
|
async def _read_frame(self):
|
||||||
|
header = await self.request.sock[0].read(2)
|
||||||
|
if len(header) != 2: # pragma: no cover
|
||||||
|
raise OSError(32, 'Websocket connection closed')
|
||||||
|
fin, opcode, has_mask, length = self._parse_frame_header(header)
|
||||||
|
if length == -2:
|
||||||
|
length = await self.request.sock[0].read(2)
|
||||||
|
length = int.from_bytes(length, 'big')
|
||||||
|
elif length == -8:
|
||||||
|
length = await self.request.sock[0].read(8)
|
||||||
|
length = int.from_bytes(length, 'big')
|
||||||
|
if has_mask: # pragma: no cover
|
||||||
|
mask = await self.request.sock[0].read(4)
|
||||||
|
payload = await self.request.sock[0].read(length)
|
||||||
|
if has_mask: # pragma: no cover
|
||||||
|
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
|
||||||
|
return opcode, payload
|
||||||
|
|
||||||
|
|
||||||
|
async def websocket_upgrade(request):
|
||||||
|
"""Upgrade a request handler to a websocket connection.
|
||||||
|
|
||||||
|
This function can be called directly inside a route function to process a
|
||||||
|
WebSocket upgrade handshake, for example after the user's credentials are
|
||||||
|
verified. The function returns the websocket object::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
async def echo(request):
|
||||||
|
if not authenticate_user(request):
|
||||||
|
abort(401)
|
||||||
|
ws = await websocket_upgrade(request)
|
||||||
|
while True:
|
||||||
|
message = await ws.receive()
|
||||||
|
await ws.send(message)
|
||||||
|
"""
|
||||||
|
ws = WebSocket(request)
|
||||||
|
await ws.handshake()
|
||||||
|
|
||||||
|
@request.after_request
|
||||||
|
async def after_request(request, response):
|
||||||
|
return Response.already_handled
|
||||||
|
|
||||||
|
return ws
|
||||||
|
|
||||||
|
|
||||||
|
def with_websocket(f):
|
||||||
|
"""Decorator to make a route a WebSocket endpoint.
|
||||||
|
|
||||||
|
This decorator is used to define a route that accepts websocket
|
||||||
|
connections. The route then receives a websocket object as a second
|
||||||
|
argument that it can use to send and receive messages::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
message = await ws.receive()
|
||||||
|
await ws.send(message)
|
||||||
|
"""
|
||||||
|
async def wrapper(request, *args, **kwargs):
|
||||||
|
ws = await websocket_upgrade(request)
|
||||||
|
try:
|
||||||
|
await f(request, ws, *args, **kwargs)
|
||||||
|
await ws.close() # pragma: no cover
|
||||||
|
except OSError as exc:
|
||||||
|
if exc.errno not in [32, 54, 104]: # pragma: no cover
|
||||||
|
raise
|
||||||
|
return ''
|
||||||
|
return wrapper
|
||||||
@@ -23,15 +23,19 @@ def get_session(request):
|
|||||||
global secret_key
|
global secret_key
|
||||||
if not secret_key:
|
if not secret_key:
|
||||||
raise ValueError('The session secret key is not configured')
|
raise ValueError('The session secret key is not configured')
|
||||||
|
if hasattr(request.g, '_session'):
|
||||||
|
return request.g._session
|
||||||
session = request.cookies.get('session')
|
session = request.cookies.get('session')
|
||||||
if session is None:
|
if session is None:
|
||||||
return {}
|
request.g._session = {}
|
||||||
|
return request.g._session
|
||||||
try:
|
try:
|
||||||
session = jwt.decode(session, secret_key, algorithms=['HS256'])
|
session = jwt.decode(session, secret_key, algorithms=['HS256'])
|
||||||
except jwt.exceptions.PyJWTError: # pragma: no cover
|
except jwt.exceptions.PyJWTError: # pragma: no cover
|
||||||
raise
|
request.g._session = {}
|
||||||
return {}
|
else:
|
||||||
return session
|
request.g._session = session
|
||||||
|
return request.g._session
|
||||||
|
|
||||||
|
|
||||||
def update_session(request, session):
|
def update_session(request, session):
|
||||||
|
|||||||
61
src/microdot_ssl.py
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import ssl
|
||||||
|
|
||||||
|
|
||||||
|
def create_ssl_context(cert, key, **kwargs):
|
||||||
|
"""Create an SSL context to wrap sockets with.
|
||||||
|
|
||||||
|
:param cert: The certificate to use. If it is given as a string, it is
|
||||||
|
assumed to be a filename. If it is given as a bytes object, it
|
||||||
|
is assumed to be the certificate data. In both cases the data
|
||||||
|
is expected to be in PEM format for CPython and in DER format
|
||||||
|
for MicroPython.
|
||||||
|
:param key: The private key to use. If it is given as a string, it is
|
||||||
|
assumed to be a filename. If it is given as a bytes object, it
|
||||||
|
is assumed to be the private key data. in both cases the data
|
||||||
|
is expected to be in PEM format for CPython and in DER format
|
||||||
|
for MicroPython.
|
||||||
|
:param kwargs: Additional arguments to pass to the ``ssl.wrap_socket``
|
||||||
|
function.
|
||||||
|
|
||||||
|
Note: This function creates a fairly limited SSL context object to enable
|
||||||
|
the use of certificates under MicroPython. It is not intended to be used in
|
||||||
|
any other context, and in particular, it is not needed when using CPython
|
||||||
|
or any other Python implementation that has native support for
|
||||||
|
``SSLContext`` objects. Once MicroPython implements ``SSLContext``
|
||||||
|
natively, this function will be deprecated.
|
||||||
|
"""
|
||||||
|
if hasattr(ssl, 'SSLContext'):
|
||||||
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER, **kwargs)
|
||||||
|
ctx.load_cert_chain(cert, key)
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
if isinstance(cert, str):
|
||||||
|
with open(cert, 'rb') as f:
|
||||||
|
cert = f.read()
|
||||||
|
if isinstance(key, str):
|
||||||
|
with open(key, 'rb') as f:
|
||||||
|
key = f.read()
|
||||||
|
|
||||||
|
class FakeSSLSocket:
|
||||||
|
def __init__(self, sock, **kwargs):
|
||||||
|
self.sock = sock
|
||||||
|
self.kwargs = kwargs
|
||||||
|
|
||||||
|
def accept(self):
|
||||||
|
client, addr = self.sock.accept()
|
||||||
|
return (ssl.wrap_socket(client, cert=cert, key=key, **self.kwargs),
|
||||||
|
addr)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.sock.close()
|
||||||
|
|
||||||
|
class FakeSSLContext:
|
||||||
|
def __init__(self, **kwargs):
|
||||||
|
self.kwargs = kwargs
|
||||||
|
|
||||||
|
def wrap_socket(self, sock, **kwargs):
|
||||||
|
all_kwargs = self.kwargs.copy()
|
||||||
|
all_kwargs.update(kwargs)
|
||||||
|
return FakeSSLSocket(sock, **all_kwargs)
|
||||||
|
|
||||||
|
return FakeSSLContext(**kwargs)
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
import json
|
import json
|
||||||
from microdot import Request
|
from microdot import Request, Response, NoCaseDict
|
||||||
|
try:
|
||||||
|
from microdot_websocket import WebSocket
|
||||||
|
except: # pragma: no cover # noqa: E722
|
||||||
|
WebSocket = None
|
||||||
|
|
||||||
|
|
||||||
class TestResponse:
|
class TestResponse:
|
||||||
@@ -42,11 +46,10 @@ class TestResponse:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def _process_json_body(self):
|
def _process_json_body(self):
|
||||||
for name, value in self.headers.items(): # pragma: no branch
|
if 'Content-Type' in self.headers: # pragma: no branch
|
||||||
if name.lower() == 'content-type':
|
content_type = self.headers['Content-Type']
|
||||||
if value.lower() == 'application/json':
|
if content_type.split(';')[0] == 'application/json':
|
||||||
self.json = json.loads(self.text)
|
self.json = json.loads(self.text)
|
||||||
break
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def create(cls, res):
|
def create(cls, res):
|
||||||
@@ -82,6 +85,8 @@ class TestClient:
|
|||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
assert res.text == 'Hello, World!'
|
assert res.text == 'Hello, World!'
|
||||||
"""
|
"""
|
||||||
|
__test__ = False # remove this class from pytest's test collection
|
||||||
|
|
||||||
def __init__(self, app, cookies=None):
|
def __init__(self, app, cookies=None):
|
||||||
self.app = app
|
self.app = app
|
||||||
self.cookies = cookies or {}
|
self.cookies = cookies or {}
|
||||||
@@ -91,13 +96,11 @@ class TestClient:
|
|||||||
body = b''
|
body = b''
|
||||||
elif isinstance(body, (dict, list)):
|
elif isinstance(body, (dict, list)):
|
||||||
body = json.dumps(body).encode()
|
body = json.dumps(body).encode()
|
||||||
if 'Content-Type' not in headers and \
|
if 'Content-Type' not in headers: # pragma: no cover
|
||||||
'content-type' not in headers: # pragma: no cover
|
|
||||||
headers['Content-Type'] = 'application/json'
|
headers['Content-Type'] = 'application/json'
|
||||||
elif isinstance(body, str):
|
elif isinstance(body, str):
|
||||||
body = body.encode()
|
body = body.encode()
|
||||||
if body and 'Content-Length' not in headers and \
|
if body and 'Content-Length' not in headers:
|
||||||
'content-length' not in headers:
|
|
||||||
headers['Content-Length'] = str(len(body))
|
headers['Content-Length'] = str(len(body))
|
||||||
if 'Host' not in headers: # pragma: no branch
|
if 'Host' not in headers: # pragma: no branch
|
||||||
headers['Host'] = 'example.com:1234'
|
headers['Host'] = 'example.com:1234'
|
||||||
@@ -126,36 +129,37 @@ class TestClient:
|
|||||||
return request_bytes
|
return request_bytes
|
||||||
|
|
||||||
def _update_cookies(self, res):
|
def _update_cookies(self, res):
|
||||||
for name, value in res.headers.items():
|
cookies = res.headers.get('Set-Cookie', [])
|
||||||
if name.lower() == 'set-cookie':
|
for cookie in cookies:
|
||||||
for cookie in value:
|
cookie_name, cookie_value = cookie.split('=', 1)
|
||||||
cookie_name, cookie_value = cookie.split('=', 1)
|
cookie_options = cookie_value.split(';')
|
||||||
cookie_options = cookie_value.split(';')
|
delete = False
|
||||||
delete = False
|
for option in cookie_options[1:]:
|
||||||
for option in cookie_options[1:]:
|
if option.strip().lower().startswith('expires='):
|
||||||
if option.strip().lower().startswith('expires='):
|
_, e = option.strip().split('=', 1)
|
||||||
_, e = option.strip().split('=', 1)
|
# this is a very limited parser for cookie expiry
|
||||||
# this is a very limited parser for cookie expiry
|
# that only detects a cookie deletion request when
|
||||||
# that only detects a cookie deletion request when
|
# the date is 1/1/1970
|
||||||
# the date is 1/1/1970
|
if '1 jan 1970' in e.lower(): # pragma: no branch
|
||||||
if '1 jan 1970' in e.lower(): # pragma: no branch
|
delete = True
|
||||||
delete = True
|
break
|
||||||
break
|
if delete:
|
||||||
if delete:
|
if cookie_name in self.cookies: # pragma: no branch
|
||||||
if cookie_name in self.cookies: # pragma: no branch
|
del self.cookies[cookie_name]
|
||||||
del self.cookies[cookie_name]
|
else:
|
||||||
else:
|
self.cookies[cookie_name] = cookie_options[0]
|
||||||
self.cookies[cookie_name] = cookie_options[0]
|
|
||||||
|
|
||||||
def request(self, method, path, headers=None, body=None):
|
def request(self, method, path, headers=None, body=None, sock=None):
|
||||||
headers = headers or {}
|
headers = NoCaseDict(headers or {})
|
||||||
body, headers = self._process_body(body, headers)
|
body, headers = self._process_body(body, headers)
|
||||||
cookies, headers = self._process_cookies(headers)
|
cookies, headers = self._process_cookies(headers)
|
||||||
request_bytes = self._render_request(method, path, headers, body)
|
request_bytes = self._render_request(method, path, headers, body)
|
||||||
|
|
||||||
req = Request.create(self.app, BytesIO(request_bytes),
|
req = Request.create(self.app, BytesIO(request_bytes),
|
||||||
('127.0.0.1', 1234))
|
('127.0.0.1', 1234), client_sock=sock)
|
||||||
res = self.app.dispatch_request(req)
|
res = self.app.dispatch_request(req)
|
||||||
|
if res == Response.already_handled:
|
||||||
|
return None
|
||||||
res.complete()
|
res.complete()
|
||||||
|
|
||||||
self._update_cookies(res)
|
self._update_cookies(res)
|
||||||
@@ -224,3 +228,59 @@ class TestClient:
|
|||||||
:class:`TestResponse <microdot_test_client.TestResponse>` object.
|
:class:`TestResponse <microdot_test_client.TestResponse>` object.
|
||||||
"""
|
"""
|
||||||
return self.request('DELETE', path, headers=headers)
|
return self.request('DELETE', path, headers=headers)
|
||||||
|
|
||||||
|
def websocket(self, path, client, headers=None):
|
||||||
|
"""Send a websocket connection request to the application.
|
||||||
|
|
||||||
|
:param path: The request URL.
|
||||||
|
:param client: A generator function that yields client messages.
|
||||||
|
:param headers: A dictionary of headers to send with the request.
|
||||||
|
"""
|
||||||
|
gen = client()
|
||||||
|
|
||||||
|
class FakeWebSocket:
|
||||||
|
def __init__(self):
|
||||||
|
self.started = False
|
||||||
|
self.closed = False
|
||||||
|
self.buffer = b''
|
||||||
|
|
||||||
|
def _next(self, data=None):
|
||||||
|
try:
|
||||||
|
data = gen.send(data)
|
||||||
|
except StopIteration:
|
||||||
|
if self.closed: # pragma: no cover
|
||||||
|
return
|
||||||
|
self.closed = True
|
||||||
|
raise OSError(32, 'Websocket connection closed')
|
||||||
|
opcode = WebSocket.TEXT if isinstance(data, str) \
|
||||||
|
else WebSocket.BINARY
|
||||||
|
return WebSocket._encode_websocket_frame(opcode, data)
|
||||||
|
|
||||||
|
def recv(self, n):
|
||||||
|
self.started = True
|
||||||
|
if not self.buffer:
|
||||||
|
self.buffer = self._next()
|
||||||
|
data = self.buffer[:n]
|
||||||
|
self.buffer = self.buffer[n:]
|
||||||
|
return data
|
||||||
|
|
||||||
|
def send(self, data):
|
||||||
|
if self.started:
|
||||||
|
h = WebSocket._parse_frame_header(data[0:2])
|
||||||
|
if h[3] < 0:
|
||||||
|
data = data[2 - h[3]:]
|
||||||
|
else:
|
||||||
|
data = data[2:]
|
||||||
|
if h[1] == WebSocket.TEXT:
|
||||||
|
data = data.decode()
|
||||||
|
self.buffer = self._next(data)
|
||||||
|
|
||||||
|
ws_headers = {
|
||||||
|
'Upgrade': 'websocket',
|
||||||
|
'Connection': 'Upgrade',
|
||||||
|
'Sec-WebSocket-Version': '13',
|
||||||
|
'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
|
||||||
|
}
|
||||||
|
ws_headers.update(headers or {})
|
||||||
|
return self.request('GET', path, headers=ws_headers,
|
||||||
|
sock=FakeWebSocket())
|
||||||
|
|||||||
177
src/microdot_websocket.py
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
import binascii
|
||||||
|
import hashlib
|
||||||
|
from microdot import Response
|
||||||
|
|
||||||
|
|
||||||
|
class WebSocket:
|
||||||
|
CONT = 0
|
||||||
|
TEXT = 1
|
||||||
|
BINARY = 2
|
||||||
|
CLOSE = 8
|
||||||
|
PING = 9
|
||||||
|
PONG = 10
|
||||||
|
|
||||||
|
def __init__(self, request):
|
||||||
|
self.request = request
|
||||||
|
self.closed = False
|
||||||
|
|
||||||
|
def handshake(self):
|
||||||
|
response = self._handshake_response()
|
||||||
|
self.request.sock.send(b'HTTP/1.1 101 Switching Protocols\r\n')
|
||||||
|
self.request.sock.send(b'Upgrade: websocket\r\n')
|
||||||
|
self.request.sock.send(b'Connection: Upgrade\r\n')
|
||||||
|
self.request.sock.send(
|
||||||
|
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
||||||
|
|
||||||
|
def receive(self):
|
||||||
|
while True:
|
||||||
|
opcode, payload = self._read_frame()
|
||||||
|
send_opcode, data = self._process_websocket_frame(opcode, payload)
|
||||||
|
if send_opcode: # pragma: no cover
|
||||||
|
self.send(send_opcode, data)
|
||||||
|
elif data: # pragma: no branch
|
||||||
|
return data
|
||||||
|
|
||||||
|
def send(self, data, opcode=None):
|
||||||
|
frame = self._encode_websocket_frame(
|
||||||
|
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
|
||||||
|
data)
|
||||||
|
self.request.sock.send(frame)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
if not self.closed: # pragma: no cover
|
||||||
|
self.closed = True
|
||||||
|
self.send(b'', self.CLOSE)
|
||||||
|
|
||||||
|
def _handshake_response(self):
|
||||||
|
connection = False
|
||||||
|
upgrade = False
|
||||||
|
websocket_key = None
|
||||||
|
for header, value in self.request.headers.items():
|
||||||
|
h = header.lower()
|
||||||
|
if h == 'connection':
|
||||||
|
connection = True
|
||||||
|
if 'upgrade' not in value.lower():
|
||||||
|
return self.request.app.abort(400)
|
||||||
|
elif h == 'upgrade':
|
||||||
|
upgrade = True
|
||||||
|
if not value.lower() == 'websocket':
|
||||||
|
return self.request.app.abort(400)
|
||||||
|
elif h == 'sec-websocket-key':
|
||||||
|
websocket_key = value
|
||||||
|
if not connection or not upgrade or not websocket_key:
|
||||||
|
return self.request.app.abort(400)
|
||||||
|
d = hashlib.sha1(websocket_key.encode())
|
||||||
|
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
||||||
|
return binascii.b2a_base64(d.digest())[:-1]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _parse_frame_header(cls, header):
|
||||||
|
fin = header[0] & 0x80
|
||||||
|
opcode = header[0] & 0x0f
|
||||||
|
if fin == 0 or opcode == cls.CONT: # pragma: no cover
|
||||||
|
raise OSError(32, 'Continuation frames not supported')
|
||||||
|
has_mask = header[1] & 0x80
|
||||||
|
length = header[1] & 0x7f
|
||||||
|
if length == 126:
|
||||||
|
length = -2
|
||||||
|
elif length == 127:
|
||||||
|
length = -8
|
||||||
|
return fin, opcode, has_mask, length
|
||||||
|
|
||||||
|
def _process_websocket_frame(self, opcode, payload):
|
||||||
|
if opcode == self.TEXT:
|
||||||
|
payload = payload.decode()
|
||||||
|
elif opcode == self.BINARY:
|
||||||
|
pass
|
||||||
|
elif opcode == self.CLOSE:
|
||||||
|
raise OSError(32, 'Websocket connection closed')
|
||||||
|
elif opcode == self.PING:
|
||||||
|
return self.PONG, payload
|
||||||
|
elif opcode == self.PONG: # pragma: no branch
|
||||||
|
return None, None
|
||||||
|
return None, payload
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _encode_websocket_frame(cls, opcode, payload):
|
||||||
|
frame = bytearray()
|
||||||
|
frame.append(0x80 | opcode)
|
||||||
|
if opcode == cls.TEXT:
|
||||||
|
payload = payload.encode()
|
||||||
|
if len(payload) < 126:
|
||||||
|
frame.append(len(payload))
|
||||||
|
elif len(payload) < (1 << 16):
|
||||||
|
frame.append(126)
|
||||||
|
frame.extend(len(payload).to_bytes(2, 'big'))
|
||||||
|
else:
|
||||||
|
frame.append(127)
|
||||||
|
frame.extend(len(payload).to_bytes(8, 'big'))
|
||||||
|
frame.extend(payload)
|
||||||
|
return frame
|
||||||
|
|
||||||
|
def _read_frame(self):
|
||||||
|
header = self.request.sock.recv(2)
|
||||||
|
if len(header) != 2: # pragma: no cover
|
||||||
|
raise OSError(32, 'Websocket connection closed')
|
||||||
|
fin, opcode, has_mask, length = self._parse_frame_header(header)
|
||||||
|
if length < 0:
|
||||||
|
length = self.request.sock.recv(-length)
|
||||||
|
length = int.from_bytes(length, 'big')
|
||||||
|
if has_mask: # pragma: no cover
|
||||||
|
mask = self.request.sock.recv(4)
|
||||||
|
payload = self.request.sock.recv(length)
|
||||||
|
if has_mask: # pragma: no cover
|
||||||
|
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
|
||||||
|
return opcode, payload
|
||||||
|
|
||||||
|
|
||||||
|
def websocket_upgrade(request):
|
||||||
|
"""Upgrade a request handler to a websocket connection.
|
||||||
|
|
||||||
|
This function can be called directly inside a route function to process a
|
||||||
|
WebSocket upgrade handshake, for example after the user's credentials are
|
||||||
|
verified. The function returns the websocket object::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
def echo(request):
|
||||||
|
if not authenticate_user(request):
|
||||||
|
abort(401)
|
||||||
|
ws = websocket_upgrade(request)
|
||||||
|
while True:
|
||||||
|
message = ws.receive()
|
||||||
|
ws.send(message)
|
||||||
|
"""
|
||||||
|
ws = WebSocket(request)
|
||||||
|
ws.handshake()
|
||||||
|
|
||||||
|
@request.after_request
|
||||||
|
def after_request(request, response):
|
||||||
|
return Response.already_handled
|
||||||
|
|
||||||
|
return ws
|
||||||
|
|
||||||
|
|
||||||
|
def with_websocket(f):
|
||||||
|
"""Decorator to make a route a WebSocket endpoint.
|
||||||
|
|
||||||
|
This decorator is used to define a route that accepts websocket
|
||||||
|
connections. The route then receives a websocket object as a second
|
||||||
|
argument that it can use to send and receive messages::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
message = ws.receive()
|
||||||
|
ws.send(message)
|
||||||
|
"""
|
||||||
|
def wrapper(request, *args, **kwargs):
|
||||||
|
ws = websocket_upgrade(request)
|
||||||
|
try:
|
||||||
|
f(request, ws, *args, **kwargs)
|
||||||
|
ws.close() # pragma: no cover
|
||||||
|
except OSError as exc:
|
||||||
|
if exc.errno not in [32, 54, 104]: # pragma: no cover
|
||||||
|
raise
|
||||||
|
return ''
|
||||||
|
return wrapper
|
||||||
114
src/microdot_websocket_alt.py
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
import binascii
|
||||||
|
import hashlib
|
||||||
|
import select
|
||||||
|
import websocket as _websocket
|
||||||
|
from microdot import Response
|
||||||
|
|
||||||
|
|
||||||
|
class WebSocket:
|
||||||
|
CONT = 0
|
||||||
|
TEXT = 1
|
||||||
|
BINARY = 2
|
||||||
|
CLOSE = 8
|
||||||
|
PING = 9
|
||||||
|
PONG = 10
|
||||||
|
|
||||||
|
def __init__(self, request):
|
||||||
|
self.request = request
|
||||||
|
self.poll = select.poll()
|
||||||
|
self.poll.register(self.request.sock, select.POLLIN)
|
||||||
|
self.ws = _websocket.websocket(self.request.sock, True)
|
||||||
|
self.request.sock.setblocking(False)
|
||||||
|
|
||||||
|
def handshake(self):
|
||||||
|
response = self._handshake_response()
|
||||||
|
self.request.sock.write(b'HTTP/1.1 101 Switching Protocols\r\n')
|
||||||
|
self.request.sock.write(b'Upgrade: websocket\r\n')
|
||||||
|
self.request.sock.write(b'Connection: Upgrade\r\n')
|
||||||
|
self.request.sock.write(
|
||||||
|
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
||||||
|
|
||||||
|
def receive(self):
|
||||||
|
while True:
|
||||||
|
self.poll.poll()
|
||||||
|
data = self.ws.read()
|
||||||
|
if data:
|
||||||
|
try:
|
||||||
|
data = data.decode()
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
return data
|
||||||
|
|
||||||
|
def send(self, data):
|
||||||
|
self.ws.write(data)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.poll.unregister(self.request.sock)
|
||||||
|
self.ws.close()
|
||||||
|
|
||||||
|
def _handshake_response(self):
|
||||||
|
for header, value in self.request.headers.items():
|
||||||
|
h = header.lower()
|
||||||
|
if h == 'connection' and not value.lower().startswith('upgrade'):
|
||||||
|
return self.request.app.abort(400)
|
||||||
|
elif h == 'upgrade' and not value.lower() == 'websocket':
|
||||||
|
return self.request.app.abort(400)
|
||||||
|
elif h == 'sec-websocket-key':
|
||||||
|
websocket_key = value
|
||||||
|
if not websocket_key:
|
||||||
|
return self.request.app.abort(400)
|
||||||
|
d = hashlib.sha1(websocket_key.encode())
|
||||||
|
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
||||||
|
return binascii.b2a_base64(d.digest())[:-1]
|
||||||
|
|
||||||
|
|
||||||
|
def websocket_upgrade(request):
|
||||||
|
"""Upgrade a request handler to a websocket connection.
|
||||||
|
|
||||||
|
This function can be called directly inside a route function to process a
|
||||||
|
WebSocket upgrade handshake, for example after the user's credentials are
|
||||||
|
verified. The function returns the websocket object::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
def echo(request):
|
||||||
|
if not authenticate_user(request):
|
||||||
|
abort(401)
|
||||||
|
ws = websocket_upgrade(request)
|
||||||
|
while True:
|
||||||
|
message = ws.receive()
|
||||||
|
ws.send(message)
|
||||||
|
"""
|
||||||
|
ws = WebSocket(request)
|
||||||
|
ws.handshake()
|
||||||
|
|
||||||
|
@request.after_request
|
||||||
|
def after_request(request, response):
|
||||||
|
return Response.already_handled
|
||||||
|
|
||||||
|
return ws
|
||||||
|
|
||||||
|
|
||||||
|
def with_websocket(f):
|
||||||
|
"""Decorator to make a route a WebSocket endpoint.
|
||||||
|
|
||||||
|
This decorator is used to define a route that accepts websocket
|
||||||
|
connections. The route then receives a websocket object as a second
|
||||||
|
argument that it can use to send and receive messages::
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def echo(request, ws):
|
||||||
|
while True:
|
||||||
|
message = ws.receive()
|
||||||
|
ws.send(message)
|
||||||
|
"""
|
||||||
|
def wrapper(request, *args, **kwargs):
|
||||||
|
ws = websocket_upgrade(request)
|
||||||
|
try:
|
||||||
|
f(request, ws, *args, **kwargs)
|
||||||
|
except OSError as exc:
|
||||||
|
if exc.errno != 32 and exc.errno != 54:
|
||||||
|
raise
|
||||||
|
ws.close()
|
||||||
|
return ''
|
||||||
|
return wrapper
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
import signal
|
import signal
|
||||||
from microdot import * # noqa: F401, F403
|
from microdot import * # noqa: F401, F403
|
||||||
from microdot import Microdot as BaseMicrodot
|
from microdot import Microdot as BaseMicrodot, Request, NoCaseDict
|
||||||
from microdot import Request
|
|
||||||
|
|
||||||
|
|
||||||
class Microdot(BaseMicrodot):
|
class Microdot(BaseMicrodot):
|
||||||
@@ -15,7 +14,7 @@ class Microdot(BaseMicrodot):
|
|||||||
path = environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')
|
path = environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')
|
||||||
if 'QUERY_STRING' in environ and environ['QUERY_STRING']:
|
if 'QUERY_STRING' in environ and environ['QUERY_STRING']:
|
||||||
path += '?' + environ['QUERY_STRING']
|
path += '?' + environ['QUERY_STRING']
|
||||||
headers = {}
|
headers = NoCaseDict()
|
||||||
for k, v in environ.items():
|
for k, v in environ.items():
|
||||||
if k.startswith('HTTP_'):
|
if k.startswith('HTTP_'):
|
||||||
h = '-'.join([p.title() for p in k[5:].split('_')])
|
h = '-'.join([p.title() for p in k[5:].split('_')])
|
||||||
@@ -27,7 +26,8 @@ class Microdot(BaseMicrodot):
|
|||||||
path,
|
path,
|
||||||
environ['SERVER_PROTOCOL'],
|
environ['SERVER_PROTOCOL'],
|
||||||
headers,
|
headers,
|
||||||
stream=environ['wsgi.input'])
|
stream=environ['wsgi.input'],
|
||||||
|
sock=environ.get('gunicorn.socket'))
|
||||||
req.environ = environ
|
req.environ = environ
|
||||||
|
|
||||||
res = self.dispatch_request(req)
|
res = self.dispatch_request(req)
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ from .test_request import TestRequest
|
|||||||
from .test_response import TestResponse
|
from .test_response import TestResponse
|
||||||
from .test_url_pattern import TestURLPattern
|
from .test_url_pattern import TestURLPattern
|
||||||
from .test_microdot import TestMicrodot
|
from .test_microdot import TestMicrodot
|
||||||
|
from .test_microdot_websocket import TestMicrodotWebSocket
|
||||||
|
|
||||||
from .test_request_asyncio import TestRequestAsync
|
from .test_request_asyncio import TestRequestAsync
|
||||||
from .test_response_asyncio import TestResponseAsync
|
from .test_response_asyncio import TestResponseAsync
|
||||||
from .test_microdot_asyncio import TestMicrodotAsync
|
from .test_microdot_asyncio import TestMicrodotAsync
|
||||||
|
from .test_microdot_asyncio_websocket import TestMicrodotAsyncWebSocket
|
||||||
from .test_utemplate import TestUTemplate
|
from .test_utemplate import TestUTemplate
|
||||||
|
|
||||||
from .test_session import TestSession
|
from .test_session import TestSession
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ def _run(coro):
|
|||||||
|
|
||||||
@unittest.skipIf(sys.implementation.name == 'micropython',
|
@unittest.skipIf(sys.implementation.name == 'micropython',
|
||||||
'not supported under MicroPython')
|
'not supported under MicroPython')
|
||||||
class TestUTemplate(unittest.TestCase):
|
class TestJinja(unittest.TestCase):
|
||||||
def test_render_template(self):
|
def test_render_template(self):
|
||||||
s = render_template('hello.jinja.txt', name='foo')
|
s = render_template('hello.jinja.txt', name='foo')
|
||||||
self.assertEqual(s, 'Hello, foo!')
|
self.assertEqual(s, 'Hello, foo!')
|
||||||
@@ -44,7 +44,7 @@ class TestUTemplate(unittest.TestCase):
|
|||||||
return render_template('hello.jinja.txt', name='foo')
|
return render_template('hello.jinja.txt', name='foo')
|
||||||
|
|
||||||
req = _run(RequestAsync.create(
|
req = _run(RequestAsync.create(
|
||||||
app, get_async_request_fd('GET', '/'), 'addr'))
|
app, get_async_request_fd('GET', '/'), 'writer', 'addr'))
|
||||||
res = _run(app.dispatch_request(req))
|
res = _run(app.dispatch_request(req))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
from microdot import Microdot, Response
|
from microdot import Microdot, Response, abort
|
||||||
from microdot_test_client import TestClient
|
from microdot_test_client import TestClient
|
||||||
from tests import mock_socket
|
from tests import mock_socket
|
||||||
|
|
||||||
@@ -37,7 +37,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.get('/')
|
res = client.get('/')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Content-Length'], '3')
|
self.assertEqual(res.headers['Content-Length'], '3')
|
||||||
self.assertEqual(res.text, 'foo')
|
self.assertEqual(res.text, 'foo')
|
||||||
self.assertEqual(res.body, b'foo')
|
self.assertEqual(res.body, b'foo')
|
||||||
@@ -57,7 +58,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/')
|
res = client.post('/')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Content-Length'], '3')
|
self.assertEqual(res.headers['Content-Length'], '3')
|
||||||
self.assertEqual(res.text, 'bar')
|
self.assertEqual(res.text, 'bar')
|
||||||
|
|
||||||
@@ -73,7 +75,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
app.run()
|
app.run()
|
||||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
||||||
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
||||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
||||||
|
|
||||||
self._unmock()
|
self._unmock()
|
||||||
@@ -106,7 +109,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
for method in methods:
|
for method in methods:
|
||||||
res = getattr(client, method.lower())('/' + method.lower())
|
res = getattr(client, method.lower())('/' + method.lower())
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, method)
|
self.assertEqual(res.text, method)
|
||||||
|
|
||||||
def test_headers(self):
|
def test_headers(self):
|
||||||
@@ -119,7 +123,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.get('/', headers={'X-Foo': 'bar'})
|
res = client.get('/', headers={'X-Foo': 'bar'})
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'bar')
|
self.assertEqual(res.text, 'bar')
|
||||||
|
|
||||||
def test_cookies(self):
|
def test_cookies(self):
|
||||||
@@ -133,7 +138,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
||||||
res = client.get('/', headers={'Cookie': 'three=3'})
|
res = client.get('/', headers={'Cookie': 'three=3'})
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '123')
|
self.assertEqual(res.text, '123')
|
||||||
|
|
||||||
def test_binary_payload(self):
|
def test_binary_payload(self):
|
||||||
@@ -146,7 +152,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/', body=b'foo')
|
res = client.post('/', body=b'foo')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'foo')
|
self.assertEqual(res.text, 'foo')
|
||||||
|
|
||||||
def test_json_payload(self):
|
def test_json_payload(self):
|
||||||
@@ -165,12 +172,14 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
res = client.post('/dict', body={'foo': 'bar'})
|
res = client.post('/dict', body={'foo': 'bar'})
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'bar')
|
self.assertEqual(res.text, 'bar')
|
||||||
|
|
||||||
res = client.post('/list', body=['foo', 'bar'])
|
res = client.post('/list', body=['foo', 'bar'])
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'foo')
|
self.assertEqual(res.text, 'foo')
|
||||||
|
|
||||||
def test_tuple_responses(self):
|
def test_tuple_responses(self):
|
||||||
@@ -190,18 +199,21 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
@app.route('/body-status-headers')
|
@app.route('/body-status-headers')
|
||||||
def four(req):
|
def four(req):
|
||||||
return '<p>four</p>', 202, {'Content-Type': 'text/html'}
|
return '<p>four</p>', 202, \
|
||||||
|
{'Content-Type': 'text/html; charset=UTF-8'}
|
||||||
|
|
||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
|
|
||||||
res = client.get('/body')
|
res = client.get('/body')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'one')
|
self.assertEqual(res.text, 'one')
|
||||||
|
|
||||||
res = client.get('/body-status')
|
res = client.get('/body-status')
|
||||||
self.assertEqual(res.status_code, 202)
|
self.assertEqual(res.status_code, 202)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'two')
|
self.assertEqual(res.text, 'two')
|
||||||
|
|
||||||
res = client.get('/body-headers')
|
res = client.get('/body-headers')
|
||||||
@@ -211,7 +223,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
res = client.get('/body-status-headers')
|
res = client.get('/body-status-headers')
|
||||||
self.assertEqual(res.status_code, 202)
|
self.assertEqual(res.status_code, 202)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/html')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/html; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '<p>four</p>')
|
self.assertEqual(res.text, '<p>four</p>')
|
||||||
|
|
||||||
def test_before_after_request(self):
|
def test_before_after_request(self):
|
||||||
@@ -248,7 +261,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
res = client.get('/bar')
|
res = client.get('/bar')
|
||||||
self.assertEqual(res.status_code, 202)
|
self.assertEqual(res.status_code, 202)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
||||||
self.assertEqual(res.headers['X-One'], '1')
|
self.assertEqual(res.headers['X-One'], '1')
|
||||||
self.assertEqual(res.headers['X-Two'], '2')
|
self.assertEqual(res.headers['X-Two'], '2')
|
||||||
@@ -257,13 +271,47 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
res = client.get('/baz')
|
res = client.get('/baz')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
||||||
self.assertEqual(res.headers['X-One'], '1')
|
self.assertEqual(res.headers['X-One'], '1')
|
||||||
self.assertFalse('X-Two' in res.headers)
|
self.assertFalse('X-Two' in res.headers)
|
||||||
self.assertEqual(res.headers['Content-Length'], '3')
|
self.assertEqual(res.headers['Content-Length'], '3')
|
||||||
self.assertEqual(res.text, 'baz')
|
self.assertEqual(res.text, 'baz')
|
||||||
|
|
||||||
|
def test_after_error_request(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.after_error_request
|
||||||
|
def after_error_request_one(req, res):
|
||||||
|
res.headers['X-One'] = '1'
|
||||||
|
|
||||||
|
@app.after_error_request
|
||||||
|
def after_error_request_two(req, res):
|
||||||
|
res.set_cookie('foo', 'bar')
|
||||||
|
return res
|
||||||
|
|
||||||
|
@app.route('/foo')
|
||||||
|
def foo(req):
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
res = client.get('/foo')
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertFalse('X-One' in res.headers)
|
||||||
|
self.assertFalse('Set-Cookie' in res.headers)
|
||||||
|
|
||||||
|
res = client.get('/bar')
|
||||||
|
self.assertEqual(res.status_code, 404)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
||||||
|
self.assertEqual(res.headers['X-One'], '1')
|
||||||
|
self.assertEqual(client.cookies['foo'], 'bar')
|
||||||
|
|
||||||
def test_400(self):
|
def test_400(self):
|
||||||
self._mock()
|
self._mock()
|
||||||
|
|
||||||
@@ -276,7 +324,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
app.run()
|
app.run()
|
||||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
||||||
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
||||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
||||||
|
|
||||||
self._unmock()
|
self._unmock()
|
||||||
@@ -297,7 +346,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
app.run()
|
app.run()
|
||||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
|
||||||
self.assertIn(b'Content-Length: 3\r\n', fd.response)
|
self.assertIn(b'Content-Length: 3\r\n', fd.response)
|
||||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\n400'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\n400'))
|
||||||
|
|
||||||
self._unmock()
|
self._unmock()
|
||||||
@@ -312,7 +362,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/foo')
|
res = client.post('/foo')
|
||||||
self.assertEqual(res.status_code, 404)
|
self.assertEqual(res.status_code, 404)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Not found')
|
self.assertEqual(res.text, 'Not found')
|
||||||
|
|
||||||
def test_404_handler(self):
|
def test_404_handler(self):
|
||||||
@@ -329,7 +380,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/foo')
|
res = client.post('/foo')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '404')
|
self.assertEqual(res.text, '404')
|
||||||
|
|
||||||
def test_405(self):
|
def test_405(self):
|
||||||
@@ -342,7 +394,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/foo')
|
res = client.post('/foo')
|
||||||
self.assertEqual(res.status_code, 405)
|
self.assertEqual(res.status_code, 405)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Not found')
|
self.assertEqual(res.text, 'Not found')
|
||||||
|
|
||||||
def test_405_handler(self):
|
def test_405_handler(self):
|
||||||
@@ -359,7 +412,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.patch('/foo')
|
res = client.patch('/foo')
|
||||||
self.assertEqual(res.status_code, 405)
|
self.assertEqual(res.status_code, 405)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '405')
|
self.assertEqual(res.text, '405')
|
||||||
|
|
||||||
def test_413(self):
|
def test_413(self):
|
||||||
@@ -372,7 +426,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/foo', body='x' * 17000)
|
res = client.post('/foo', body='x' * 17000)
|
||||||
self.assertEqual(res.status_code, 413)
|
self.assertEqual(res.status_code, 413)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Payload too large')
|
self.assertEqual(res.text, 'Payload too large')
|
||||||
|
|
||||||
def test_413_handler(self):
|
def test_413_handler(self):
|
||||||
@@ -389,7 +444,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.post('/foo', body='x' * 17000)
|
res = client.post('/foo', body='x' * 17000)
|
||||||
self.assertEqual(res.status_code, 400)
|
self.assertEqual(res.status_code, 400)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '413')
|
self.assertEqual(res.text, '413')
|
||||||
|
|
||||||
def test_500(self):
|
def test_500(self):
|
||||||
@@ -402,7 +458,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.get('/')
|
res = client.get('/')
|
||||||
self.assertEqual(res.status_code, 500)
|
self.assertEqual(res.status_code, 500)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Internal server error')
|
self.assertEqual(res.text, 'Internal server error')
|
||||||
|
|
||||||
def test_500_handler(self):
|
def test_500_handler(self):
|
||||||
@@ -419,7 +476,8 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.get('/')
|
res = client.get('/')
|
||||||
self.assertEqual(res.status_code, 501)
|
self.assertEqual(res.status_code, 501)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '501')
|
self.assertEqual(res.text, '501')
|
||||||
|
|
||||||
def test_exception_handler(self):
|
def test_exception_handler(self):
|
||||||
@@ -436,9 +494,128 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.get('/')
|
res = client.get('/')
|
||||||
self.assertEqual(res.status_code, 501)
|
self.assertEqual(res.status_code, 501)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '501')
|
self.assertEqual(res.text, '501')
|
||||||
|
|
||||||
|
def test_exception_handler_parent(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(LookupError)
|
||||||
|
def handle_lookup_error(req, exc):
|
||||||
|
return exc.__class__.__name__, 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res.status_code, 501)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'IndexError')
|
||||||
|
|
||||||
|
def test_exception_handler_redundant_parent(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(LookupError)
|
||||||
|
def handle_lookup_error(req, exc):
|
||||||
|
return 'LookupError', 501
|
||||||
|
|
||||||
|
@app.errorhandler(IndexError)
|
||||||
|
def handle_index_error(req, exc):
|
||||||
|
return 'IndexError', 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res.status_code, 501)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'IndexError')
|
||||||
|
|
||||||
|
def test_exception_handler_multiple_parents(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(Exception)
|
||||||
|
def handle_generic_exception(req, exc):
|
||||||
|
return 'Exception', 501
|
||||||
|
|
||||||
|
@app.errorhandler(LookupError)
|
||||||
|
def handle_lookup_error(req, exc):
|
||||||
|
return 'LookupError', 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res.status_code, 501)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'LookupError')
|
||||||
|
|
||||||
|
def test_exception_handler_no_viable_parents(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(RuntimeError)
|
||||||
|
def handle_runtime_error(req, exc):
|
||||||
|
return 'RuntimeError', 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res.status_code, 500)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'Internal server error')
|
||||||
|
|
||||||
|
def test_abort(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
abort(406, 'Not acceptable')
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res.status_code, 406)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'Not acceptable')
|
||||||
|
|
||||||
|
def test_abort_handler(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
abort(406)
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
@app.errorhandler(406)
|
||||||
|
def handle_406(req):
|
||||||
|
return '406', 406
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res.status_code, 406)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, '406')
|
||||||
|
|
||||||
def test_json_response(self):
|
def test_json_response(self):
|
||||||
app = Microdot()
|
app = Microdot()
|
||||||
|
|
||||||
@@ -454,12 +631,14 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
res = client.get('/dict')
|
res = client.get('/dict')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'application/json')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'application/json; charset=UTF-8')
|
||||||
self.assertEqual(res.json, {'foo': 'bar'})
|
self.assertEqual(res.json, {'foo': 'bar'})
|
||||||
|
|
||||||
res = client.get('/list')
|
res = client.get('/list')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'application/json')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'application/json; charset=UTF-8')
|
||||||
self.assertEqual(res.json, ['foo', 'bar'])
|
self.assertEqual(res.json, ['foo', 'bar'])
|
||||||
|
|
||||||
def test_binary_response(self):
|
def test_binary_response(self):
|
||||||
@@ -491,9 +670,21 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = client.get('/')
|
res = client.get('/')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'foobar')
|
self.assertEqual(res.text, 'foobar')
|
||||||
|
|
||||||
|
def test_already_handled_response(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
return Response.already_handled
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/')
|
||||||
|
self.assertEqual(res, None)
|
||||||
|
|
||||||
def test_mount(self):
|
def test_mount(self):
|
||||||
subapp = Microdot()
|
subapp = Microdot()
|
||||||
|
|
||||||
@@ -503,7 +694,11 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
@subapp.after_request
|
@subapp.after_request
|
||||||
def after(req, res):
|
def after(req, res):
|
||||||
return res.body + b':after'
|
res.body += b':after'
|
||||||
|
|
||||||
|
@subapp.after_error_request
|
||||||
|
def after_error(req, res):
|
||||||
|
res.body += b':errorafter'
|
||||||
|
|
||||||
@subapp.errorhandler(404)
|
@subapp.errorhandler(404)
|
||||||
def not_found(req):
|
def not_found(req):
|
||||||
@@ -520,10 +715,37 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
|
|
||||||
res = client.get('/app')
|
res = client.get('/app')
|
||||||
self.assertEqual(res.status_code, 404)
|
self.assertEqual(res.status_code, 404)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
self.assertEqual(res.text, '404')
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, '404:errorafter')
|
||||||
|
|
||||||
res = client.get('/sub/app')
|
res = client.get('/sub/app')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'before:foo:after')
|
self.assertEqual(res.text, 'before:foo:after')
|
||||||
|
|
||||||
|
def test_ssl(self):
|
||||||
|
self._mock()
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/foo')
|
||||||
|
def foo(req):
|
||||||
|
return 'bar'
|
||||||
|
|
||||||
|
class FakeSSL:
|
||||||
|
def wrap_socket(self, sock, **kwargs):
|
||||||
|
return sock
|
||||||
|
|
||||||
|
mock_socket.clear_requests()
|
||||||
|
fd = mock_socket.add_request('GET', '/foo')
|
||||||
|
self._add_shutdown(app)
|
||||||
|
app.run(ssl=FakeSSL())
|
||||||
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
|
||||||
|
self.assertIn(b'Content-Length: 3\r\n', fd.response)
|
||||||
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
|
self.assertTrue(fd.response.endswith(b'\r\n\r\nbar'))
|
||||||
|
|
||||||
|
self._unmock()
|
||||||
|
|||||||
@@ -82,10 +82,12 @@ class TestMicrodotASGI(unittest.TestCase):
|
|||||||
async def send(packet):
|
async def send(packet):
|
||||||
if packet['type'] == 'http.response.start':
|
if packet['type'] == 'http.response.start':
|
||||||
self.assertEqual(packet['status'], 200)
|
self.assertEqual(packet['status'], 200)
|
||||||
expected_headers = [('Content-Length', '8'),
|
expected_headers = [
|
||||||
('Content-Type', 'text/plain'),
|
(b'content-length', b'8'),
|
||||||
('Set-Cookie', 'foo=foo'),
|
(b'content-type', b'text/plain; charset=UTF-8'),
|
||||||
('Set-Cookie', 'bar=bar; HttpOnly')]
|
(b'set-cookie', b'foo=foo'),
|
||||||
|
(b'set-cookie', b'bar=bar; HttpOnly')
|
||||||
|
]
|
||||||
self.assertEqual(len(packet['headers']), len(expected_headers))
|
self.assertEqual(len(packet['headers']), len(expected_headers))
|
||||||
for header in expected_headers:
|
for header in expected_headers:
|
||||||
self.assertIn(header, packet['headers'])
|
self.assertIn(header, packet['headers'])
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ except ImportError:
|
|||||||
import asyncio
|
import asyncio
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
from microdot_asyncio import Microdot, Response
|
from microdot_asyncio import Microdot, Response, abort
|
||||||
from microdot_asyncio_test_client import TestClient
|
from microdot_asyncio_test_client import TestClient
|
||||||
from tests import mock_asyncio, mock_socket
|
from tests import mock_asyncio, mock_socket
|
||||||
|
|
||||||
@@ -50,7 +50,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Content-Length'], '3')
|
self.assertEqual(res.headers['Content-Length'], '3')
|
||||||
self.assertEqual(res.text, 'foo')
|
self.assertEqual(res.text, 'foo')
|
||||||
self.assertEqual(res.body, b'foo')
|
self.assertEqual(res.body, b'foo')
|
||||||
@@ -58,7 +59,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/async'))
|
res = self._run(client.get('/async'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Content-Length'], '9')
|
self.assertEqual(res.headers['Content-Length'], '9')
|
||||||
self.assertEqual(res.text, 'foo-async')
|
self.assertEqual(res.text, 'foo-async')
|
||||||
self.assertEqual(res.body, b'foo-async')
|
self.assertEqual(res.body, b'foo-async')
|
||||||
@@ -83,7 +85,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.post('/'))
|
res = self._run(client.post('/'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Content-Length'], '3')
|
self.assertEqual(res.headers['Content-Length'], '3')
|
||||||
self.assertEqual(res.text, 'bar')
|
self.assertEqual(res.text, 'bar')
|
||||||
self.assertEqual(res.body, b'bar')
|
self.assertEqual(res.body, b'bar')
|
||||||
@@ -91,7 +94,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.post('/async'))
|
res = self._run(client.post('/async'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Content-Length'], '9')
|
self.assertEqual(res.headers['Content-Length'], '9')
|
||||||
self.assertEqual(res.text, 'bar-async')
|
self.assertEqual(res.text, 'bar-async')
|
||||||
self.assertEqual(res.body, b'bar-async')
|
self.assertEqual(res.body, b'bar-async')
|
||||||
@@ -107,7 +111,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
app.run()
|
app.run()
|
||||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
||||||
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
||||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
||||||
|
|
||||||
def test_method_decorators(self):
|
def test_method_decorators(self):
|
||||||
@@ -139,7 +144,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
res = self._run(getattr(
|
res = self._run(getattr(
|
||||||
client, method.lower())('/' + method.lower()))
|
client, method.lower())('/' + method.lower()))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, method)
|
self.assertEqual(res.text, method)
|
||||||
|
|
||||||
def test_headers(self):
|
def test_headers(self):
|
||||||
@@ -152,7 +158,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.get('/', headers={'X-Foo': 'bar'}))
|
res = self._run(client.get('/', headers={'X-Foo': 'bar'}))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'bar')
|
self.assertEqual(res.text, 'bar')
|
||||||
|
|
||||||
def test_cookies(self):
|
def test_cookies(self):
|
||||||
@@ -166,7 +173,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
||||||
res = self._run(client.get('/', headers={'Cookie': 'three=3'}))
|
res = self._run(client.get('/', headers={'Cookie': 'three=3'}))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '123')
|
self.assertEqual(res.text, '123')
|
||||||
|
|
||||||
def test_binary_payload(self):
|
def test_binary_payload(self):
|
||||||
@@ -179,7 +187,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.post('/', body=b'foo'))
|
res = self._run(client.post('/', body=b'foo'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'foo')
|
self.assertEqual(res.text, 'foo')
|
||||||
|
|
||||||
def test_json_payload(self):
|
def test_json_payload(self):
|
||||||
@@ -198,12 +207,14 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.post('/dict', body={'foo': 'bar'}))
|
res = self._run(client.post('/dict', body={'foo': 'bar'}))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'bar')
|
self.assertEqual(res.text, 'bar')
|
||||||
|
|
||||||
res = self._run(client.post('/list', body=['foo', 'bar']))
|
res = self._run(client.post('/list', body=['foo', 'bar']))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'foo')
|
self.assertEqual(res.text, 'foo')
|
||||||
|
|
||||||
def test_tuple_responses(self):
|
def test_tuple_responses(self):
|
||||||
@@ -223,18 +234,21 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
@app.route('/body-status-headers')
|
@app.route('/body-status-headers')
|
||||||
def four(req):
|
def four(req):
|
||||||
return '<p>four</p>', 202, {'Content-Type': 'text/html'}
|
return '<p>four</p>', 202, \
|
||||||
|
{'Content-Type': 'text/html; charset=UTF-8'}
|
||||||
|
|
||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
|
|
||||||
res = self._run(client.get('/body'))
|
res = self._run(client.get('/body'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'one')
|
self.assertEqual(res.text, 'one')
|
||||||
|
|
||||||
res = self._run(client.get('/body-status'))
|
res = self._run(client.get('/body-status'))
|
||||||
self.assertEqual(res.status_code, 202)
|
self.assertEqual(res.status_code, 202)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'two')
|
self.assertEqual(res.text, 'two')
|
||||||
|
|
||||||
res = self._run(client.get('/body-headers'))
|
res = self._run(client.get('/body-headers'))
|
||||||
@@ -244,7 +258,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/body-status-headers'))
|
res = self._run(client.get('/body-status-headers'))
|
||||||
self.assertEqual(res.status_code, 202)
|
self.assertEqual(res.status_code, 202)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/html')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/html; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '<p>four</p>')
|
self.assertEqual(res.text, '<p>four</p>')
|
||||||
|
|
||||||
def test_before_after_request(self):
|
def test_before_after_request(self):
|
||||||
@@ -281,7 +296,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/bar'))
|
res = self._run(client.get('/bar'))
|
||||||
self.assertEqual(res.status_code, 202)
|
self.assertEqual(res.status_code, 202)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
||||||
self.assertEqual(res.headers['X-One'], '1')
|
self.assertEqual(res.headers['X-One'], '1')
|
||||||
self.assertEqual(res.headers['X-Two'], '2')
|
self.assertEqual(res.headers['X-Two'], '2')
|
||||||
@@ -290,13 +306,47 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/baz'))
|
res = self._run(client.get('/baz'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
||||||
self.assertEqual(res.headers['X-One'], '1')
|
self.assertEqual(res.headers['X-One'], '1')
|
||||||
self.assertFalse('X-Two' in res.headers)
|
self.assertFalse('X-Two' in res.headers)
|
||||||
self.assertEqual(res.headers['Content-Length'], '3')
|
self.assertEqual(res.headers['Content-Length'], '3')
|
||||||
self.assertEqual(res.text, 'baz')
|
self.assertEqual(res.text, 'baz')
|
||||||
|
|
||||||
|
def test_after_error_request(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.after_error_request
|
||||||
|
def after_error_request_one(req, res):
|
||||||
|
res.headers['X-One'] = '1'
|
||||||
|
|
||||||
|
@app.after_error_request
|
||||||
|
def after_error_request_two(req, res):
|
||||||
|
res.set_cookie('foo', 'bar')
|
||||||
|
return res
|
||||||
|
|
||||||
|
@app.route('/foo')
|
||||||
|
def foo(req):
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
res = self._run(client.get('/foo'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertFalse('X-One' in res.headers)
|
||||||
|
self.assertFalse('Set-Cookie' in res.headers)
|
||||||
|
|
||||||
|
res = self._run(client.get('/bar'))
|
||||||
|
self.assertEqual(res.status_code, 404)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.headers['Set-Cookie'], ['foo=bar'])
|
||||||
|
self.assertEqual(res.headers['X-One'], '1')
|
||||||
|
self.assertEqual(client.cookies['foo'], 'bar')
|
||||||
|
|
||||||
def test_400(self):
|
def test_400(self):
|
||||||
self._mock()
|
self._mock()
|
||||||
|
|
||||||
@@ -309,7 +359,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
app.run()
|
app.run()
|
||||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 400 N/A\r\n'))
|
||||||
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
self.assertIn(b'Content-Length: 11\r\n', fd.response)
|
||||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\nBad request'))
|
||||||
|
|
||||||
self._unmock()
|
self._unmock()
|
||||||
@@ -330,7 +381,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
app.run()
|
app.run()
|
||||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
|
self.assertTrue(fd.response.startswith(b'HTTP/1.0 200 OK\r\n'))
|
||||||
self.assertIn(b'Content-Length: 3\r\n', fd.response)
|
self.assertIn(b'Content-Length: 3\r\n', fd.response)
|
||||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
self.assertIn(b'Content-Type: text/plain; charset=UTF-8\r\n',
|
||||||
|
fd.response)
|
||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\n400'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\n400'))
|
||||||
|
|
||||||
self._unmock()
|
self._unmock()
|
||||||
@@ -345,7 +397,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.post('/foo'))
|
res = self._run(client.post('/foo'))
|
||||||
self.assertEqual(res.status_code, 404)
|
self.assertEqual(res.status_code, 404)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Not found')
|
self.assertEqual(res.text, 'Not found')
|
||||||
|
|
||||||
def test_404_handler(self):
|
def test_404_handler(self):
|
||||||
@@ -362,7 +415,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.post('/foo'))
|
res = self._run(client.post('/foo'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '404')
|
self.assertEqual(res.text, '404')
|
||||||
|
|
||||||
def test_405(self):
|
def test_405(self):
|
||||||
@@ -375,7 +429,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.post('/foo'))
|
res = self._run(client.post('/foo'))
|
||||||
self.assertEqual(res.status_code, 405)
|
self.assertEqual(res.status_code, 405)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Not found')
|
self.assertEqual(res.text, 'Not found')
|
||||||
|
|
||||||
def test_405_handler(self):
|
def test_405_handler(self):
|
||||||
@@ -392,7 +447,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.patch('/foo'))
|
res = self._run(client.patch('/foo'))
|
||||||
self.assertEqual(res.status_code, 405)
|
self.assertEqual(res.status_code, 405)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '405')
|
self.assertEqual(res.text, '405')
|
||||||
|
|
||||||
def test_413(self):
|
def test_413(self):
|
||||||
@@ -405,7 +461,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.post('/foo', body='x' * 17000))
|
res = self._run(client.post('/foo', body='x' * 17000))
|
||||||
self.assertEqual(res.status_code, 413)
|
self.assertEqual(res.status_code, 413)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Payload too large')
|
self.assertEqual(res.text, 'Payload too large')
|
||||||
|
|
||||||
def test_413_handler(self):
|
def test_413_handler(self):
|
||||||
@@ -422,7 +479,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.post('/foo', body='x' * 17000))
|
res = self._run(client.post('/foo', body='x' * 17000))
|
||||||
self.assertEqual(res.status_code, 400)
|
self.assertEqual(res.status_code, 400)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '413')
|
self.assertEqual(res.text, '413')
|
||||||
|
|
||||||
def test_500(self):
|
def test_500(self):
|
||||||
@@ -435,7 +493,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 500)
|
self.assertEqual(res.status_code, 500)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'Internal server error')
|
self.assertEqual(res.text, 'Internal server error')
|
||||||
|
|
||||||
def test_500_handler(self):
|
def test_500_handler(self):
|
||||||
@@ -452,7 +511,8 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 501)
|
self.assertEqual(res.status_code, 501)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '501')
|
self.assertEqual(res.text, '501')
|
||||||
|
|
||||||
def test_exception_handler(self):
|
def test_exception_handler(self):
|
||||||
@@ -469,9 +529,128 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 501)
|
self.assertEqual(res.status_code, 501)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '501')
|
self.assertEqual(res.text, '501')
|
||||||
|
|
||||||
|
def test_exception_handler_parent(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(LookupError)
|
||||||
|
async def handle_lookup_error(req, exc):
|
||||||
|
return exc.__class__.__name__, 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 501)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'IndexError')
|
||||||
|
|
||||||
|
def test_exception_handler_redundant_parent(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(LookupError)
|
||||||
|
async def handle_lookup_error(req, exc):
|
||||||
|
return 'LookupError', 501
|
||||||
|
|
||||||
|
@app.errorhandler(IndexError)
|
||||||
|
async def handle_index_error(req, exc):
|
||||||
|
return 'IndexError', 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 501)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'IndexError')
|
||||||
|
|
||||||
|
def test_exception_handler_multiple_parents(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(Exception)
|
||||||
|
async def handle_generic_exception(req, exc):
|
||||||
|
return 'Exception', 501
|
||||||
|
|
||||||
|
@app.errorhandler(LookupError)
|
||||||
|
async def handle_lookup_error(req, exc):
|
||||||
|
return 'LookupError', 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 501)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'LookupError')
|
||||||
|
|
||||||
|
def test_exception_handler_no_viable_parents(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
foo = []
|
||||||
|
return foo[1]
|
||||||
|
|
||||||
|
@app.errorhandler(RuntimeError)
|
||||||
|
async def handle_runtime_error(req, exc):
|
||||||
|
return 'RuntimeError', 501
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 500)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'Internal server error')
|
||||||
|
|
||||||
|
def test_abort(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
abort(406, 'Not acceptable')
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 406)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, 'Not acceptable')
|
||||||
|
|
||||||
|
def test_abort_handler(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
abort(406)
|
||||||
|
return 'foo'
|
||||||
|
|
||||||
|
@app.errorhandler(406)
|
||||||
|
def handle_500(req):
|
||||||
|
return '406', 406
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 406)
|
||||||
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
|
self.assertEqual(res.text, '406')
|
||||||
|
|
||||||
def test_json_response(self):
|
def test_json_response(self):
|
||||||
app = Microdot()
|
app = Microdot()
|
||||||
|
|
||||||
@@ -487,12 +666,14 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/dict'))
|
res = self._run(client.get('/dict'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'application/json')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'application/json; charset=UTF-8')
|
||||||
self.assertEqual(res.json, {'foo': 'bar'})
|
self.assertEqual(res.json, {'foo': 'bar'})
|
||||||
|
|
||||||
res = self._run(client.get('/list'))
|
res = self._run(client.get('/list'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'application/json')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'application/json; charset=UTF-8')
|
||||||
self.assertEqual(res.json, ['foo', 'bar'])
|
self.assertEqual(res.json, ['foo', 'bar'])
|
||||||
|
|
||||||
def test_binary_response(self):
|
def test_binary_response(self):
|
||||||
@@ -536,5 +717,17 @@ class TestMicrodotAsync(unittest.TestCase):
|
|||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
self.assertEqual(res.headers['Content-Type'],
|
||||||
|
'text/plain; charset=UTF-8')
|
||||||
self.assertEqual(res.text, 'foobar')
|
self.assertEqual(res.text, 'foobar')
|
||||||
|
|
||||||
|
def test_already_handled_response(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index(req):
|
||||||
|
return Response.already_handled
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res, None)
|
||||||
|
|||||||
71
tests/test_microdot_asyncio_websocket.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import sys
|
||||||
|
try:
|
||||||
|
import uasyncio as asyncio
|
||||||
|
except ImportError:
|
||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from microdot_asyncio import Microdot
|
||||||
|
from microdot_asyncio_websocket import with_websocket
|
||||||
|
from microdot_asyncio_test_client import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
class TestMicrodotAsyncWebSocket(unittest.TestCase):
|
||||||
|
def _run(self, coro):
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
return loop.run_until_complete(coro)
|
||||||
|
|
||||||
|
def test_websocket_echo(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def index(req, ws):
|
||||||
|
while True:
|
||||||
|
data = await ws.receive()
|
||||||
|
await ws.send(data)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
def ws():
|
||||||
|
data = yield 'hello'
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'bye'
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'*' * 300
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'+' * 65537
|
||||||
|
results.append(data)
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.websocket('/echo', ws))
|
||||||
|
self.assertIsNone(res)
|
||||||
|
self.assertEqual(results, ['hello', b'bye', b'*' * 300, b'+' * 65537])
|
||||||
|
|
||||||
|
@unittest.skipIf(sys.implementation.name == 'micropython',
|
||||||
|
'no support for async generators in MicroPython')
|
||||||
|
def test_websocket_echo_async_client(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
async def index(req, ws):
|
||||||
|
while True:
|
||||||
|
data = await ws.receive()
|
||||||
|
await ws.send(data)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
async def ws():
|
||||||
|
data = yield 'hello'
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'bye'
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'*' * 300
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'+' * 65537
|
||||||
|
results.append(data)
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.websocket('/echo', ws))
|
||||||
|
self.assertIsNone(res)
|
||||||
|
self.assertEqual(results, ['hello', b'bye', b'*' * 300, b'+' * 65537])
|
||||||
73
tests/test_microdot_websocket.py
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import unittest
|
||||||
|
from microdot import Microdot
|
||||||
|
from microdot_websocket import with_websocket, WebSocket
|
||||||
|
from microdot_test_client import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
class TestMicrodotWebSocket(unittest.TestCase):
|
||||||
|
def test_websocket_echo(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def index(req, ws):
|
||||||
|
while True:
|
||||||
|
data = ws.receive()
|
||||||
|
ws.send(data)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
def ws():
|
||||||
|
data = yield 'hello'
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'bye'
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'*' * 300
|
||||||
|
results.append(data)
|
||||||
|
data = yield b'+' * 65537
|
||||||
|
results.append(data)
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.websocket('/echo', ws)
|
||||||
|
self.assertIsNone(res)
|
||||||
|
self.assertEqual(results, ['hello', b'bye', b'*' * 300, b'+' * 65537])
|
||||||
|
|
||||||
|
def test_bad_websocket_request(self):
|
||||||
|
app = Microdot()
|
||||||
|
|
||||||
|
@app.route('/echo')
|
||||||
|
@with_websocket
|
||||||
|
def index(req, ws):
|
||||||
|
return 'hello'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = client.get('/echo')
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
res = client.get('/echo', headers={'Connection': 'Upgrade'})
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
res = client.get('/echo', headers={'Connection': 'foo'})
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
res = client.get('/echo', headers={'Upgrade': 'websocket'})
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
res = client.get('/echo', headers={'Upgrade': 'bar'})
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
res = client.get('/echo', headers={'Connection': 'Upgrade',
|
||||||
|
'Upgrade': 'websocket'})
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
res = client.get('/echo', headers={'Sec-WebSocket-Key': 'xxx'})
|
||||||
|
self.assertEqual(res.status_code, 400)
|
||||||
|
|
||||||
|
def test_process_websocket_frame(self):
|
||||||
|
ws = WebSocket(None)
|
||||||
|
ws.closed = True
|
||||||
|
|
||||||
|
self.assertEqual(ws._process_websocket_frame(WebSocket.TEXT, b'foo'),
|
||||||
|
(None, 'foo'))
|
||||||
|
self.assertEqual(ws._process_websocket_frame(WebSocket.BINARY, b'foo'),
|
||||||
|
(None, b'foo'))
|
||||||
|
self.assertRaises(OSError, ws._process_websocket_frame,
|
||||||
|
WebSocket.CLOSE, b'')
|
||||||
|
self.assertEqual(ws._process_websocket_frame(WebSocket.PING, b'foo'),
|
||||||
|
(WebSocket.PONG, b'foo'))
|
||||||
|
self.assertEqual(ws._process_websocket_frame(WebSocket.PONG, b'foo'),
|
||||||
|
(None, None))
|
||||||
@@ -54,7 +54,7 @@ class TestMicrodotWSGI(unittest.TestCase):
|
|||||||
def start_response(status, headers):
|
def start_response(status, headers):
|
||||||
self.assertEqual(status, '200 OK')
|
self.assertEqual(status, '200 OK')
|
||||||
expected_headers = [('Content-Length', '8'),
|
expected_headers = [('Content-Length', '8'),
|
||||||
('Content-Type', 'text/plain'),
|
('Content-Type', 'text/plain; charset=UTF-8'),
|
||||||
('Set-Cookie', 'foo=foo'),
|
('Set-Cookie', 'foo=foo'),
|
||||||
('Set-Cookie', 'bar=bar; HttpOnly')]
|
('Set-Cookie', 'bar=bar; HttpOnly')]
|
||||||
self.assertEqual(len(headers), len(expected_headers))
|
self.assertEqual(len(headers), len(expected_headers))
|
||||||
|
|||||||
@@ -1,31 +1,60 @@
|
|||||||
import unittest
|
import unittest
|
||||||
from microdot import MultiDict
|
from microdot import MultiDict, NoCaseDict
|
||||||
|
|
||||||
|
|
||||||
class TestMultiDict(unittest.TestCase):
|
class TestMultiDict(unittest.TestCase):
|
||||||
def test_multidict(self):
|
def test_multidict(self):
|
||||||
d = MultiDict()
|
d = MultiDict()
|
||||||
|
|
||||||
assert dict(d) == {}
|
self.assertEqual(dict(d), {})
|
||||||
assert d.get('zero') is None
|
self.assertIsNone(d.get('zero'))
|
||||||
assert d.get('zero', default=0) == 0
|
self.assertEqual(d.get('zero', default=0), 0)
|
||||||
assert d.getlist('zero') == []
|
self.assertEqual(d.getlist('zero'), [])
|
||||||
assert d.getlist('zero', type=int) == []
|
self.assertEqual(d.getlist('zero', type=int), [])
|
||||||
|
|
||||||
d['one'] = 1
|
d['one'] = 1
|
||||||
assert d['one'] == 1
|
self.assertEqual(d['one'], 1)
|
||||||
assert d.get('one') == 1
|
self.assertEqual(d.get('one'), 1)
|
||||||
assert d.get('one', default=2) == 1
|
self.assertEqual(d.get('one', default=2), 1)
|
||||||
assert d.get('one', type=int) == 1
|
self.assertEqual(d.get('one', type=int), 1)
|
||||||
assert d.get('one', type=str) == '1'
|
self.assertEqual(d.get('one', type=str), '1')
|
||||||
|
|
||||||
d['two'] = 1
|
d['two'] = 1
|
||||||
d['two'] = 2
|
d['two'] = 2
|
||||||
assert d['two'] == 1
|
self.assertEqual(d['two'], 1)
|
||||||
assert d.get('two') == 1
|
self.assertEqual(d.get('two'), 1)
|
||||||
assert d.get('two', default=2) == 1
|
self.assertEqual(d.get('two', default=2), 1)
|
||||||
assert d.get('two', type=int) == 1
|
self.assertEqual(d.get('two', type=int), 1)
|
||||||
assert d.get('two', type=str) == '1'
|
self.assertEqual(d.get('two', type=str), '1')
|
||||||
assert d.getlist('two') == [1, 2]
|
self.assertEqual(d.getlist('two'), [1, 2])
|
||||||
assert d.getlist('two', type=int) == [1, 2]
|
self.assertEqual(d.getlist('two', type=int), [1, 2])
|
||||||
assert d.getlist('two', type=str) == ['1', '2']
|
self.assertEqual(d.getlist('two', type=str), ['1', '2'])
|
||||||
|
|
||||||
|
def test_case_insensitive_dict(self):
|
||||||
|
d = NoCaseDict()
|
||||||
|
|
||||||
|
d['One'] = 1
|
||||||
|
d['one'] = 2
|
||||||
|
d['ONE'] = 3
|
||||||
|
d['One'] = 4
|
||||||
|
d['two'] = 5
|
||||||
|
self.assertEqual(d['one'], 4)
|
||||||
|
self.assertEqual(d['One'], 4)
|
||||||
|
self.assertEqual(d['ONE'], 4)
|
||||||
|
self.assertEqual(d['onE'], 4)
|
||||||
|
self.assertEqual(d['two'], 5)
|
||||||
|
self.assertEqual(d['tWO'], 5)
|
||||||
|
self.assertEqual(d.get('one'), 4)
|
||||||
|
self.assertEqual(d.get('One'), 4)
|
||||||
|
self.assertEqual(d.get('ONE'), 4)
|
||||||
|
self.assertEqual(d.get('onE'), 4)
|
||||||
|
self.assertEqual(d.get('two'), 5)
|
||||||
|
self.assertEqual(d.get('tWO'), 5)
|
||||||
|
self.assertIn(('One', 4), list(d.items()))
|
||||||
|
self.assertIn(('two', 5), list(d.items()))
|
||||||
|
self.assertIn(4, list(d.values()))
|
||||||
|
self.assertIn(5, list(d.values()))
|
||||||
|
|
||||||
|
del d['oNE']
|
||||||
|
self.assertEqual(list(d.items()), [('two', 5)])
|
||||||
|
self.assertEqual(list(d.values()), [5])
|
||||||
|
|||||||