Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53287217ae | ||
|
|
6ffb8a8fe9 | ||
|
|
0151611fc8 | ||
|
|
4204db61e5 | ||
|
|
12438743a8 | ||
|
|
7cbb1edf59 | ||
|
|
dac6df7a7a | ||
|
|
5d6e838f3c | ||
|
|
563bfdc8f5 | ||
|
|
679d8e63b8 | ||
|
|
4cb155ee41 | ||
|
|
dea79c5ce2 | ||
|
|
6b1fd61917 | ||
|
|
f6876c0d15 | ||
|
|
904d5fcaa2 | ||
|
|
a0ea439def | ||
|
|
a1801d9a53 | ||
|
|
14f2c9d345 | ||
|
|
d0a4cf8fa7 | ||
|
|
901f4e55b8 |
1
.github/workflows/tests.yml
vendored
1
.github/workflows/tests.yml
vendored
@@ -64,6 +64,7 @@ jobs:
|
||||
with:
|
||||
files: ./coverage.xml
|
||||
fail_ci_if_error: true
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
benchmark:
|
||||
name: benchmark
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
15
CHANGES.md
15
CHANGES.md
@@ -1,5 +1,20 @@
|
||||
# Microdot change log
|
||||
|
||||
**Release 2.0.6** - 2024-06-18
|
||||
|
||||
- Add event ID to the SSE implementation [#213](https://github.com/miguelgrinberg/microdot/issues/213) ([commit](https://github.com/miguelgrinberg/microdot/commit/904d5fcaa2d19d939a719b8e68c4dee3eb470739)) (thanks **Hamsanger**!)
|
||||
- Configurable session cookie options [#242](https://github.com/miguelgrinberg/microdot/issues/242) ([commit](https://github.com/miguelgrinberg/microdot/commit/0151611fc84fec450820d673f4c4d70c32c990a7))
|
||||
- Improved cookie support in the test client ([commit](https://github.com/miguelgrinberg/microdot/commit/4cb155ee411dc2d9c9f15714cb32b25ba79b156a))
|
||||
- Cookie path support in session extension and test client ([commit](https://github.com/miguelgrinberg/microdot/commit/6ffb8a8fe920111c4d8c16e98715a0d5ee2d1da3))
|
||||
- Refactor `Session` class to make it more reusable ([commit](https://github.com/miguelgrinberg/microdot/commit/dea79c5ce224dec7858ffef45a42bed442fd3a5a))
|
||||
- Use `@functools.wraps` on decorated functions ([commit](https://github.com/miguelgrinberg/microdot/commit/f6876c0d154adcae96098405fb6a1fdf1ea4ec28))
|
||||
- Removed outdated import from documentation [#216](https://github.com/miguelgrinberg/microdot/issues/216) ([commit](https://github.com/miguelgrinberg/microdot/commit/6b1fd6191702e7a9ad934fddfcdd0a3cebea7c94)) (thanks **Carlo Colombo**!)
|
||||
- Add roadmap details to readme ([commit](https://github.com/miguelgrinberg/microdot/commit/a0ea439def238084c4d68309c0992b66ffd28ad6))
|
||||
|
||||
**Release 2.0.5** - 2024-03-09
|
||||
|
||||
- Correct handling of 0 as an integer argument (regression from #207) [#212](https://github.com/miguelgrinberg/microdot/issues/212) ([commit](https://github.com/miguelgrinberg/microdot/commit/d0a4cf8fa7dfb1da7466157b18d3329a8cf9a5df))
|
||||
|
||||
**Release 2.0.4** - 2024-02-20
|
||||
|
||||
- Do not use regexes for parsing simple URLs [#207](https://github.com/miguelgrinberg/microdot/issues/207) ([commit #1](https://github.com/miguelgrinberg/microdot/commit/38262c56d34784401659639b482a4a1224e1e59a) [commit #2](https://github.com/miguelgrinberg/microdot/commit/f6cba2c0f7e18e2f32b5adb779fb037b6c473eab))
|
||||
|
||||
27
README.md
27
README.md
@@ -32,10 +32,25 @@ describes the backwards incompatible changes that were made.
|
||||
|
||||
## Resources
|
||||
|
||||
- Documentation
|
||||
- [Stable](https://microdot.readthedocs.io/en/stable/)
|
||||
- [Latest](https://microdot.readthedocs.io/en/latest/)
|
||||
- Still using version 1?
|
||||
- [Code](https://github.com/miguelgrinberg/microdot/tree/v1)
|
||||
- [Documentation](https://microdot.readthedocs.io/en/v1/)
|
||||
- [Change Log](https://github.com/miguelgrinberg/microdot/blob/main/CHANGES.md)
|
||||
- Documentation
|
||||
- [Latest](https://microdot.readthedocs.io/en/latest/)
|
||||
- [Stable (v2)](https://microdot.readthedocs.io/en/stable/)
|
||||
- [Legacy (v1)](https://microdot.readthedocs.io/en/v1/) ([Code](https://github.com/miguelgrinberg/microdot/tree/v1))
|
||||
|
||||
## Roadmap
|
||||
|
||||
The following features are planned for future releases of Microdot, both for
|
||||
MicroPython and CPython:
|
||||
|
||||
- Support for forms encoded in `multipart/form-data` format
|
||||
- Authentication support, similar to [Flask-Login](https://github.com/maxcountryman/flask-login) for Flask
|
||||
- OpenAPI integration, similar to [APIFairy](https://github.com/miguelgrinberg/apifairy) for Flask
|
||||
|
||||
In addition to the above, the following extensions are also under consideration,
|
||||
but only for CPython:
|
||||
|
||||
- Database integration through [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy)
|
||||
- Socket.IO support through [python-socketio](https://github.com/miguelgrinberg/python-socketio)
|
||||
|
||||
Do you have other ideas to propose? Let's [discuss them](https://github.com/miguelgrinberg/microdot/discussions/new?category=ideas)!
|
||||
|
||||
@@ -32,7 +32,7 @@ flask==3.0.0
|
||||
# via
|
||||
# -r requirements.in
|
||||
# quart
|
||||
gunicorn==21.2.0
|
||||
gunicorn==22.0.0
|
||||
# via -r requirements.in
|
||||
h11==0.14.0
|
||||
# via
|
||||
@@ -49,7 +49,7 @@ hypercorn==0.15.0
|
||||
# via quart
|
||||
hyperframe==6.0.1
|
||||
# via h2
|
||||
idna==3.6
|
||||
idna==3.7
|
||||
# via
|
||||
# anyio
|
||||
# requests
|
||||
@@ -57,7 +57,7 @@ itsdangerous==2.1.2
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
jinja2==3.1.3
|
||||
jinja2==3.1.4
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
@@ -84,7 +84,7 @@ pyproject-hooks==1.0.0
|
||||
# via build
|
||||
quart==0.19.4
|
||||
# via -r requirements.in
|
||||
requests==2.31.0
|
||||
requests==2.32.0
|
||||
# via -r requirements.in
|
||||
sniffio==1.3.0
|
||||
# via anyio
|
||||
@@ -99,7 +99,7 @@ urllib3==2.1.0
|
||||
# via requests
|
||||
uvicorn==0.24.0.post1
|
||||
# via -r requirements.in
|
||||
werkzeug==3.0.1
|
||||
werkzeug==3.0.3
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "microdot"
|
||||
version = "2.0.4"
|
||||
version = "2.0.6"
|
||||
authors = [
|
||||
{ name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" },
|
||||
]
|
||||
@@ -26,6 +26,7 @@ Homepage = "https://github.com/miguelgrinberg/microdot"
|
||||
[project.optional-dependencies]
|
||||
docs = [
|
||||
"sphinx",
|
||||
"pyjwt"
|
||||
]
|
||||
|
||||
[tool.setuptools]
|
||||
|
||||
8
src/microdot/helpers.py
Normal file
8
src/microdot/helpers.py
Normal file
@@ -0,0 +1,8 @@
|
||||
try:
|
||||
from functools import wraps
|
||||
except ImportError: # pragma: no cover
|
||||
# MicroPython does not currently implement functools.wraps
|
||||
def wraps(wrapped):
|
||||
def _(wrapper):
|
||||
return wrapper
|
||||
return _
|
||||
@@ -598,7 +598,7 @@ class Response:
|
||||
else: # pragma: no cover
|
||||
http_cookie += '; Expires=' + time.strftime(
|
||||
'%a, %d %b %Y %H:%M:%S GMT', expires.timetuple())
|
||||
if max_age:
|
||||
if max_age is not None:
|
||||
http_cookie += '; Max-Age=' + str(max_age)
|
||||
if secure:
|
||||
http_cookie += '; Secure'
|
||||
@@ -616,10 +616,10 @@ class Response:
|
||||
|
||||
:param cookie: The cookie's name.
|
||||
:param kwargs: Any cookie opens and flags supported by
|
||||
``set_cookie()`` except ``expires``.
|
||||
``set_cookie()`` except ``expires`` and ``max_age``.
|
||||
"""
|
||||
self.set_cookie(cookie, '', expires='Thu, 01 Jan 1970 00:00:01 GMT',
|
||||
**kwargs)
|
||||
max_age=0, **kwargs)
|
||||
|
||||
def complete(self):
|
||||
if isinstance(self.body, bytes) and \
|
||||
@@ -862,8 +862,6 @@ class URLPattern():
|
||||
if arg is None:
|
||||
return
|
||||
if 'name' in segment:
|
||||
if not arg:
|
||||
return
|
||||
args[segment['name']] = arg
|
||||
if path is not None:
|
||||
return
|
||||
@@ -879,6 +877,8 @@ class URLPattern():
|
||||
|
||||
def _string_segment(self, value):
|
||||
s = value.split('/', 1)
|
||||
if len(s[0]) == 0:
|
||||
return None, None
|
||||
return s[0], s[1] if len(s) > 1 else None
|
||||
|
||||
def _int_segment(self, value):
|
||||
@@ -1191,7 +1191,7 @@ class Microdot:
|
||||
Example::
|
||||
|
||||
import asyncio
|
||||
from microdot_asyncio import Microdot
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@@ -1268,7 +1268,7 @@ class Microdot:
|
||||
|
||||
Example::
|
||||
|
||||
from microdot_asyncio import Microdot
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import jwt
|
||||
from microdot.microdot import invoke_handler
|
||||
|
||||
secret_key = None
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class SessionDict(dict):
|
||||
@@ -30,14 +29,21 @@ class Session:
|
||||
"""
|
||||
secret_key = None
|
||||
|
||||
def __init__(self, app=None, secret_key=None):
|
||||
def __init__(self, app=None, secret_key=None, cookie_options=None):
|
||||
self.secret_key = secret_key
|
||||
self.cookie_options = cookie_options or {}
|
||||
if app is not None:
|
||||
self.initialize(app)
|
||||
|
||||
def initialize(self, app, secret_key=None):
|
||||
def initialize(self, app, secret_key=None, cookie_options=None):
|
||||
if secret_key is not None:
|
||||
self.secret_key = secret_key
|
||||
if cookie_options is not None:
|
||||
self.cookie_options = cookie_options
|
||||
if 'path' not in self.cookie_options:
|
||||
self.cookie_options['path'] = '/'
|
||||
if 'http_only' not in self.cookie_options:
|
||||
self.cookie_options['http_only'] = True
|
||||
app._session = self
|
||||
|
||||
def get(self, request):
|
||||
@@ -57,13 +63,7 @@ class Session:
|
||||
if session is None:
|
||||
request.g._session = SessionDict(request, {})
|
||||
return request.g._session
|
||||
try:
|
||||
session = jwt.decode(session, self.secret_key,
|
||||
algorithms=['HS256'])
|
||||
except jwt.exceptions.PyJWTError: # pragma: no cover
|
||||
request.g._session = SessionDict(request, {})
|
||||
else:
|
||||
request.g._session = SessionDict(request, session)
|
||||
request.g._session = SessionDict(request, self.decode(session))
|
||||
return request.g._session
|
||||
|
||||
def update(self, request, session):
|
||||
@@ -89,12 +89,12 @@ class Session:
|
||||
if not self.secret_key:
|
||||
raise ValueError('The session secret key is not configured')
|
||||
|
||||
encoded_session = jwt.encode(session, self.secret_key,
|
||||
algorithm='HS256')
|
||||
encoded_session = self.encode(session)
|
||||
|
||||
@request.after_request
|
||||
def _update_session(request, response):
|
||||
response.set_cookie('session', encoded_session, http_only=True)
|
||||
response.set_cookie('session', encoded_session,
|
||||
**self.cookie_options)
|
||||
return response
|
||||
|
||||
def delete(self, request):
|
||||
@@ -117,10 +117,21 @@ class Session:
|
||||
"""
|
||||
@request.after_request
|
||||
def _delete_session(request, response):
|
||||
response.set_cookie('session', '', http_only=True,
|
||||
expires='Thu, 01 Jan 1970 00:00:01 GMT')
|
||||
response.delete_cookie('session', **self.cookie_options)
|
||||
return response
|
||||
|
||||
def encode(self, payload, secret_key=None):
|
||||
return jwt.encode(payload, secret_key or self.secret_key,
|
||||
algorithm='HS256')
|
||||
|
||||
def decode(self, session, secret_key=None):
|
||||
try:
|
||||
payload = jwt.decode(session, secret_key or self.secret_key,
|
||||
algorithms=['HS256'])
|
||||
except jwt.exceptions.PyJWTError: # pragma: no cover
|
||||
return {}
|
||||
return payload
|
||||
|
||||
|
||||
def with_session(f):
|
||||
"""Decorator that passes the user session to the route handler.
|
||||
@@ -136,13 +147,9 @@ def with_session(f):
|
||||
Note that the decorator does not save the session. To update the session,
|
||||
call the :func:`session.save() <microdot.session.SessionDict.save>` method.
|
||||
"""
|
||||
@wraps(f)
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
return await invoke_handler(
|
||||
f, request, request.app._session.get(request), *args, **kwargs)
|
||||
|
||||
for attr in ['__name__', '__doc__', '__module__', '__qualname__']:
|
||||
try:
|
||||
setattr(wrapper, attr, getattr(f, attr))
|
||||
except AttributeError: # pragma: no cover
|
||||
pass
|
||||
return wrapper
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class SSE:
|
||||
@@ -12,7 +13,7 @@ class SSE:
|
||||
self.event = asyncio.Event()
|
||||
self.queue = []
|
||||
|
||||
async def send(self, data, event=None):
|
||||
async def send(self, data, event=None, event_id=None):
|
||||
"""Send an event to the client.
|
||||
|
||||
:param data: the data to send. It can be given as a string, bytes, dict
|
||||
@@ -20,6 +21,8 @@ class SSE:
|
||||
Any other types are converted to string before sending.
|
||||
:param event: an optional event name, to send along with the data. If
|
||||
given, it must be a string.
|
||||
:param event_id: an optional event id, to send along with the data. If
|
||||
given, it must be a string.
|
||||
"""
|
||||
if isinstance(data, (dict, list)):
|
||||
data = json.dumps(data).encode()
|
||||
@@ -28,6 +31,8 @@ class SSE:
|
||||
elif not isinstance(data, bytes):
|
||||
data = str(data).encode()
|
||||
data = b'data: ' + data + b'\n\n'
|
||||
if event_id:
|
||||
data = b'id: ' + event_id.encode() + b'\n' + data
|
||||
if event:
|
||||
data = b'event: ' + event.encode() + b'\n' + data
|
||||
self.queue.append(data)
|
||||
@@ -99,6 +104,7 @@ def with_sse(f):
|
||||
# send a named event
|
||||
await sse.send('hello', event='greeting')
|
||||
"""
|
||||
@wraps(f)
|
||||
async def sse_handler(request, *args, **kwargs):
|
||||
return sse_response(request, f, *args, **kwargs)
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ class TestClient:
|
||||
The following example shows how to create a test client for an application
|
||||
and send a test request::
|
||||
|
||||
from microdot_asyncio import Microdot
|
||||
from microdot import Microdot
|
||||
|
||||
app = Microdot()
|
||||
|
||||
@@ -112,9 +112,13 @@ class TestClient:
|
||||
headers['Host'] = 'example.com:1234'
|
||||
return body, headers
|
||||
|
||||
def _process_cookies(self, headers):
|
||||
def _process_cookies(self, path, headers):
|
||||
cookies = ''
|
||||
for name, value in self.cookies.items():
|
||||
if isinstance(value, tuple):
|
||||
value, cookie_path = value
|
||||
if not path.startswith(cookie_path):
|
||||
continue
|
||||
if cookies:
|
||||
cookies += '; '
|
||||
cookies += name + '=' + value
|
||||
@@ -123,7 +127,7 @@ class TestClient:
|
||||
headers['Cookie'] += '; ' + cookies
|
||||
else:
|
||||
headers['Cookie'] = cookies
|
||||
return cookies, headers
|
||||
return headers
|
||||
|
||||
def _render_request(self, method, path, headers, body):
|
||||
request_bytes = '{method} {path} HTTP/1.0\n'.format(
|
||||
@@ -139,26 +143,45 @@ class TestClient:
|
||||
for cookie in cookies:
|
||||
cookie_name, cookie_value = cookie.split('=', 1)
|
||||
cookie_options = cookie_value.split(';')
|
||||
path = '/'
|
||||
delete = False
|
||||
for option in cookie_options[1:]:
|
||||
if option.strip().lower().startswith('expires='):
|
||||
_, e = option.strip().split('=', 1)
|
||||
option = option.strip().lower()
|
||||
if option.startswith(
|
||||
'max-age='): # pragma: no cover
|
||||
_, age = option.split('=', 1)
|
||||
try:
|
||||
age = int(age)
|
||||
except ValueError: # pragma: no cover
|
||||
age = 0
|
||||
if age <= 0:
|
||||
delete = True
|
||||
elif option.startswith('expires='):
|
||||
_, e = option.split('=', 1)
|
||||
# this is a very limited parser for cookie expiry
|
||||
# that only detects a cookie deletion request when
|
||||
# the date is 1/1/1970
|
||||
if '1 jan 1970' in e.lower(): # pragma: no branch
|
||||
delete = True
|
||||
break
|
||||
elif option.startswith('path='):
|
||||
_, path = option.split('=', 1)
|
||||
if delete:
|
||||
if cookie_name in self.cookies: # pragma: no branch
|
||||
cookie_path = self.cookies[cookie_name][1] \
|
||||
if isinstance(self.cookies[cookie_name], tuple) \
|
||||
else '/'
|
||||
if path == cookie_path:
|
||||
del self.cookies[cookie_name]
|
||||
else:
|
||||
if path == '/':
|
||||
self.cookies[cookie_name] = cookie_options[0]
|
||||
else:
|
||||
self.cookies[cookie_name] = (cookie_options[0], path)
|
||||
|
||||
async def request(self, method, path, headers=None, body=None, sock=None):
|
||||
headers = headers or {}
|
||||
body, headers = self._process_body(body, headers)
|
||||
cookies, headers = self._process_cookies(headers)
|
||||
headers = self._process_cookies(path, headers)
|
||||
request_bytes = self._render_request(method, path, headers, body)
|
||||
if sock:
|
||||
reader = sock[0]
|
||||
|
||||
@@ -2,6 +2,7 @@ import binascii
|
||||
import hashlib
|
||||
from microdot import Request, Response
|
||||
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class WebSocketError(Exception):
|
||||
@@ -192,6 +193,7 @@ async def websocket_upgrade(request):
|
||||
|
||||
|
||||
def websocket_wrapper(f, upgrade_function):
|
||||
@wraps(f)
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
ws = await upgrade_function(request)
|
||||
try:
|
||||
|
||||
@@ -203,6 +203,7 @@ class TestMicrodot(unittest.TestCase):
|
||||
req.cookies['one'] + req.cookies['two'] + req.cookies['three'])
|
||||
res.set_cookie('four', '4')
|
||||
res.delete_cookie('two', path='/')
|
||||
res.delete_cookie('one', path='/bad')
|
||||
return res
|
||||
|
||||
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
||||
|
||||
@@ -193,6 +193,7 @@ class TestResponse(unittest.TestCase):
|
||||
expires='Tue, 05 Nov 2019 02:23:54 GMT', max_age=123,
|
||||
secure=True, http_only=True)
|
||||
res.delete_cookie('foo8', http_only=True)
|
||||
res.delete_cookie('foo9', path='/s')
|
||||
self.assertEqual(res.headers, {'Set-Cookie': [
|
||||
'foo1=bar1',
|
||||
'foo2=bar2; Path=/; Partitioned',
|
||||
@@ -203,7 +204,10 @@ class TestResponse(unittest.TestCase):
|
||||
'foo7=bar7; Path=/foo; Domain=example.com:1234; '
|
||||
'Expires=Tue, 05 Nov 2019 02:23:54 GMT; Max-Age=123; Secure; '
|
||||
'HttpOnly',
|
||||
'foo8=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; HttpOnly',
|
||||
('foo8=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=0; '
|
||||
'HttpOnly'),
|
||||
('foo9=; Path=/s; Expires=Thu, 01 Jan 1970 00:00:01 GMT; '
|
||||
'Max-Age=0'),
|
||||
]})
|
||||
|
||||
def test_redirect(self):
|
||||
|
||||
@@ -82,3 +82,77 @@ class TestSession(unittest.TestCase):
|
||||
|
||||
res = self._run(client.get('/'))
|
||||
self.assertEqual(res.status_code, 200)
|
||||
|
||||
def test_session_default_path(self):
|
||||
app = Microdot()
|
||||
Session(app, secret_key='some-other-secret')
|
||||
client = TestClient(app)
|
||||
|
||||
@app.get('/')
|
||||
@with_session
|
||||
def index(req, session):
|
||||
session['foo'] = 'bar'
|
||||
session.save()
|
||||
return ''
|
||||
|
||||
@app.get('/child')
|
||||
@with_session
|
||||
def child(req, session):
|
||||
return str(session.get('foo'))
|
||||
|
||||
@app.get('/delete')
|
||||
@with_session
|
||||
def delete(req, session):
|
||||
session.delete()
|
||||
return ''
|
||||
|
||||
res = self._run(client.get('/'))
|
||||
self.assertEqual(res.status_code, 200)
|
||||
res = self._run(client.get('/child'))
|
||||
self.assertEqual(res.text, 'bar')
|
||||
res = self._run(client.get('/delete'))
|
||||
res = self._run(client.get('/child'))
|
||||
self.assertEqual(res.text, 'None')
|
||||
|
||||
def test_session_custom_path(self):
|
||||
app = Microdot()
|
||||
session_ext = Session()
|
||||
session_ext.initialize(app, secret_key='some-other-secret',
|
||||
cookie_options={'path': '/child',
|
||||
'http_only': False})
|
||||
client = TestClient(app)
|
||||
|
||||
@app.get('/')
|
||||
@with_session
|
||||
def index(req, session):
|
||||
return str(session.get('foo'))
|
||||
|
||||
@app.get('/child')
|
||||
@with_session
|
||||
def child(req, session):
|
||||
session['foo'] = 'bar'
|
||||
session.save()
|
||||
return ''
|
||||
|
||||
@app.get('/child/foo')
|
||||
@with_session
|
||||
def foo(req, session):
|
||||
return str(session.get('foo'))
|
||||
|
||||
@app.get('/child/delete')
|
||||
@with_session
|
||||
def delete(req, session):
|
||||
session.delete()
|
||||
return ''
|
||||
|
||||
res = self._run(client.get('/child'))
|
||||
self.assertEqual(res.status_code, 200)
|
||||
res = self._run(client.get('/'))
|
||||
self.assertEqual(res.text, 'None')
|
||||
res = self._run(client.get('/child/foo'))
|
||||
self.assertEqual(res.text, 'bar')
|
||||
res = self._run(client.get('/child/delete'))
|
||||
res = self._run(client.get('/'))
|
||||
self.assertEqual(res.text, 'None')
|
||||
res = self._run(client.get('/child/foo'))
|
||||
self.assertEqual(res.text, 'None')
|
||||
|
||||
@@ -23,6 +23,8 @@ class TestWebSocket(unittest.TestCase):
|
||||
async def handle_sse(request, sse):
|
||||
await sse.send('foo')
|
||||
await sse.send('bar', event='test')
|
||||
await sse.send('bar', event='test', event_id='id42')
|
||||
await sse.send('bar', event_id='id42')
|
||||
await sse.send({'foo': 'bar'})
|
||||
await sse.send([42, 'foo', 'bar'])
|
||||
await sse.send(ValueError('foo'))
|
||||
@@ -34,6 +36,8 @@ class TestWebSocket(unittest.TestCase):
|
||||
self.assertEqual(response.headers['Content-Type'], 'text/event-stream')
|
||||
self.assertEqual(response.text, ('data: foo\n\n'
|
||||
'event: test\ndata: bar\n\n'
|
||||
'event: test\nid: id42\ndata: bar\n\n'
|
||||
'id: id42\ndata: bar\n\n'
|
||||
'data: {"foo": "bar"}\n\n'
|
||||
'data: [42, "foo", "bar"]\n\n'
|
||||
'data: foo\n\n'
|
||||
|
||||
@@ -26,10 +26,14 @@ class TestURLPattern(unittest.TestCase):
|
||||
p = URLPattern('/<arg>')
|
||||
self.assertEqual(p.match('/foo'), {'arg': 'foo'})
|
||||
self.assertIsNone(p.match('/'))
|
||||
self.assertIsNone(p.match('//'))
|
||||
self.assertIsNone(p.match(''))
|
||||
self.assertIsNone(p.match('foo/'))
|
||||
self.assertIsNone(p.match('/foo/'))
|
||||
self.assertIsNone(p.match('//foo/'))
|
||||
self.assertIsNone(p.match('/foo//'))
|
||||
self.assertIsNone(p.match('/foo/bar'))
|
||||
self.assertIsNone(p.match('/foo//bar'))
|
||||
|
||||
p = URLPattern('/<arg>/')
|
||||
self.assertEqual(p.match('/foo/'), {'arg': 'foo'})
|
||||
@@ -64,6 +68,8 @@ class TestURLPattern(unittest.TestCase):
|
||||
def test_int_argument(self):
|
||||
p = URLPattern('/users/<int:id>')
|
||||
self.assertEqual(p.match('/users/123'), {'id': 123})
|
||||
self.assertEqual(p.match('/users/-123'), {'id': -123})
|
||||
self.assertEqual(p.match('/users/0'), {'id': 0})
|
||||
self.assertIsNone(p.match('/users/'))
|
||||
self.assertIsNone(p.match('/users/abc'))
|
||||
self.assertIsNone(p.match('/users/123abc'))
|
||||
|
||||
Reference in New Issue
Block a user