Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53287217ae | ||
|
|
6ffb8a8fe9 | ||
|
|
0151611fc8 | ||
|
|
4204db61e5 | ||
|
|
12438743a8 | ||
|
|
7cbb1edf59 | ||
|
|
dac6df7a7a | ||
|
|
5d6e838f3c | ||
|
|
563bfdc8f5 | ||
|
|
679d8e63b8 | ||
|
|
4cb155ee41 | ||
|
|
dea79c5ce2 | ||
|
|
6b1fd61917 | ||
|
|
f6876c0d15 | ||
|
|
904d5fcaa2 | ||
|
|
a0ea439def | ||
|
|
a1801d9a53 |
1
.github/workflows/tests.yml
vendored
1
.github/workflows/tests.yml
vendored
@@ -64,6 +64,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
files: ./coverage.xml
|
files: ./coverage.xml
|
||||||
fail_ci_if_error: true
|
fail_ci_if_error: true
|
||||||
|
token: ${{ secrets.CODECOV_TOKEN }}
|
||||||
benchmark:
|
benchmark:
|
||||||
name: benchmark
|
name: benchmark
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
11
CHANGES.md
11
CHANGES.md
@@ -1,5 +1,16 @@
|
|||||||
# Microdot change log
|
# 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
|
**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))
|
- 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))
|
||||||
|
|||||||
27
README.md
27
README.md
@@ -32,10 +32,25 @@ describes the backwards incompatible changes that were made.
|
|||||||
|
|
||||||
## Resources
|
## 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)
|
- [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
|
# via
|
||||||
# -r requirements.in
|
# -r requirements.in
|
||||||
# quart
|
# quart
|
||||||
gunicorn==21.2.0
|
gunicorn==22.0.0
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
h11==0.14.0
|
h11==0.14.0
|
||||||
# via
|
# via
|
||||||
@@ -49,7 +49,7 @@ hypercorn==0.15.0
|
|||||||
# via quart
|
# via quart
|
||||||
hyperframe==6.0.1
|
hyperframe==6.0.1
|
||||||
# via h2
|
# via h2
|
||||||
idna==3.6
|
idna==3.7
|
||||||
# via
|
# via
|
||||||
# anyio
|
# anyio
|
||||||
# requests
|
# requests
|
||||||
@@ -57,7 +57,7 @@ itsdangerous==2.1.2
|
|||||||
# via
|
# via
|
||||||
# flask
|
# flask
|
||||||
# quart
|
# quart
|
||||||
jinja2==3.1.3
|
jinja2==3.1.4
|
||||||
# via
|
# via
|
||||||
# flask
|
# flask
|
||||||
# quart
|
# quart
|
||||||
@@ -84,7 +84,7 @@ pyproject-hooks==1.0.0
|
|||||||
# via build
|
# via build
|
||||||
quart==0.19.4
|
quart==0.19.4
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
requests==2.31.0
|
requests==2.32.0
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
sniffio==1.3.0
|
sniffio==1.3.0
|
||||||
# via anyio
|
# via anyio
|
||||||
@@ -99,7 +99,7 @@ urllib3==2.1.0
|
|||||||
# via requests
|
# via requests
|
||||||
uvicorn==0.24.0.post1
|
uvicorn==0.24.0.post1
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
werkzeug==3.0.1
|
werkzeug==3.0.3
|
||||||
# via
|
# via
|
||||||
# flask
|
# flask
|
||||||
# quart
|
# quart
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "microdot"
|
name = "microdot"
|
||||||
version = "2.0.5"
|
version = "2.0.6"
|
||||||
authors = [
|
authors = [
|
||||||
{ name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" },
|
{ name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" },
|
||||||
]
|
]
|
||||||
@@ -26,6 +26,7 @@ Homepage = "https://github.com/miguelgrinberg/microdot"
|
|||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
docs = [
|
docs = [
|
||||||
"sphinx",
|
"sphinx",
|
||||||
|
"pyjwt"
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.setuptools]
|
[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
|
else: # pragma: no cover
|
||||||
http_cookie += '; Expires=' + time.strftime(
|
http_cookie += '; Expires=' + time.strftime(
|
||||||
'%a, %d %b %Y %H:%M:%S GMT', expires.timetuple())
|
'%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)
|
http_cookie += '; Max-Age=' + str(max_age)
|
||||||
if secure:
|
if secure:
|
||||||
http_cookie += '; Secure'
|
http_cookie += '; Secure'
|
||||||
@@ -616,10 +616,10 @@ class Response:
|
|||||||
|
|
||||||
:param cookie: The cookie's name.
|
:param cookie: The cookie's name.
|
||||||
:param kwargs: Any cookie opens and flags supported by
|
: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',
|
self.set_cookie(cookie, '', expires='Thu, 01 Jan 1970 00:00:01 GMT',
|
||||||
**kwargs)
|
max_age=0, **kwargs)
|
||||||
|
|
||||||
def complete(self):
|
def complete(self):
|
||||||
if isinstance(self.body, bytes) and \
|
if isinstance(self.body, bytes) and \
|
||||||
@@ -1191,7 +1191,7 @@ class Microdot:
|
|||||||
Example::
|
Example::
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from microdot_asyncio import Microdot
|
from microdot import Microdot
|
||||||
|
|
||||||
app = Microdot()
|
app = Microdot()
|
||||||
|
|
||||||
@@ -1268,7 +1268,7 @@ class Microdot:
|
|||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
from microdot_asyncio import Microdot
|
from microdot import Microdot
|
||||||
|
|
||||||
app = Microdot()
|
app = Microdot()
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import jwt
|
import jwt
|
||||||
from microdot.microdot import invoke_handler
|
from microdot.microdot import invoke_handler
|
||||||
|
from microdot.helpers import wraps
|
||||||
secret_key = None
|
|
||||||
|
|
||||||
|
|
||||||
class SessionDict(dict):
|
class SessionDict(dict):
|
||||||
@@ -30,14 +29,21 @@ class Session:
|
|||||||
"""
|
"""
|
||||||
secret_key = None
|
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.secret_key = secret_key
|
||||||
|
self.cookie_options = cookie_options or {}
|
||||||
if app is not None:
|
if app is not None:
|
||||||
self.initialize(app)
|
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:
|
if secret_key is not None:
|
||||||
self.secret_key = secret_key
|
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
|
app._session = self
|
||||||
|
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
@@ -57,13 +63,7 @@ class Session:
|
|||||||
if session is None:
|
if session is None:
|
||||||
request.g._session = SessionDict(request, {})
|
request.g._session = SessionDict(request, {})
|
||||||
return request.g._session
|
return request.g._session
|
||||||
try:
|
request.g._session = SessionDict(request, self.decode(session))
|
||||||
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)
|
|
||||||
return request.g._session
|
return request.g._session
|
||||||
|
|
||||||
def update(self, request, session):
|
def update(self, request, session):
|
||||||
@@ -89,12 +89,12 @@ class Session:
|
|||||||
if not self.secret_key:
|
if not self.secret_key:
|
||||||
raise ValueError('The session secret key is not configured')
|
raise ValueError('The session secret key is not configured')
|
||||||
|
|
||||||
encoded_session = jwt.encode(session, self.secret_key,
|
encoded_session = self.encode(session)
|
||||||
algorithm='HS256')
|
|
||||||
|
|
||||||
@request.after_request
|
@request.after_request
|
||||||
def _update_session(request, response):
|
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
|
return response
|
||||||
|
|
||||||
def delete(self, request):
|
def delete(self, request):
|
||||||
@@ -117,10 +117,21 @@ class Session:
|
|||||||
"""
|
"""
|
||||||
@request.after_request
|
@request.after_request
|
||||||
def _delete_session(request, response):
|
def _delete_session(request, response):
|
||||||
response.set_cookie('session', '', http_only=True,
|
response.delete_cookie('session', **self.cookie_options)
|
||||||
expires='Thu, 01 Jan 1970 00:00:01 GMT')
|
|
||||||
return response
|
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):
|
def with_session(f):
|
||||||
"""Decorator that passes the user session to the route handler.
|
"""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,
|
Note that the decorator does not save the session. To update the session,
|
||||||
call the :func:`session.save() <microdot.session.SessionDict.save>` method.
|
call the :func:`session.save() <microdot.session.SessionDict.save>` method.
|
||||||
"""
|
"""
|
||||||
|
@wraps(f)
|
||||||
async def wrapper(request, *args, **kwargs):
|
async def wrapper(request, *args, **kwargs):
|
||||||
return await invoke_handler(
|
return await invoke_handler(
|
||||||
f, request, request.app._session.get(request), *args, **kwargs)
|
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
|
return wrapper
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
from microdot.helpers import wraps
|
||||||
|
|
||||||
|
|
||||||
class SSE:
|
class SSE:
|
||||||
@@ -12,7 +13,7 @@ class SSE:
|
|||||||
self.event = asyncio.Event()
|
self.event = asyncio.Event()
|
||||||
self.queue = []
|
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.
|
"""Send an event to the client.
|
||||||
|
|
||||||
:param data: the data to send. It can be given as a string, bytes, dict
|
: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.
|
Any other types are converted to string before sending.
|
||||||
:param event: an optional event name, to send along with the data. If
|
:param event: an optional event name, to send along with the data. If
|
||||||
given, it must be a string.
|
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)):
|
if isinstance(data, (dict, list)):
|
||||||
data = json.dumps(data).encode()
|
data = json.dumps(data).encode()
|
||||||
@@ -28,6 +31,8 @@ class SSE:
|
|||||||
elif not isinstance(data, bytes):
|
elif not isinstance(data, bytes):
|
||||||
data = str(data).encode()
|
data = str(data).encode()
|
||||||
data = b'data: ' + data + b'\n\n'
|
data = b'data: ' + data + b'\n\n'
|
||||||
|
if event_id:
|
||||||
|
data = b'id: ' + event_id.encode() + b'\n' + data
|
||||||
if event:
|
if event:
|
||||||
data = b'event: ' + event.encode() + b'\n' + data
|
data = b'event: ' + event.encode() + b'\n' + data
|
||||||
self.queue.append(data)
|
self.queue.append(data)
|
||||||
@@ -99,6 +104,7 @@ def with_sse(f):
|
|||||||
# send a named event
|
# send a named event
|
||||||
await sse.send('hello', event='greeting')
|
await sse.send('hello', event='greeting')
|
||||||
"""
|
"""
|
||||||
|
@wraps(f)
|
||||||
async def sse_handler(request, *args, **kwargs):
|
async def sse_handler(request, *args, **kwargs):
|
||||||
return sse_response(request, f, *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
|
The following example shows how to create a test client for an application
|
||||||
and send a test request::
|
and send a test request::
|
||||||
|
|
||||||
from microdot_asyncio import Microdot
|
from microdot import Microdot
|
||||||
|
|
||||||
app = Microdot()
|
app = Microdot()
|
||||||
|
|
||||||
@@ -112,9 +112,13 @@ class TestClient:
|
|||||||
headers['Host'] = 'example.com:1234'
|
headers['Host'] = 'example.com:1234'
|
||||||
return body, headers
|
return body, headers
|
||||||
|
|
||||||
def _process_cookies(self, headers):
|
def _process_cookies(self, path, headers):
|
||||||
cookies = ''
|
cookies = ''
|
||||||
for name, value in self.cookies.items():
|
for name, value in self.cookies.items():
|
||||||
|
if isinstance(value, tuple):
|
||||||
|
value, cookie_path = value
|
||||||
|
if not path.startswith(cookie_path):
|
||||||
|
continue
|
||||||
if cookies:
|
if cookies:
|
||||||
cookies += '; '
|
cookies += '; '
|
||||||
cookies += name + '=' + value
|
cookies += name + '=' + value
|
||||||
@@ -123,7 +127,7 @@ class TestClient:
|
|||||||
headers['Cookie'] += '; ' + cookies
|
headers['Cookie'] += '; ' + cookies
|
||||||
else:
|
else:
|
||||||
headers['Cookie'] = cookies
|
headers['Cookie'] = cookies
|
||||||
return cookies, headers
|
return headers
|
||||||
|
|
||||||
def _render_request(self, method, path, headers, body):
|
def _render_request(self, method, path, headers, body):
|
||||||
request_bytes = '{method} {path} HTTP/1.0\n'.format(
|
request_bytes = '{method} {path} HTTP/1.0\n'.format(
|
||||||
@@ -139,26 +143,45 @@ class TestClient:
|
|||||||
for cookie in cookies:
|
for cookie in cookies:
|
||||||
cookie_name, cookie_value = cookie.split('=', 1)
|
cookie_name, cookie_value = cookie.split('=', 1)
|
||||||
cookie_options = cookie_value.split(';')
|
cookie_options = cookie_value.split(';')
|
||||||
|
path = '/'
|
||||||
delete = False
|
delete = False
|
||||||
for option in cookie_options[1:]:
|
for option in cookie_options[1:]:
|
||||||
if option.strip().lower().startswith('expires='):
|
option = option.strip().lower()
|
||||||
_, e = option.strip().split('=', 1)
|
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
|
# 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
|
elif option.startswith('path='):
|
||||||
|
_, path = option.split('=', 1)
|
||||||
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]
|
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:
|
else:
|
||||||
self.cookies[cookie_name] = cookie_options[0]
|
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):
|
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)
|
headers = self._process_cookies(path, headers)
|
||||||
request_bytes = self._render_request(method, path, headers, body)
|
request_bytes = self._render_request(method, path, headers, body)
|
||||||
if sock:
|
if sock:
|
||||||
reader = sock[0]
|
reader = sock[0]
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import binascii
|
|||||||
import hashlib
|
import hashlib
|
||||||
from microdot import Request, Response
|
from microdot import Request, Response
|
||||||
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
||||||
|
from microdot.helpers import wraps
|
||||||
|
|
||||||
|
|
||||||
class WebSocketError(Exception):
|
class WebSocketError(Exception):
|
||||||
@@ -192,6 +193,7 @@ async def websocket_upgrade(request):
|
|||||||
|
|
||||||
|
|
||||||
def websocket_wrapper(f, upgrade_function):
|
def websocket_wrapper(f, upgrade_function):
|
||||||
|
@wraps(f)
|
||||||
async def wrapper(request, *args, **kwargs):
|
async def wrapper(request, *args, **kwargs):
|
||||||
ws = await upgrade_function(request)
|
ws = await upgrade_function(request)
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -203,6 +203,7 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
req.cookies['one'] + req.cookies['two'] + req.cookies['three'])
|
req.cookies['one'] + req.cookies['two'] + req.cookies['three'])
|
||||||
res.set_cookie('four', '4')
|
res.set_cookie('four', '4')
|
||||||
res.delete_cookie('two', path='/')
|
res.delete_cookie('two', path='/')
|
||||||
|
res.delete_cookie('one', path='/bad')
|
||||||
return res
|
return res
|
||||||
|
|
||||||
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
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,
|
expires='Tue, 05 Nov 2019 02:23:54 GMT', max_age=123,
|
||||||
secure=True, http_only=True)
|
secure=True, http_only=True)
|
||||||
res.delete_cookie('foo8', http_only=True)
|
res.delete_cookie('foo8', http_only=True)
|
||||||
|
res.delete_cookie('foo9', path='/s')
|
||||||
self.assertEqual(res.headers, {'Set-Cookie': [
|
self.assertEqual(res.headers, {'Set-Cookie': [
|
||||||
'foo1=bar1',
|
'foo1=bar1',
|
||||||
'foo2=bar2; Path=/; Partitioned',
|
'foo2=bar2; Path=/; Partitioned',
|
||||||
@@ -203,7 +204,10 @@ class TestResponse(unittest.TestCase):
|
|||||||
'foo7=bar7; Path=/foo; Domain=example.com:1234; '
|
'foo7=bar7; Path=/foo; Domain=example.com:1234; '
|
||||||
'Expires=Tue, 05 Nov 2019 02:23:54 GMT; Max-Age=123; Secure; '
|
'Expires=Tue, 05 Nov 2019 02:23:54 GMT; Max-Age=123; Secure; '
|
||||||
'HttpOnly',
|
'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):
|
def test_redirect(self):
|
||||||
|
|||||||
@@ -82,3 +82,77 @@ class TestSession(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 200)
|
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):
|
async def handle_sse(request, sse):
|
||||||
await sse.send('foo')
|
await sse.send('foo')
|
||||||
await sse.send('bar', event='test')
|
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({'foo': 'bar'})
|
||||||
await sse.send([42, 'foo', 'bar'])
|
await sse.send([42, 'foo', 'bar'])
|
||||||
await sse.send(ValueError('foo'))
|
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.headers['Content-Type'], 'text/event-stream')
|
||||||
self.assertEqual(response.text, ('data: foo\n\n'
|
self.assertEqual(response.text, ('data: foo\n\n'
|
||||||
'event: test\ndata: bar\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: {"foo": "bar"}\n\n'
|
||||||
'data: [42, "foo", "bar"]\n\n'
|
'data: [42, "foo", "bar"]\n\n'
|
||||||
'data: foo\n\n'
|
'data: foo\n\n'
|
||||||
|
|||||||
Reference in New Issue
Block a user