Compare commits
73 Commits
pre-regist
...
v22.6.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2c0eed24d | ||
|
|
3abe4f885e | ||
|
|
f4c8252185 | ||
|
|
daa1f8f2d5 | ||
|
|
0901d3188a | ||
|
|
0985d130e2 | ||
|
|
7e0b0deb11 | ||
|
|
e54ac3c6fd | ||
|
|
4429e76532 | ||
|
|
e4be70bae8 | ||
|
|
13d5a44278 | ||
|
|
aba333bfb6 | ||
|
|
b59da498cc | ||
|
|
70382f21ba | ||
|
|
0e1bf89fad | ||
|
|
6c48c8b3ba | ||
|
|
d1c5e8003b | ||
|
|
ce926a34f2 | ||
|
|
a744041e38 | ||
|
|
2f90a85df1 | ||
|
|
a411bc06e3 | ||
|
|
1668e1532f | ||
|
|
b87982769f | ||
|
|
65b53a5f3f | ||
|
|
49789b7841 | ||
|
|
c249004c30 | ||
|
|
4ee2e57ec8 | ||
|
|
86ae5f981c | ||
|
|
2bfa65e0de | ||
|
|
293278bb08 | ||
|
|
5d683c6ea4 | ||
|
|
78b6723149 | ||
|
|
3a6cc7389c | ||
|
|
cc97287f8e | ||
|
|
00218aa9f2 | ||
|
|
874718db94 | ||
|
|
bb4474897f | ||
|
|
0cb342aef4 | ||
|
|
030987480c | ||
|
|
f6fdc80b40 | ||
|
|
361c242473 | ||
|
|
32962d1e1c | ||
|
|
6e0a6871b5 | ||
|
|
0030425c8c | ||
|
|
c9dbc8ed26 | ||
|
|
44b108b564 | ||
|
|
2a8e91052f | ||
|
|
0c9df02e66 | ||
|
|
7523e87937 | ||
|
|
d4fb44e986 | ||
|
|
68b654d981 | ||
|
|
88bc6d8966 | ||
|
|
ac388d644b | ||
|
|
bb517ddcca | ||
|
|
b8d991420b | ||
|
|
4a416e177a | ||
|
|
8dfa49b648 | ||
|
|
8b0eaa097c | ||
|
|
101151b419 | ||
|
|
4669036f45 | ||
|
|
9bf9067c99 | ||
|
|
a7bc8b56ba | ||
|
|
371985d129 | ||
|
|
3eae00898d | ||
|
|
dc3ccba527 | ||
|
|
b91ffed010 | ||
|
|
8c07e388cd | ||
|
|
98ce4bdeb2 | ||
|
|
4659069350 | ||
|
|
080d41627a | ||
|
|
d799c5f03c | ||
|
|
abe062b371 | ||
|
|
b5a00ac1ca |
@@ -1,2 +0,0 @@
|
||||
[tool.black]
|
||||
line-length = 79
|
||||
@@ -1,28 +0,0 @@
|
||||
exclude_patterns:
|
||||
- "sanic/__main__.py"
|
||||
- "sanic/application/logo.py"
|
||||
- "sanic/application/motd.py"
|
||||
- "sanic/reloader_helpers.py"
|
||||
- "sanic/simple.py"
|
||||
- "sanic/utils.py"
|
||||
- ".github/"
|
||||
- "changelogs/"
|
||||
- "docker/"
|
||||
- "docs/"
|
||||
- "examples/"
|
||||
- "scripts/"
|
||||
- "tests/"
|
||||
checks:
|
||||
argument-count:
|
||||
enabled: false
|
||||
file-lines:
|
||||
config:
|
||||
threshold: 1000
|
||||
method-count:
|
||||
config:
|
||||
threshold: 40
|
||||
complex-logic:
|
||||
enabled: false
|
||||
method-complexity:
|
||||
config:
|
||||
threshold: 10
|
||||
15
.coveragerc
15
.coveragerc
@@ -3,13 +3,12 @@ branch = True
|
||||
source = sanic
|
||||
omit =
|
||||
site-packages
|
||||
sanic/application/logo.py
|
||||
sanic/application/motd.py
|
||||
sanic/cli
|
||||
sanic/__main__.py
|
||||
sanic/compat.py
|
||||
sanic/reloader_helpers.py
|
||||
sanic/simple.py
|
||||
sanic/utils.py
|
||||
sanic/cli
|
||||
|
||||
[html]
|
||||
directory = coverage
|
||||
@@ -21,3 +20,13 @@ exclude_lines =
|
||||
noqa
|
||||
NOQA
|
||||
pragma: no cover
|
||||
TYPE_CHECKING
|
||||
omit =
|
||||
site-packages
|
||||
sanic/__main__.py
|
||||
sanic/compat.py
|
||||
sanic/reloader_helpers.py
|
||||
sanic/simple.py
|
||||
sanic/utils.py
|
||||
sanic/cli
|
||||
skip_empty = True
|
||||
|
||||
8
.github/workflows/codeql-analysis.yml
vendored
8
.github/workflows/codeql-analysis.yml
vendored
@@ -2,9 +2,13 @@ name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
schedule:
|
||||
- cron: '25 16 * * 0'
|
||||
|
||||
18
.github/workflows/coverage.yml
vendored
18
.github/workflows/coverage.yml
vendored
@@ -3,13 +3,15 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
tags:
|
||||
- "!*" # Do not execute on tags
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
jobs:
|
||||
test:
|
||||
if: github.event.pull_request.draft == false
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -19,7 +21,6 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
@@ -28,9 +29,10 @@ jobs:
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install tox
|
||||
- uses: paambaati/codeclimate-action@v2.5.3
|
||||
if: always()
|
||||
env:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CODECLIMATE }}
|
||||
- name: Run coverage
|
||||
run: tox -e coverage
|
||||
continue-on-error: true
|
||||
- uses: codecov/codecov-action@v2
|
||||
with:
|
||||
coverageCommand: tox -e coverage
|
||||
files: ./coverage.xml
|
||||
fail_ci_if_error: false
|
||||
|
||||
1
.github/workflows/pr-bandit.yml
vendored
1
.github/workflows/pr-bandit.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
1
.github/workflows/pr-docs.yml
vendored
1
.github/workflows/pr-docs.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
1
.github/workflows/pr-linter.yml
vendored
1
.github/workflows/pr-linter.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
1
.github/workflows/pr-python310.yml
vendored
1
.github/workflows/pr-python310.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
1
.github/workflows/pr-python37.yml
vendored
1
.github/workflows/pr-python37.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
1
.github/workflows/pr-python38.yml
vendored
1
.github/workflows/pr-python38.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
1
.github/workflows/pr-python39.yml
vendored
1
.github/workflows/pr-python39.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
3
.github/workflows/pr-type-check.yml
vendored
3
.github/workflows/pr-type-check.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
@@ -15,7 +16,7 @@ jobs:
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
config:
|
||||
- { python-version: 3.7, tox-env: type-checking}
|
||||
# - { python-version: 3.7, tox-env: type-checking}
|
||||
- { python-version: 3.8, tox-env: type-checking}
|
||||
- { python-version: 3.9, tox-env: type-checking}
|
||||
- { python-version: "3.10", tox-env: type-checking}
|
||||
|
||||
1
.github/workflows/pr-windows.yml
vendored
1
.github/workflows/pr-windows.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- "*LTS"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
|
||||
205
CHANGELOG.rst
205
CHANGELOG.rst
@@ -1,12 +1,12 @@
|
||||
.. note::
|
||||
|
||||
From v21.9, CHANGELOG files are maintained in ``./docs/sanic/releases``
|
||||
CHANGELOG files are maintained in ``./docs/sanic/releases``. To view the full CHANGELOG, please visit https://sanic.readthedocs.io/en/stable/sanic/changelog.html.
|
||||
|
||||
|
||||
Version 21.6.1
|
||||
--------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
* `#2178 <https://github.com/sanic-org/sanic/pull/2178>`_
|
||||
Update sanic-routing to allow for better splitting of complex URI templates
|
||||
@@ -20,8 +20,7 @@ Bugfixes
|
||||
Version 21.6.0
|
||||
--------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
* `#2094 <https://github.com/sanic-org/sanic/pull/2094>`_
|
||||
Add ``response.eof()`` method for closing a stream in a handler
|
||||
@@ -68,8 +67,7 @@ Features
|
||||
* `#2170 <https://github.com/sanic-org/sanic/pull/2170>`_
|
||||
Additional methods for attaching ``HTTPMethodView``
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
* `#2091 <https://github.com/sanic-org/sanic/pull/2091>`_
|
||||
Fix ``UserWarning`` in ASGI mode for missing ``__slots__``
|
||||
@@ -85,8 +83,7 @@ Bugfixes
|
||||
Fix issue where Blueprint exception handlers do not consistently route to proper handler
|
||||
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
* `#2156 <https://github.com/sanic-org/sanic/pull/2156>`_
|
||||
Remove config value ``REQUEST_BUFFER_QUEUE_SIZE``
|
||||
@@ -95,14 +92,12 @@ Deprecations and Removals
|
||||
* `#2172 <https://github.com/sanic-org/sanic/pull/2170>`_
|
||||
Deprecate StreamingHTTPResponse
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
* `#2149 <https://github.com/sanic-org/sanic/pull/2149>`_
|
||||
Remove Travis CI in favor of GitHub Actions
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
* `#2164 <https://github.com/sanic-org/sanic/pull/2164>`_
|
||||
Fix typo in documentation
|
||||
@@ -112,8 +107,7 @@ Improved Documentation
|
||||
Version 21.3.2
|
||||
--------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
* `#2081 <https://github.com/sanic-org/sanic/pull/2081>`_
|
||||
Disable response timeout on websocket connections
|
||||
@@ -124,8 +118,7 @@ Bugfixes
|
||||
Version 21.3.1
|
||||
--------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
* `#2076 <https://github.com/sanic-org/sanic/pull/2076>`_
|
||||
Static files inside subfolders are not accessible (404)
|
||||
@@ -135,8 +128,7 @@ Version 21.3.0
|
||||
|
||||
`Release Notes <https://sanicframework.org/en/guide/release-notes/v21.3.html>`_
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1876 <https://github.com/sanic-org/sanic/pull/1876>`_
|
||||
@@ -189,8 +181,7 @@ Features
|
||||
`#2063 <https://github.com/sanic-org/sanic/pull/2063>`_
|
||||
App and connection level context objects
|
||||
|
||||
Bugfixes and issues resolved
|
||||
****************************
|
||||
**Bugfixes**
|
||||
|
||||
* Resolve `#1420 <https://github.com/sanic-org/sanic/pull/1420>`_
|
||||
``url_for`` where ``strict_slashes`` are on for a path ending in ``/``
|
||||
@@ -220,8 +211,7 @@ Bugfixes and issues resolved
|
||||
`#2001 <https://github.com/sanic-org/sanic/pull/2001>`_
|
||||
Raise ValueError when cookie max-age is not an integer
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
*
|
||||
`#2007 <https://github.com/sanic-org/sanic/pull/2007>`_
|
||||
@@ -240,8 +230,7 @@ Deprecations and Removals
|
||||
* ``Request.endpoint`` deprecated in favor of ``Request.name``
|
||||
* handler type name prefixes removed (static, websocket, etc)
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
*
|
||||
`#1995 <https://github.com/sanic-org/sanic/pull/1995>`_
|
||||
@@ -259,8 +248,7 @@ Developer infrastructure
|
||||
`#2049 <https://github.com/sanic-org/sanic/pull/2049>`_
|
||||
Updated setup.py to use ``find_packages``
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
*
|
||||
`#1218 <https://github.com/sanic-org/sanic/pull/1218>`_
|
||||
@@ -282,8 +270,7 @@ Improved Documentation
|
||||
`#2052 <https://github.com/sanic-org/sanic/pull/2052>`_
|
||||
Fix some examples and docs
|
||||
|
||||
Miscellaneous
|
||||
*************
|
||||
**Miscellaneous**
|
||||
|
||||
* ``Request.route`` property
|
||||
* Better websocket subprotocols support
|
||||
@@ -326,11 +313,12 @@ Miscellaneous
|
||||
`#2074 <https://github.com/sanic-org/sanic/pull/2074>`_
|
||||
Performance adjustments in ``handle_request_``
|
||||
|
||||
Version 20.12.3
|
||||
---------------
|
||||
Version 20.12.3 🔷
|
||||
------------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
`Current LTS version`
|
||||
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#2021 <https://github.com/sanic-org/sanic/pull/2021>`_
|
||||
@@ -339,8 +327,7 @@ Bugfixes
|
||||
Version 20.12.2
|
||||
---------------
|
||||
|
||||
Dependencies
|
||||
************
|
||||
**Dependencies**
|
||||
|
||||
*
|
||||
`#2026 <https://github.com/sanic-org/sanic/pull/2026>`_
|
||||
@@ -353,8 +340,7 @@ Dependencies
|
||||
Version 19.12.5
|
||||
---------------
|
||||
|
||||
Dependencies
|
||||
************
|
||||
**Dependencies**
|
||||
|
||||
*
|
||||
`#2025 <https://github.com/sanic-org/sanic/pull/2025>`_
|
||||
@@ -364,22 +350,15 @@ Dependencies
|
||||
`#2027 <https://github.com/sanic-org/sanic/pull/2027>`_
|
||||
Remove old chardet requirement, add in hard multidict requirement
|
||||
|
||||
Version 20.12.0
|
||||
---------------
|
||||
Version 20.12.0 🔹
|
||||
-----------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1993 <https://github.com/sanic-org/sanic/pull/1993>`_
|
||||
Add disable app registry
|
||||
|
||||
Version 20.12.0
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1945 <https://github.com/sanic-org/sanic/pull/1945>`_
|
||||
Static route more verbose if file not found
|
||||
@@ -416,22 +395,19 @@ Features
|
||||
`#1979 <https://github.com/sanic-org/sanic/pull/1979>`_
|
||||
Add app registry and Sanic class level app retrieval
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1965 <https://github.com/sanic-org/sanic/pull/1965>`_
|
||||
Fix Chunked Transport-Encoding in ASGI streaming response
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
*
|
||||
`#1981 <https://github.com/sanic-org/sanic/pull/1981>`_
|
||||
Cleanup and remove deprecated code
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
*
|
||||
`#1956 <https://github.com/sanic-org/sanic/pull/1956>`_
|
||||
@@ -445,8 +421,7 @@ Developer infrastructure
|
||||
`#1986 <https://github.com/sanic-org/sanic/pull/1986>`_
|
||||
Update tox requirements
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
*
|
||||
`#1951 <https://github.com/sanic-org/sanic/pull/1951>`_
|
||||
@@ -464,8 +439,7 @@ Improved Documentation
|
||||
Version 20.9.1
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1954 <https://github.com/sanic-org/sanic/pull/1954>`_
|
||||
@@ -478,8 +452,7 @@ Bugfixes
|
||||
Version 19.12.3
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1959 <https://github.com/sanic-org/sanic/pull/1959>`_
|
||||
@@ -490,8 +463,7 @@ Version 20.9.0
|
||||
---------------
|
||||
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1887 <https://github.com/sanic-org/sanic/pull/1887>`_
|
||||
@@ -518,22 +490,19 @@ Features
|
||||
`#1937 <https://github.com/sanic-org/sanic/pull/1937>`_
|
||||
Added auto, text, and json fallback error handlers (in v21.3, the default will change form html to auto)
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1897 <https://github.com/sanic-org/sanic/pull/1897>`_
|
||||
Resolves exception from unread bytes in stream
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
*
|
||||
`#1903 <https://github.com/sanic-org/sanic/pull/1903>`_
|
||||
config.from_envar, config.from_pyfile, and config.from_object are deprecated and set to be removed in v21.3
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
*
|
||||
`#1890 <https://github.com/sanic-org/sanic/pull/1890>`_,
|
||||
@@ -548,8 +517,7 @@ Developer infrastructure
|
||||
`#1924 <https://github.com/sanic-org/sanic/pull/1924>`_
|
||||
Adding --strict-markers for pytest
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
*
|
||||
`#1922 <https://github.com/sanic-org/sanic/pull/1922>`_
|
||||
@@ -559,8 +527,7 @@ Improved Documentation
|
||||
Version 20.6.3
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1884 <https://github.com/sanic-org/sanic/pull/1884>`_
|
||||
@@ -570,8 +537,7 @@ Bugfixes
|
||||
Version 20.6.2
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1641 <https://github.com/sanic-org/sanic/pull/1641>`_
|
||||
@@ -581,8 +547,7 @@ Features
|
||||
Version 20.6.1
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1760 <https://github.com/sanic-org/sanic/pull/1760>`_
|
||||
@@ -596,8 +561,7 @@ Features
|
||||
`#1880 <https://github.com/sanic-org/sanic/pull/1880>`_
|
||||
Add handler names for websockets for url_for usage
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1776 <https://github.com/sanic-org/sanic/pull/1776>`_
|
||||
@@ -619,15 +583,13 @@ Bugfixes
|
||||
`#1853 <https://github.com/sanic-org/sanic/pull/1853>`_
|
||||
Fix pickle error when attempting to pickle an application which contains websocket routes
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
*
|
||||
`#1739 <https://github.com/sanic-org/sanic/pull/1739>`_
|
||||
Deprecate body_bytes to merge into body
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
*
|
||||
`#1852 <https://github.com/sanic-org/sanic/pull/1852>`_
|
||||
@@ -642,8 +604,7 @@ Developer infrastructure
|
||||
Wrap run()'s "protocol" type annotation in Optional[]
|
||||
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
*
|
||||
`#1846 <https://github.com/sanic-org/sanic/pull/1846>`_
|
||||
@@ -663,8 +624,7 @@ Version 20.6.0
|
||||
Version 20.3.0
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1762 <https://github.com/sanic-org/sanic/pull/1762>`_
|
||||
@@ -695,8 +655,7 @@ Features
|
||||
`#1820 <https://github.com/sanic-org/sanic/pull/1820>`_
|
||||
Do not set content-type and content-length headers in exceptions
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1748 <https://github.com/sanic-org/sanic/pull/1748>`_
|
||||
@@ -714,8 +673,7 @@ Bugfixes
|
||||
`#1808 <https://github.com/sanic-org/sanic/pull/1808>`_
|
||||
Fix Ctrl+C and tests on Windows
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
*
|
||||
`#1800 <https://github.com/sanic-org/sanic/pull/1800>`_
|
||||
@@ -733,8 +691,7 @@ Deprecations and Removals
|
||||
`#1818 <https://github.com/sanic-org/sanic/pull/1818>`_
|
||||
Complete deprecation of ``app.remove_route`` and ``request.raw_args``
|
||||
|
||||
Dependencies
|
||||
************
|
||||
**Dependencies**
|
||||
|
||||
*
|
||||
`#1794 <https://github.com/sanic-org/sanic/pull/1794>`_
|
||||
@@ -744,15 +701,13 @@ Dependencies
|
||||
`#1806 <https://github.com/sanic-org/sanic/pull/1806>`_
|
||||
Import ``ASGIDispatch`` from top-level ``httpx`` (from third-party deprecation)
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
*
|
||||
`#1833 <https://github.com/sanic-org/sanic/pull/1833>`_
|
||||
Resolve broken documentation builds
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
*
|
||||
`#1755 <https://github.com/sanic-org/sanic/pull/1755>`_
|
||||
@@ -794,8 +749,7 @@ Improved Documentation
|
||||
Version 19.12.0
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
- Fix blueprint middleware application
|
||||
|
||||
@@ -814,8 +768,7 @@ Bugfixes
|
||||
due to an `AttributeError`. This fix makes the availability of `SERVER_NAME` on our `app.config` an optional behavior. (`#1707 <https://github.com/sanic-org/sanic/issues/1707>`__)
|
||||
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
- Move docs from MD to RST
|
||||
|
||||
@@ -829,8 +782,7 @@ Improved Documentation
|
||||
Version 19.6.3
|
||||
--------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
- Enable Towncrier Support
|
||||
|
||||
@@ -838,8 +790,7 @@ Features
|
||||
of generating and managing change logs as part of each of pull requests. (`#1631 <https://github.com/sanic-org/sanic/issues/1631>`__)
|
||||
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
- Documentation infrastructure changes
|
||||
|
||||
@@ -852,8 +803,7 @@ Improved Documentation
|
||||
Version 19.6.2
|
||||
--------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1562 <https://github.com/sanic-org/sanic/pull/1562>`_
|
||||
@@ -869,8 +819,7 @@ Features
|
||||
Add Configure support from object string
|
||||
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
*
|
||||
`#1587 <https://github.com/sanic-org/sanic/pull/1587>`_
|
||||
@@ -888,8 +837,7 @@ Bugfixes
|
||||
`#1594 <https://github.com/sanic-org/sanic/pull/1594>`_
|
||||
Strict Slashes behavior fix
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
**Deprecations and Removals**
|
||||
|
||||
*
|
||||
`#1544 <https://github.com/sanic-org/sanic/pull/1544>`_
|
||||
@@ -913,8 +861,7 @@ Deprecations and Removals
|
||||
Version 19.3
|
||||
------------
|
||||
|
||||
Features
|
||||
********
|
||||
**Features**
|
||||
|
||||
*
|
||||
`#1497 <https://github.com/sanic-org/sanic/pull/1497>`_
|
||||
@@ -982,8 +929,7 @@ Features
|
||||
|
||||
This is a breaking change.
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
**Bugfixes**
|
||||
|
||||
|
||||
*
|
||||
@@ -1019,8 +965,7 @@ Bugfixes
|
||||
This allows the access log to be disabled for example when running via
|
||||
gunicorn.
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
**Developer infrastructure**
|
||||
|
||||
* `#1529 <https://github.com/sanic-org/sanic/pull/1529>`_ Update project PyPI credentials
|
||||
* `#1515 <https://github.com/sanic-org/sanic/pull/1515>`_ fix linter issue causing travis build failures (fix #1514)
|
||||
@@ -1028,8 +973,7 @@ Developer infrastructure
|
||||
* `#1478 <https://github.com/sanic-org/sanic/pull/1478>`_ Upgrade setuptools version and use native docutils in doc build
|
||||
* `#1464 <https://github.com/sanic-org/sanic/pull/1464>`_ Upgrade pytest, and fix caplog unit tests
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
**Improved Documentation**
|
||||
|
||||
* `#1516 <https://github.com/sanic-org/sanic/pull/1516>`_ Fix typo at the exception documentation
|
||||
* `#1510 <https://github.com/sanic-org/sanic/pull/1510>`_ fix typo in Asyncio example
|
||||
@@ -1096,15 +1040,13 @@ Version 18.12
|
||||
Version 0.8
|
||||
-----------
|
||||
|
||||
0.8.3
|
||||
*****
|
||||
**0.8.3**
|
||||
|
||||
* Changes:
|
||||
|
||||
* Ownership changed to org 'sanic-org'
|
||||
|
||||
0.8.0
|
||||
*****
|
||||
**0.8.0**
|
||||
|
||||
* Changes:
|
||||
|
||||
@@ -1184,19 +1126,16 @@ Version 0.1
|
||||
-----------
|
||||
|
||||
|
||||
0.1.7
|
||||
*****
|
||||
**0.1.7**
|
||||
|
||||
* Reversed static url and directory arguments to meet spec
|
||||
|
||||
0.1.6
|
||||
*****
|
||||
**0.1.6**
|
||||
|
||||
* Static files
|
||||
* Lazy Cookie Loading
|
||||
|
||||
0.1.5
|
||||
*****
|
||||
**0.1.5**
|
||||
|
||||
* Cookies
|
||||
* Blueprint listeners and ordering
|
||||
@@ -1204,23 +1143,19 @@ Version 0.1
|
||||
* Fix: Incomplete file reads on medium+ sized post requests
|
||||
* Breaking: after_start and before_stop now pass sanic as their first argument
|
||||
|
||||
0.1.4
|
||||
*****
|
||||
**0.1.4**
|
||||
|
||||
* Multiprocessing
|
||||
|
||||
0.1.3
|
||||
*****
|
||||
**0.1.3**
|
||||
|
||||
* Blueprint support
|
||||
* Faster Response processing
|
||||
|
||||
0.1.1 - 0.1.2
|
||||
*************
|
||||
**0.1.1 - 0.1.2**
|
||||
|
||||
* Struggling to update pypi via CI
|
||||
|
||||
0.1.0
|
||||
*****
|
||||
**0.1.0**
|
||||
|
||||
* Released to public
|
||||
|
||||
@@ -140,6 +140,7 @@ To maintain the code consistency, Sanic uses following tools.
|
||||
#. `isort <https://github.com/timothycrosley/isort>`_
|
||||
#. `black <https://github.com/python/black>`_
|
||||
#. `flake8 <https://github.com/PyCQA/flake8>`_
|
||||
#. `slotscheck <https://github.com/ariebovenberg/slotscheck>`_
|
||||
|
||||
isort
|
||||
*****
|
||||
@@ -167,7 +168,13 @@ flake8
|
||||
#. pycodestyle
|
||||
#. Ned Batchelder's McCabe script
|
||||
|
||||
``isort``\ , ``black`` and ``flake8`` checks are performed during ``tox`` lint checks.
|
||||
slotscheck
|
||||
**********
|
||||
|
||||
``slotscheck`` ensures that there are no problems with ``__slots__``
|
||||
(e.g. overlaps, or missing slots in base classes).
|
||||
|
||||
``isort``\ , ``black``\ , ``flake8`` and ``slotscheck`` checks are performed during ``tox`` lint checks.
|
||||
|
||||
The **easiest** way to make your code conform is to run the following before committing.
|
||||
|
||||
|
||||
6
Makefile
6
Makefile
@@ -66,15 +66,15 @@ ifdef include_tests
|
||||
isort -rc sanic tests
|
||||
else
|
||||
$(info Sorting Imports)
|
||||
isort -rc sanic tests --profile=black
|
||||
isort -rc sanic tests
|
||||
endif
|
||||
endif
|
||||
|
||||
black:
|
||||
black --config ./.black.toml sanic tests
|
||||
black sanic tests
|
||||
|
||||
isort:
|
||||
isort sanic tests --profile=black
|
||||
isort sanic tests
|
||||
|
||||
pretty: black isort
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ Sanic | Build fast. Run fast.
|
||||
:stub-columns: 1
|
||||
|
||||
* - Build
|
||||
- | |Py39Test| |Py38Test| |Py37Test|
|
||||
- | |Py310Test| |Py39Test| |Py38Test| |Py37Test|
|
||||
* - Docs
|
||||
- | |UserGuide| |Documentation|
|
||||
* - Package
|
||||
@@ -27,6 +27,8 @@ Sanic | Build fast. Run fast.
|
||||
:target: https://community.sanicframework.org/
|
||||
.. |Discord| image:: https://img.shields.io/discord/812221182594121728?logo=discord
|
||||
:target: https://discord.gg/FARQzAEMAA
|
||||
.. |Py310Test| image:: https://github.com/sanic-org/sanic/actions/workflows/pr-python310.yml/badge.svg?branch=main
|
||||
:target: https://github.com/sanic-org/sanic/actions/workflows/pr-python310.yml
|
||||
.. |Py39Test| image:: https://github.com/sanic-org/sanic/actions/workflows/pr-python39.yml/badge.svg?branch=main
|
||||
:target: https://github.com/sanic-org/sanic/actions/workflows/pr-python39.yml
|
||||
.. |Py38Test| image:: https://github.com/sanic-org/sanic/actions/workflows/pr-python38.yml/badge.svg?branch=main
|
||||
@@ -64,7 +66,7 @@ Sanic | Build fast. Run fast.
|
||||
|
||||
Sanic is a **Python 3.7+** web server and web framework that's written to go fast. It allows the usage of the ``async/await`` syntax added in Python 3.5, which makes your code non-blocking and speedy.
|
||||
|
||||
Sanic is also ASGI compliant, so you can deploy it with an `alternative ASGI webserver <https://sanic.readthedocs.io/en/latest/sanic/deploying.html#running-via-asgi>`_.
|
||||
Sanic is also ASGI compliant, so you can deploy it with an `alternative ASGI webserver <https://sanicframework.org/en/guide/deployment/running.html#asgi>`_.
|
||||
|
||||
`Source code on GitHub <https://github.com/sanic-org/sanic/>`_ | `Help and discussion board <https://community.sanicframework.org/>`_ | `User Guide <https://sanicframework.org>`_ | `Chat on Discord <https://discord.gg/FARQzAEMAA>`_
|
||||
|
||||
@@ -112,7 +114,7 @@ Hello World Example
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic("My Hello, world app")
|
||||
app = Sanic("my-hello-world-app")
|
||||
|
||||
@app.route('/')
|
||||
async def test(request):
|
||||
|
||||
28
codecov.yml
Normal file
28
codecov.yml
Normal file
@@ -0,0 +1,28 @@
|
||||
coverage:
|
||||
status:
|
||||
patch:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 0.75
|
||||
informational: true
|
||||
project:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 0.5
|
||||
precision: 3
|
||||
codecov:
|
||||
require_ci_to_pass: false
|
||||
ignore:
|
||||
- "sanic/__main__.py"
|
||||
- "sanic/compat.py"
|
||||
- "sanic/reloader_helpers.py"
|
||||
- "sanic/simple.py"
|
||||
- "sanic/utils.py"
|
||||
- "sanic/cli"
|
||||
- ".github/"
|
||||
- "changelogs/"
|
||||
- "docker/"
|
||||
- "docs/"
|
||||
- "examples/"
|
||||
- "scripts/"
|
||||
- "tests/"
|
||||
@@ -24,7 +24,11 @@ import sanic
|
||||
|
||||
# -- General configuration ------------------------------------------------
|
||||
|
||||
extensions = ["sphinx.ext.autodoc", "m2r2"]
|
||||
extensions = [
|
||||
"sphinx.ext.autodoc",
|
||||
"m2r2",
|
||||
"enum_tools.autoenum",
|
||||
]
|
||||
|
||||
templates_path = ["_templates"]
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ API
|
||||
===
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:maxdepth: 3
|
||||
|
||||
👥 User Guide <https://sanicframework.org/guide/>
|
||||
sanic/api_reference
|
||||
|
||||
@@ -15,3 +15,19 @@ sanic.config
|
||||
.. automodule:: sanic.config
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.application.constants
|
||||
---------------------------
|
||||
|
||||
.. automodule:: sanic.application.constants
|
||||
:exclude-members: StrEnum
|
||||
:members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
|
||||
sanic.application.state
|
||||
-----------------------
|
||||
|
||||
.. automodule:: sanic.application.state
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
@@ -17,6 +17,14 @@ sanic.handlers
|
||||
:show-inheritance:
|
||||
|
||||
|
||||
sanic.headers
|
||||
--------------
|
||||
|
||||
.. automodule:: sanic.headers
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
|
||||
sanic.request
|
||||
-------------
|
||||
|
||||
@@ -38,10 +46,3 @@ sanic.views
|
||||
.. automodule:: sanic.views
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.websocket
|
||||
---------------
|
||||
|
||||
.. automodule:: sanic.websocket
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
@@ -16,10 +16,3 @@ sanic.server
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
|
||||
sanic.worker
|
||||
------------
|
||||
|
||||
.. automodule:: sanic.worker
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
📜 Changelog
|
||||
============
|
||||
|
||||
.. mdinclude:: ./releases/21.9.md
|
||||
|
||||
.. mdinclude:: ./releases/22/22.6.md
|
||||
.. mdinclude:: ./releases/22/22.3.md
|
||||
.. mdinclude:: ./releases/21/21.12.md
|
||||
.. mdinclude:: ./releases/21/21.9.md
|
||||
.. include:: ../../CHANGELOG.rst
|
||||
|
||||
66
docs/sanic/releases/21/21.12.md
Normal file
66
docs/sanic/releases/21/21.12.md
Normal file
@@ -0,0 +1,66 @@
|
||||
## Version 21.12.1 🔷
|
||||
|
||||
_Current LTS version_
|
||||
|
||||
- [#2349](https://github.com/sanic-org/sanic/pull/2349) Only display MOTD on startup
|
||||
- [#2354](https://github.com/sanic-org/sanic/pull/2354) Ignore name argument in Python 3.7
|
||||
- [#2355](https://github.com/sanic-org/sanic/pull/2355) Add config.update support for all config values
|
||||
|
||||
## Version 21.12.0 🔹
|
||||
|
||||
### Features
|
||||
- [#2260](https://github.com/sanic-org/sanic/pull/2260) Allow early Blueprint registrations to still apply later added objects
|
||||
- [#2262](https://github.com/sanic-org/sanic/pull/2262) Noisy exceptions - force logging of all exceptions
|
||||
- [#2264](https://github.com/sanic-org/sanic/pull/2264) Optional `uvloop` by configuration
|
||||
- [#2270](https://github.com/sanic-org/sanic/pull/2270) Vhost support using multiple TLS certificates
|
||||
- [#2277](https://github.com/sanic-org/sanic/pull/2277) Change signal routing for increased consistency
|
||||
- *BREAKING CHANGE*: If you were manually routing signals there is a breaking change. The signal router's `get` is no longer 100% determinative. There is now an additional step to loop thru the returned signals for proper matching on the requirements. If signals are being dispatched using `app.dispatch` or `bp.dispatch`, there is no change.
|
||||
- [#2290](https://github.com/sanic-org/sanic/pull/2290) Add contextual exceptions
|
||||
- [#2291](https://github.com/sanic-org/sanic/pull/2291) Increase join concat performance
|
||||
- [#2295](https://github.com/sanic-org/sanic/pull/2295), [#2316](https://github.com/sanic-org/sanic/pull/2316), [#2331](https://github.com/sanic-org/sanic/pull/2331) Restructure of CLI and application state with new displays and more command parity with `app.run`
|
||||
- [#2302](https://github.com/sanic-org/sanic/pull/2302) Add route context at definition time
|
||||
- [#2304](https://github.com/sanic-org/sanic/pull/2304) Named tasks and new API for managing background tasks
|
||||
- [#2307](https://github.com/sanic-org/sanic/pull/2307) On app auto-reload, provide insight of changed files
|
||||
- [#2308](https://github.com/sanic-org/sanic/pull/2308) Auto extend application with [Sanic Extensions](https://sanicframework.org/en/plugins/sanic-ext/getting-started.html) if it is installed, and provide first class support for accessing the extensions
|
||||
- [#2309](https://github.com/sanic-org/sanic/pull/2309) Builtin signals changed to `Enum`
|
||||
- [#2313](https://github.com/sanic-org/sanic/pull/2313) Support additional config implementation use case
|
||||
- [#2321](https://github.com/sanic-org/sanic/pull/2321) Refactor environment variable hydration logic
|
||||
- [#2327](https://github.com/sanic-org/sanic/pull/2327) Prevent sending multiple or mixed responses on a single request
|
||||
- [#2330](https://github.com/sanic-org/sanic/pull/2330) Custom type casting on environment variables
|
||||
- [#2332](https://github.com/sanic-org/sanic/pull/2332) Make all deprecation notices consistent
|
||||
- [#2335](https://github.com/sanic-org/sanic/pull/2335) Allow underscore to start instance names
|
||||
|
||||
### Bugfixes
|
||||
- [#2273](https://github.com/sanic-org/sanic/pull/2273) Replace assignation by typing for `websocket_handshake`
|
||||
- [#2285](https://github.com/sanic-org/sanic/pull/2285) Fix IPv6 display in startup logs
|
||||
- [#2299](https://github.com/sanic-org/sanic/pull/2299) Dispatch `http.lifecyle.response` from exception handler
|
||||
|
||||
### Deprecations and Removals
|
||||
- [#2306](https://github.com/sanic-org/sanic/pull/2306) Removal of deprecated items
|
||||
- `Sanic` and `Blueprint` may no longer have arbitrary properties attached to them
|
||||
- `Sanic` and `Blueprint` forced to have compliant names
|
||||
- alphanumeric + `_` + `-`
|
||||
- must start with letter or `_`
|
||||
- `load_env` keyword argument of `Sanic`
|
||||
- `sanic.exceptions.abort`
|
||||
- `sanic.views.CompositionView`
|
||||
- `sanic.response.StreamingHTTPResponse`
|
||||
- *NOTE:* the `stream()` response method (where you pass a callable streaming function) has been deprecated and will be removed in v22.6. You should upgrade all streaming responses to the new style: https://sanicframework.org/en/guide/advanced/streaming.html#response-streaming
|
||||
- [#2320](https://github.com/sanic-org/sanic/pull/2320) Remove app instance from Config for error handler setting
|
||||
|
||||
### Developer infrastructure
|
||||
- [#2251](https://github.com/sanic-org/sanic/pull/2251) Change dev install command
|
||||
- [#2286](https://github.com/sanic-org/sanic/pull/2286) Change codeclimate complexity threshold from 5 to 10
|
||||
- [#2287](https://github.com/sanic-org/sanic/pull/2287) Update host test function names so they are not overwritten
|
||||
- [#2292](https://github.com/sanic-org/sanic/pull/2292) Fail CI on error
|
||||
- [#2311](https://github.com/sanic-org/sanic/pull/2311), [#2324](https://github.com/sanic-org/sanic/pull/2324) Do not run tests for draft PRs
|
||||
- [#2336](https://github.com/sanic-org/sanic/pull/2336) Remove paths from coverage checks
|
||||
- [#2338](https://github.com/sanic-org/sanic/pull/2338) Cleanup ports on tests
|
||||
|
||||
### Improved Documentation
|
||||
- [#2269](https://github.com/sanic-org/sanic/pull/2269), [#2329](https://github.com/sanic-org/sanic/pull/2329), [#2333](https://github.com/sanic-org/sanic/pull/2333) Cleanup typos and fix language
|
||||
|
||||
### Miscellaneous
|
||||
- [#2257](https://github.com/sanic-org/sanic/pull/2257), [#2294](https://github.com/sanic-org/sanic/pull/2294), [#2341](https://github.com/sanic-org/sanic/pull/2341) Add Python 3.10 support
|
||||
- [#2279](https://github.com/sanic-org/sanic/pull/2279), [#2317](https://github.com/sanic-org/sanic/pull/2317), [#2322](https://github.com/sanic-org/sanic/pull/2322) Add/correct missing type annotations
|
||||
- [#2305](https://github.com/sanic-org/sanic/pull/2305) Fix examples to use modern implementations
|
||||
@@ -1,4 +1,14 @@
|
||||
## Version 21.9
|
||||
## Version 21.9.3
|
||||
*Rerelease of v21.9.2 with some cleanup*
|
||||
|
||||
## Version 21.9.2
|
||||
- [#2268](https://github.com/sanic-org/sanic/pull/2268) Make HTTP connections start in IDLE stage, avoiding delays and error messages
|
||||
- [#2310](https://github.com/sanic-org/sanic/pull/2310) More consistent config setting with post-FALLBACK_ERROR_FORMAT apply
|
||||
|
||||
## Version 21.9.1
|
||||
- [#2259](https://github.com/sanic-org/sanic/pull/2259) Allow non-conforming ErrorHandlers
|
||||
|
||||
## Version 21.9.0
|
||||
|
||||
### Features
|
||||
- [#2158](https://github.com/sanic-org/sanic/pull/2158), [#2248](https://github.com/sanic-org/sanic/pull/2248) Complete overhaul of I/O to websockets
|
||||
52
docs/sanic/releases/22/22.3.md
Normal file
52
docs/sanic/releases/22/22.3.md
Normal file
@@ -0,0 +1,52 @@
|
||||
## Version 22.3.0
|
||||
|
||||
### Features
|
||||
- [#2347](https://github.com/sanic-org/sanic/pull/2347) API for multi-application server
|
||||
- 🚨 *BREAKING CHANGE*: The old `sanic.worker.GunicornWorker` has been **removed**. To run Sanic with `gunicorn`, you should use it thru `uvicorn` [as described in their docs](https://www.uvicorn.org/#running-with-gunicorn).
|
||||
- 🧁 *SIDE EFFECT*: Named background tasks are now supported, even in Python 3.7
|
||||
- [#2357](https://github.com/sanic-org/sanic/pull/2357) Parse `Authorization` header as `Request.credentials`
|
||||
- [#2361](https://github.com/sanic-org/sanic/pull/2361) Add config option to skip `Touchup` step in application startup
|
||||
- [#2372](https://github.com/sanic-org/sanic/pull/2372) Updates to CLI help messaging
|
||||
- [#2382](https://github.com/sanic-org/sanic/pull/2382) Downgrade warnings to backwater debug messages
|
||||
- [#2396](https://github.com/sanic-org/sanic/pull/2396) Allow for `multidict` v0.6
|
||||
- [#2401](https://github.com/sanic-org/sanic/pull/2401) Upgrade CLI catching for alternative application run types
|
||||
- [#2402](https://github.com/sanic-org/sanic/pull/2402) Conditionally inject CLI arguments into factory
|
||||
- [#2413](https://github.com/sanic-org/sanic/pull/2413) Add new start and stop event listeners to reloader process
|
||||
- [#2414](https://github.com/sanic-org/sanic/pull/2414) Remove loop as required listener arg
|
||||
- [#2415](https://github.com/sanic-org/sanic/pull/2415) Better exception for bad URL parsing
|
||||
- [sanic-routing#47](https://github.com/sanic-org/sanic-routing/pull/47) Add a new extention parameter type: `<file:ext>`, `<file:ext=jpg>`, `<file:ext=jpg|png|gif|svg>`, `<file=int:ext>`, `<file=int:ext=jpg|png|gif|svg>`, `<file=float:ext=tar.gz>`
|
||||
- 👶 *BETA FEATURE*: This feature will not work with `path` type matching, and is being released as a beta feature only.
|
||||
- [sanic-routing#57](https://github.com/sanic-org/sanic-routing/pull/57) Change `register_pattern` to accept a `str` or `Pattern`
|
||||
- [sanic-routing#58](https://github.com/sanic-org/sanic-routing/pull/58) Default matching on non-empty strings only, and new `strorempty` pattern type
|
||||
- 🚨 *BREAKING CHANGE*: Previously a route with a dynamic string parameter (`/<foo>` or `/<foo:str>`) would match on any string, including empty strings. It will now **only** match a non-empty string. To retain the old behavior, you should use the new parameter type: `/<foo:strorempty>`.
|
||||
|
||||
### Bugfixes
|
||||
- [#2373](https://github.com/sanic-org/sanic/pull/2373) Remove `error_logger` on websockets
|
||||
- [#2381](https://github.com/sanic-org/sanic/pull/2381) Fix newly assigned `None` in task registry
|
||||
- [sanic-routing#52](https://github.com/sanic-org/sanic-routing/pull/52) Add type casting to regex route matching
|
||||
- [sanic-routing#60](https://github.com/sanic-org/sanic-routing/pull/60) Add requirements check on regex routes (this resolves, for example, multiple static directories with differing `host` values)
|
||||
|
||||
### Deprecations and Removals
|
||||
- [#2362](https://github.com/sanic-org/sanic/pull/2362) 22.3 Deprecations and changes
|
||||
1. `debug=True` and `--debug` do _NOT_ automatically run `auto_reload`
|
||||
2. Default error render is with plain text (browsers still get HTML by default because `auto` looks at headers)
|
||||
3. `config` is required for `ErrorHandler.finalize`
|
||||
4. `ErrorHandler.lookup` requires two positional args
|
||||
5. Unused websocket protocol args removed
|
||||
- [#2344](https://github.com/sanic-org/sanic/pull/2344) Deprecate loading of lowercase environment variables
|
||||
|
||||
### Developer infrastructure
|
||||
- [#2363](https://github.com/sanic-org/sanic/pull/2363) Revert code coverage back to Codecov
|
||||
- [#2405](https://github.com/sanic-org/sanic/pull/2405) Upgrade tests for `sanic-routing` changes
|
||||
- [sanic-testing#35](https://github.com/sanic-org/sanic-testing/pull/35) Allow for httpx v0.22
|
||||
|
||||
### Improved Documentation
|
||||
- [#2350](https://github.com/sanic-org/sanic/pull/2350) Fix link in README for ASGI
|
||||
- [#2398](https://github.com/sanic-org/sanic/pull/2398) Document middleware on_request and on_response
|
||||
- [#2409](https://github.com/sanic-org/sanic/pull/2409) Add missing documentation for `Request.respond`
|
||||
|
||||
### Miscellaneous
|
||||
- [#2376](https://github.com/sanic-org/sanic/pull/2376) Fix typing for `ListenerMixin.listener`
|
||||
- [#2383](https://github.com/sanic-org/sanic/pull/2383) Clear deprecation warning in `asyncio.wait`
|
||||
- [#2387](https://github.com/sanic-org/sanic/pull/2387) Cleanup `__slots__` implementations
|
||||
- [#2390](https://github.com/sanic-org/sanic/pull/2390) Clear deprecation warning in `asyncio.get_event_loop`
|
||||
43
docs/sanic/releases/22/22.6.md
Normal file
43
docs/sanic/releases/22/22.6.md
Normal file
@@ -0,0 +1,43 @@
|
||||
## Version 22.6.0 🔶
|
||||
|
||||
_Current version_
|
||||
|
||||
### Features
|
||||
- [#2378](https://github.com/sanic-org/sanic/pull/2378) Introduce HTTP/3 and autogeneration of TLS certificates in `DEBUG` mode
|
||||
- 👶 *EARLY RELEASE FEATURE*: Serving Sanic over HTTP/3 is an early release feature. It does not yet fully cover the HTTP/3 spec, but instead aims for feature parity with Sanic's existing HTTP/1.1 server. Websockets, WebTransport, push responses are examples of some features not yet implemented.
|
||||
- 📦 *EXTRA REQUIREMENT*: Not all HTTP clients are capable of interfacing with HTTP/3 servers. You may need to install a [HTTP/3 capable client](https://curl.se/docs/http3.html).
|
||||
- 📦 *EXTRA REQUIREMENT*: In order to use TLS autogeneration, you must install either [mkcert](https://github.com/FiloSottile/mkcert) or [trustme](https://github.com/python-trio/trustme).
|
||||
- [#2416](https://github.com/sanic-org/sanic/pull/2416) Add message to `task.cancel`
|
||||
- [#2420](https://github.com/sanic-org/sanic/pull/2420) Add exception aliases for more consistent naming with standard HTTP response types (`BadRequest`, `MethodNotAllowed`, `RangeNotSatisfiable`)
|
||||
- [#2432](https://github.com/sanic-org/sanic/pull/2432) Expose ASGI `scope` as a property on the `Request` object
|
||||
- [#2438](https://github.com/sanic-org/sanic/pull/2438) Easier access to websocket class for annotation: `from sanic import Websocket`
|
||||
- [#2439](https://github.com/sanic-org/sanic/pull/2439) New API for reading form values with options: `Request.get_form`
|
||||
- [#2445](https://github.com/sanic-org/sanic/pull/2445) Add custom `loads` function
|
||||
- [#2447](https://github.com/sanic-org/sanic/pull/2447), [#2486](https://github.com/sanic-org/sanic/pull/2486) Improved API to support setting cache control headers
|
||||
- [#2453](https://github.com/sanic-org/sanic/pull/2453) Move verbosity filtering to logger
|
||||
- [#2475](https://github.com/sanic-org/sanic/pull/2475) Expose getter for current request using `Request.get_current()`
|
||||
|
||||
### Bugfixes
|
||||
- [#2448](https://github.com/sanic-org/sanic/pull/2448) Fix to allow running with `pythonw.exe` or places where there is no `sys.stdout`
|
||||
- [#2451](https://github.com/sanic-org/sanic/pull/2451) Trigger `http.lifecycle.request` signal in ASGI mode
|
||||
- [#2455](https://github.com/sanic-org/sanic/pull/2455) Resolve typing of stacked route definitions
|
||||
- [#2463](https://github.com/sanic-org/sanic/pull/2463) Properly catch websocket CancelledError in websocket handler in Python 3.7
|
||||
|
||||
### Deprecations and Removals
|
||||
- [#2487](https://github.com/sanic-org/sanic/pull/2487) v22.6 deprecations and changes
|
||||
1. Optional application registry
|
||||
1. Execution of custom handlers after some part of response was sent
|
||||
1. Configuring fallback handlers on the `ErrorHandler`
|
||||
1. Custom `LOGO` setting
|
||||
1. `sanic.response.stream`
|
||||
1. `AsyncioServer.init`
|
||||
|
||||
### Developer infrastructure
|
||||
- [#2449](https://github.com/sanic-org/sanic/pull/2449) Clean up `black` and `isort` config
|
||||
- [#2479](https://github.com/sanic-org/sanic/pull/2479) Fix some flappy tests
|
||||
|
||||
### Improved Documentation
|
||||
- [#2461](https://github.com/sanic-org/sanic/pull/2461) Update example to match current application naming standards
|
||||
- [#2466](https://github.com/sanic-org/sanic/pull/2466) Better type annotation for `Extend`
|
||||
- [#2485](https://github.com/sanic-org/sanic/pull/2485) Improved help messages in CLI
|
||||
|
||||
@@ -5,7 +5,7 @@ import asyncio
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
async def notify_server_started_after_five_seconds():
|
||||
|
||||
@@ -4,7 +4,7 @@ from sanic import Sanic
|
||||
from sanic.response import text
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.middleware("request")
|
||||
|
||||
@@ -6,7 +6,7 @@ from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
def check_request_for_authorization_status(request):
|
||||
|
||||
@@ -8,9 +8,9 @@ are added. And blueprint response middleware are executed in _reverse_ order.
|
||||
On a valid request, it should print "1 2 3 6 5 4" to terminal
|
||||
"""
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
bp = Blueprint("bp_" + __name__)
|
||||
bp = Blueprint("bp_example")
|
||||
|
||||
|
||||
@bp.on_request
|
||||
|
||||
@@ -2,10 +2,10 @@ from sanic import Blueprint, Sanic
|
||||
from sanic.response import file, json
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
blueprint = Blueprint("name", url_prefix="/my_blueprint")
|
||||
blueprint2 = Blueprint("name2", url_prefix="/my_blueprint2")
|
||||
blueprint3 = Blueprint("name3", url_prefix="/my_blueprint3")
|
||||
app = Sanic("Example")
|
||||
blueprint = Blueprint("bp_example", url_prefix="/my_blueprint")
|
||||
blueprint2 = Blueprint("bp_example2", url_prefix="/my_blueprint2")
|
||||
blueprint3 = Blueprint("bp_example3", url_prefix="/my_blueprint3")
|
||||
|
||||
|
||||
@blueprint.route("/foo")
|
||||
|
||||
@@ -3,7 +3,8 @@ from asyncio import sleep
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
app = Sanic(__name__, strict_slashes=True)
|
||||
app = Sanic("DelayedResponseApp", strict_slashes=True)
|
||||
app.config.AUTO_EXTEND = False
|
||||
|
||||
|
||||
@app.get("/")
|
||||
@@ -11,7 +12,7 @@ async def handler(request):
|
||||
return response.redirect("/sleep/3")
|
||||
|
||||
|
||||
@app.get("/sleep/<t:number>")
|
||||
@app.get("/sleep/<t:float>")
|
||||
async def handler2(request, t=0.3):
|
||||
await sleep(t)
|
||||
return response.text(f"Slept {t:.1f} seconds.\n")
|
||||
|
||||
@@ -41,7 +41,7 @@ from sanic import Sanic
|
||||
|
||||
|
||||
handler = CustomHandler()
|
||||
app = Sanic(__name__, error_handler=handler)
|
||||
app = Sanic("Example", error_handler=handler)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from sanic import Sanic
|
||||
from sanic import response
|
||||
from sanic import Sanic, response
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
@@ -9,5 +9,5 @@ async def test(request):
|
||||
return response.json({"test": True})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
@@ -6,7 +6,7 @@ from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
sem = None
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ LOG_SETTINGS = {
|
||||
}
|
||||
|
||||
|
||||
app = Sanic(__name__, log_config=LOG_SETTINGS)
|
||||
app = Sanic("Example", log_config=LOG_SETTINGS)
|
||||
|
||||
|
||||
@app.on_request
|
||||
|
||||
@@ -43,7 +43,7 @@ logdna = logging.getLogger(__name__)
|
||||
logdna.setLevel(logging.INFO)
|
||||
logdna.addHandler(logdna_handler)
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.middleware
|
||||
|
||||
@@ -2,27 +2,29 @@
|
||||
Modify header or status in response
|
||||
"""
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic import response
|
||||
|
||||
app = Sanic(__name__)
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
@app.route('/')
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def handle_request(request):
|
||||
return response.json(
|
||||
{'message': 'Hello world!'},
|
||||
headers={'X-Served-By': 'sanic'},
|
||||
status=200
|
||||
{"message": "Hello world!"},
|
||||
headers={"X-Served-By": "sanic"},
|
||||
status=200,
|
||||
)
|
||||
|
||||
|
||||
@app.route('/unauthorized')
|
||||
@app.route("/unauthorized")
|
||||
def handle_request(request):
|
||||
return response.json(
|
||||
{'message': 'You are not authorized'},
|
||||
headers={'X-Served-By': 'sanic'},
|
||||
status=404
|
||||
{"message": "You are not authorized"},
|
||||
headers={"X-Served-By": "sanic"},
|
||||
status=404,
|
||||
)
|
||||
|
||||
app.run(host="0.0.0.0", port=8000, debug=True)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000, debug=True)
|
||||
|
||||
@@ -32,7 +32,7 @@ def test_port(worker_id):
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def app():
|
||||
app = Sanic()
|
||||
app = Sanic("Example")
|
||||
|
||||
@app.route("/")
|
||||
async def index(request):
|
||||
|
||||
@@ -8,7 +8,6 @@ from sanic.handlers import ErrorHandler
|
||||
|
||||
|
||||
class RaygunExceptionReporter(ErrorHandler):
|
||||
|
||||
def __init__(self, raygun_api_key=None):
|
||||
super().__init__()
|
||||
if raygun_api_key is None:
|
||||
@@ -22,16 +21,13 @@ class RaygunExceptionReporter(ErrorHandler):
|
||||
|
||||
|
||||
raygun_error_reporter = RaygunExceptionReporter()
|
||||
app = Sanic(__name__, error_handler=raygun_error_reporter)
|
||||
app = Sanic("Example", error_handler=raygun_error_reporter)
|
||||
|
||||
|
||||
@app.route("/raise")
|
||||
async def test(request):
|
||||
raise SanicException('You Broke It!')
|
||||
raise SanicException("You Broke It!")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(
|
||||
host="0.0.0.0",
|
||||
port=getenv("PORT", 8080)
|
||||
)
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=getenv("PORT", 8080))
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
from sanic import Sanic
|
||||
from sanic import response
|
||||
from sanic import Sanic, response
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
|
||||
@app.route('/')
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def handle_request(request):
|
||||
return response.redirect('/redirect')
|
||||
return response.redirect("/redirect")
|
||||
|
||||
|
||||
@app.route('/redirect')
|
||||
@app.route("/redirect")
|
||||
async def test(request):
|
||||
return response.json({"Redirected": True})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
@@ -1,65 +1,63 @@
|
||||
from sanic import Sanic
|
||||
from sanic.views import CompositionView
|
||||
from sanic.views import HTTPMethodView
|
||||
from sanic.views import stream as stream_decorator
|
||||
from sanic.blueprints import Blueprint
|
||||
from sanic.response import stream, text
|
||||
from sanic.views import HTTPMethodView
|
||||
from sanic.views import stream as stream_decorator
|
||||
|
||||
bp = Blueprint('blueprint_request_stream')
|
||||
app = Sanic('request_stream')
|
||||
|
||||
bp = Blueprint("bp_example")
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
class SimpleView(HTTPMethodView):
|
||||
|
||||
@stream_decorator
|
||||
async def post(self, request):
|
||||
result = ''
|
||||
result = ""
|
||||
while True:
|
||||
body = await request.stream.get()
|
||||
if body is None:
|
||||
break
|
||||
result += body.decode('utf-8')
|
||||
result += body.decode("utf-8")
|
||||
return text(result)
|
||||
|
||||
|
||||
@app.post('/stream', stream=True)
|
||||
@app.post("/stream", stream=True)
|
||||
async def handler(request):
|
||||
async def streaming(response):
|
||||
while True:
|
||||
body = await request.stream.get()
|
||||
if body is None:
|
||||
break
|
||||
body = body.decode('utf-8').replace('1', 'A')
|
||||
body = body.decode("utf-8").replace("1", "A")
|
||||
await response.write(body)
|
||||
|
||||
return stream(streaming)
|
||||
|
||||
|
||||
@bp.put('/bp_stream', stream=True)
|
||||
@bp.put("/bp_stream", stream=True)
|
||||
async def bp_handler(request):
|
||||
result = ''
|
||||
result = ""
|
||||
while True:
|
||||
body = await request.stream.get()
|
||||
if body is None:
|
||||
break
|
||||
result += body.decode('utf-8').replace('1', 'A')
|
||||
result += body.decode("utf-8").replace("1", "A")
|
||||
return text(result)
|
||||
|
||||
|
||||
async def post_handler(request):
|
||||
result = ''
|
||||
result = ""
|
||||
while True:
|
||||
body = await request.stream.get()
|
||||
if body is None:
|
||||
break
|
||||
result += body.decode('utf-8')
|
||||
result += body.decode("utf-8")
|
||||
return text(result)
|
||||
|
||||
|
||||
app.blueprint(bp)
|
||||
app.add_route(SimpleView.as_view(), '/method_view')
|
||||
view = CompositionView()
|
||||
view.add(['POST'], post_handler, stream=True)
|
||||
app.add_route(view, '/composition_view')
|
||||
app.add_route(SimpleView.as_view(), "/method_view")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=8000)
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import asyncio
|
||||
from sanic import Sanic
|
||||
from sanic import response
|
||||
|
||||
from sanic import Sanic, response
|
||||
from sanic.config import Config
|
||||
from sanic.exceptions import RequestTimeout
|
||||
|
||||
|
||||
Config.REQUEST_TIMEOUT = 1
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
await asyncio.sleep(3)
|
||||
return response.text('Hello, world!')
|
||||
return response.text("Hello, world!")
|
||||
|
||||
|
||||
@app.exception(RequestTimeout)
|
||||
def timeout(request, exception):
|
||||
return response.text('RequestTimeout from error_handler.', 408)
|
||||
return response.text("RequestTimeout from error_handler.", 408)
|
||||
|
||||
app.run(host='0.0.0.0', port=8000)
|
||||
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
from os import getenv
|
||||
|
||||
import rollbar
|
||||
|
||||
from sanic.handlers import ErrorHandler
|
||||
from sanic import Sanic
|
||||
from sanic.exceptions import SanicException
|
||||
from os import getenv
|
||||
from sanic.handlers import ErrorHandler
|
||||
|
||||
|
||||
rollbar.init(getenv("ROLLBAR_API_KEY"))
|
||||
|
||||
|
||||
class RollbarExceptionHandler(ErrorHandler):
|
||||
|
||||
def default(self, request, exception):
|
||||
rollbar.report_message(str(exception))
|
||||
return super().default(request, exception)
|
||||
|
||||
|
||||
app = Sanic(__name__, error_handler=RollbarExceptionHandler())
|
||||
app = Sanic("Example", error_handler=RollbarExceptionHandler())
|
||||
|
||||
|
||||
@app.route("/raise")
|
||||
@@ -24,7 +25,4 @@ def create_error(request):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(
|
||||
host="0.0.0.0",
|
||||
port=getenv("PORT", 8080)
|
||||
)
|
||||
app.run(host="0.0.0.0", port=getenv("PORT", 8080))
|
||||
|
||||
@@ -11,7 +11,7 @@ from pathlib import Path
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/text")
|
||||
|
||||
@@ -5,7 +5,7 @@ import uvloop
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
|
||||
@@ -8,7 +8,7 @@ from sanic import Sanic, response
|
||||
from sanic.server import AsyncioServer
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.before_server_start
|
||||
|
||||
@@ -6,20 +6,19 @@ from sentry_sdk.integrations.sanic import SanicIntegration
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
|
||||
sentry_init(
|
||||
dsn=getenv("SENTRY_DSN"),
|
||||
integrations=[SanicIntegration()],
|
||||
)
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
@app.route("/working")
|
||||
async def working_path(request):
|
||||
return json({
|
||||
"response": "Working API Response"
|
||||
})
|
||||
return json({"response": "Working API Response"})
|
||||
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
@@ -28,8 +27,5 @@ async def raise_error(request):
|
||||
raise Exception("Testing Sentry Integration")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(
|
||||
host="0.0.0.0",
|
||||
port=getenv("PORT", 8080)
|
||||
)
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=getenv("PORT", 8080))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
app.static("/", "./static")
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
from sanic import Sanic
|
||||
from sanic import response as res
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
async def test(req):
|
||||
return res.text("I\'m a teapot", status=418)
|
||||
return res.text("I'm a teapot", status=418)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
@@ -5,7 +5,7 @@ from sanic.exceptions import ServerError
|
||||
from sanic.log import logger as log
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
|
||||
@@ -4,7 +4,7 @@ import socket
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/test")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
@app.route("/")
|
||||
|
||||
@@ -8,7 +8,7 @@ from sanic.blueprints import Blueprint
|
||||
# curl -H "Host: bp.example.com" localhost:8000/question
|
||||
# curl -H "Host: bp.example.com" localhost:8000/answer
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
bp = Blueprint("bp", host="bp.example.com")
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ from sanic import Sanic
|
||||
from sanic.response import redirect
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
app = Sanic("Example")
|
||||
|
||||
|
||||
app.static("index.html", "websocket.html")
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
requires = ["setuptools<60.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.black]
|
||||
line-length = 79
|
||||
|
||||
[tool.isort]
|
||||
atomic = true
|
||||
default_section = "THIRDPARTY"
|
||||
include_trailing_comma = true
|
||||
known_first_party = "sanic"
|
||||
known_third_party = "pytest"
|
||||
line_length = 79
|
||||
lines_after_imports = 2
|
||||
lines_between_types = 1
|
||||
multi_line_output = 3
|
||||
profile = "black"
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = [
|
||||
"httptools.*",
|
||||
"trustme.*",
|
||||
"sanic_routing.*",
|
||||
]
|
||||
ignore_missing_imports = true
|
||||
|
||||
@@ -6,4 +6,4 @@ python:
|
||||
path: .
|
||||
extra_requirements:
|
||||
- docs
|
||||
system_packages: true
|
||||
system_packages: true
|
||||
|
||||
@@ -4,6 +4,7 @@ from sanic.blueprints import Blueprint
|
||||
from sanic.constants import HTTPMethod
|
||||
from sanic.request import Request
|
||||
from sanic.response import HTTPResponse, html, json, text
|
||||
from sanic.server.websockets.impl import WebsocketImplProtocol as Websocket
|
||||
|
||||
|
||||
__all__ = (
|
||||
@@ -13,6 +14,7 @@ __all__ = (
|
||||
"HTTPMethod",
|
||||
"HTTPResponse",
|
||||
"Request",
|
||||
"Websocket",
|
||||
"html",
|
||||
"json",
|
||||
"text",
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "21.12.0dev"
|
||||
__version__ = "22.6.2"
|
||||
|
||||
958
sanic/app.py
958
sanic/app.py
File diff suppressed because it is too large
Load Diff
23
sanic/application/constants.py
Normal file
23
sanic/application/constants.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from enum import Enum, IntEnum, auto
|
||||
|
||||
|
||||
class StrEnum(str, Enum):
|
||||
def _generate_next_value_(name: str, *args) -> str: # type: ignore
|
||||
return name.lower()
|
||||
|
||||
|
||||
class Server(StrEnum):
|
||||
SANIC = auto()
|
||||
ASGI = auto()
|
||||
GUNICORN = auto()
|
||||
|
||||
|
||||
class Mode(StrEnum):
|
||||
PRODUCTION = auto()
|
||||
DEBUG = auto()
|
||||
|
||||
|
||||
class ServerStage(IntEnum):
|
||||
STOPPED = auto()
|
||||
PARTIAL = auto()
|
||||
SERVING = auto()
|
||||
39
sanic/application/ext.py
Normal file
39
sanic/application/ext.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import suppress
|
||||
from importlib import import_module
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic
|
||||
|
||||
try:
|
||||
from sanic_ext import Extend # type: ignore
|
||||
except ImportError:
|
||||
...
|
||||
|
||||
|
||||
def setup_ext(app: Sanic, *, fail: bool = False, **kwargs):
|
||||
if not app.config.AUTO_EXTEND:
|
||||
return
|
||||
|
||||
sanic_ext = None
|
||||
with suppress(ModuleNotFoundError):
|
||||
sanic_ext = import_module("sanic_ext")
|
||||
|
||||
if not sanic_ext:
|
||||
if fail:
|
||||
raise RuntimeError(
|
||||
"Sanic Extensions is not installed. You can add it to your "
|
||||
"environment using:\n$ pip install sanic[ext]\nor\n$ pip "
|
||||
"install sanic-ext"
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
if not getattr(app, "_ext", None):
|
||||
Ext: Extend = getattr(sanic_ext, "Extend")
|
||||
app._ext = Ext(app, **kwargs)
|
||||
|
||||
return app.ext
|
||||
@@ -3,6 +3,8 @@ import sys
|
||||
|
||||
from os import environ
|
||||
|
||||
from sanic.compat import is_atty
|
||||
|
||||
|
||||
BASE_LOGO = """
|
||||
|
||||
@@ -44,7 +46,7 @@ ansi_pattern = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
||||
def get_logo(full=False, coffee=False):
|
||||
logo = (
|
||||
(FULL_COLOR_LOGO if full else (COFFEE_LOGO if coffee else COLOR_LOGO))
|
||||
if sys.stdout.isatty()
|
||||
if is_atty()
|
||||
else BASE_LOGO
|
||||
)
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import sys
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from shutil import get_terminal_size
|
||||
from textwrap import indent, wrap
|
||||
from typing import Dict, Optional
|
||||
|
||||
from sanic import __version__
|
||||
from sanic.compat import is_atty
|
||||
from sanic.log import logger
|
||||
|
||||
|
||||
@@ -36,14 +35,11 @@ class MOTD(ABC):
|
||||
data: Dict[str, str],
|
||||
extra: Dict[str, str],
|
||||
) -> None:
|
||||
motd_class = MOTDTTY if sys.stdout.isatty() else MOTDBasic
|
||||
motd_class = MOTDTTY if is_atty() else MOTDBasic
|
||||
motd_class(logo, serve_location, data, extra).display()
|
||||
|
||||
|
||||
class MOTDBasic(MOTD):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def display(self):
|
||||
if self.logo:
|
||||
logger.debug(self.logo)
|
||||
|
||||
86
sanic/application/spinner.py
Normal file
86
sanic/application/spinner.py
Normal file
@@ -0,0 +1,86 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from contextlib import contextmanager
|
||||
from queue import Queue
|
||||
from threading import Thread
|
||||
|
||||
|
||||
if os.name == "nt": # noqa
|
||||
import ctypes # noqa
|
||||
|
||||
class _CursorInfo(ctypes.Structure):
|
||||
_fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
|
||||
|
||||
|
||||
class Spinner: # noqa
|
||||
def __init__(self, message: str) -> None:
|
||||
self.message = message
|
||||
self.queue: Queue[int] = Queue()
|
||||
self.spinner = self.cursor()
|
||||
self.thread = Thread(target=self.run)
|
||||
|
||||
def start(self):
|
||||
self.queue.put(1)
|
||||
self.thread.start()
|
||||
self.hide()
|
||||
|
||||
def run(self):
|
||||
while self.queue.get():
|
||||
output = f"\r{self.message} [{next(self.spinner)}]"
|
||||
sys.stdout.write(output)
|
||||
sys.stdout.flush()
|
||||
time.sleep(0.1)
|
||||
self.queue.put(1)
|
||||
|
||||
def stop(self):
|
||||
self.queue.put(0)
|
||||
self.thread.join()
|
||||
self.show()
|
||||
|
||||
@staticmethod
|
||||
def cursor():
|
||||
while True:
|
||||
for cursor in "|/-\\":
|
||||
yield cursor
|
||||
|
||||
@staticmethod
|
||||
def hide():
|
||||
if os.name == "nt":
|
||||
ci = _CursorInfo()
|
||||
handle = ctypes.windll.kernel32.GetStdHandle(-11)
|
||||
ctypes.windll.kernel32.GetConsoleCursorInfo(
|
||||
handle, ctypes.byref(ci)
|
||||
)
|
||||
ci.visible = False
|
||||
ctypes.windll.kernel32.SetConsoleCursorInfo(
|
||||
handle, ctypes.byref(ci)
|
||||
)
|
||||
elif os.name == "posix":
|
||||
sys.stdout.write("\033[?25l")
|
||||
sys.stdout.flush()
|
||||
|
||||
@staticmethod
|
||||
def show():
|
||||
if os.name == "nt":
|
||||
ci = _CursorInfo()
|
||||
handle = ctypes.windll.kernel32.GetStdHandle(-11)
|
||||
ctypes.windll.kernel32.GetConsoleCursorInfo(
|
||||
handle, ctypes.byref(ci)
|
||||
)
|
||||
ci.visible = True
|
||||
ctypes.windll.kernel32.SetConsoleCursorInfo(
|
||||
handle, ctypes.byref(ci)
|
||||
)
|
||||
elif os.name == "posix":
|
||||
sys.stdout.write("\033[?25h")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def loading(message: str = "Loading"): # noqa
|
||||
spinner = Spinner(message)
|
||||
spinner.start()
|
||||
yield
|
||||
spinner.stop()
|
||||
@@ -3,31 +3,25 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Set, Union
|
||||
from socket import socket
|
||||
from ssl import SSLContext
|
||||
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union
|
||||
|
||||
from sanic.log import logger
|
||||
from sanic.application.constants import Mode, Server, ServerStage
|
||||
from sanic.log import VerbosityFilter, logger
|
||||
from sanic.server.async_server import AsyncioServer
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
class StrEnum(str, Enum):
|
||||
def _generate_next_value_(name: str, *args) -> str: # type: ignore
|
||||
return name.lower()
|
||||
|
||||
|
||||
class Server(StrEnum):
|
||||
SANIC = auto()
|
||||
ASGI = auto()
|
||||
GUNICORN = auto()
|
||||
|
||||
|
||||
class Mode(StrEnum):
|
||||
PRODUCTION = auto()
|
||||
DEBUG = auto()
|
||||
@dataclass
|
||||
class ApplicationServerInfo:
|
||||
settings: Dict[str, Any]
|
||||
stage: ServerStage = field(default=ServerStage.STOPPED)
|
||||
server: Optional[AsyncioServer] = field(default=None)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -37,15 +31,21 @@ class ApplicationState:
|
||||
coffee: bool = field(default=False)
|
||||
fast: bool = field(default=False)
|
||||
host: str = field(default="")
|
||||
mode: Mode = field(default=Mode.PRODUCTION)
|
||||
port: int = field(default=0)
|
||||
ssl: Optional[SSLContext] = field(default=None)
|
||||
sock: Optional[socket] = field(default=None)
|
||||
unix: Optional[str] = field(default=None)
|
||||
mode: Mode = field(default=Mode.PRODUCTION)
|
||||
reload_dirs: Set[Path] = field(default_factory=set)
|
||||
auto_reload: bool = field(default=False)
|
||||
server: Server = field(default=Server.SANIC)
|
||||
is_running: bool = field(default=False)
|
||||
is_started: bool = field(default=False)
|
||||
is_stopping: bool = field(default=False)
|
||||
verbosity: int = field(default=0)
|
||||
workers: int = field(default=0)
|
||||
primary: bool = field(default=True)
|
||||
server_info: List[ApplicationServerInfo] = field(default_factory=list)
|
||||
|
||||
# This property relates to the ApplicationState instance and should
|
||||
# not be changed except in the __post_init__ method
|
||||
@@ -69,6 +69,23 @@ class ApplicationState:
|
||||
if getattr(self.app, "configure_logging", False) and self.app.debug:
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
def set_verbosity(self, value: int):
|
||||
VerbosityFilter.verbosity = value
|
||||
|
||||
@property
|
||||
def is_debug(self):
|
||||
return self.mode is Mode.DEBUG
|
||||
|
||||
@property
|
||||
def stage(self) -> ServerStage:
|
||||
if not self.server_info:
|
||||
return ServerStage.STOPPED
|
||||
|
||||
if all(info.stage is ServerStage.SERVING for info in self.server_info):
|
||||
return ServerStage.SERVING
|
||||
elif any(
|
||||
info.stage is ServerStage.SERVING for info in self.server_info
|
||||
):
|
||||
return ServerStage.PARTIAL
|
||||
|
||||
return ServerStage.STOPPED
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
|
||||
from typing import Optional
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import sanic.app # noqa
|
||||
|
||||
from sanic.compat import Header
|
||||
from sanic.exceptions import ServerError
|
||||
from sanic.helpers import _default
|
||||
from sanic.http import Stage
|
||||
from sanic.log import logger
|
||||
from sanic.models.asgi import ASGIReceive, ASGIScope, ASGISend, MockTransport
|
||||
from sanic.request import Request
|
||||
from sanic.response import BaseHTTPResponse
|
||||
@@ -15,29 +17,35 @@ from sanic.server import ConnInfo
|
||||
from sanic.server.websockets.connection import WebSocketConnection
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
class Lifespan:
|
||||
def __init__(self, asgi_app: "ASGIApp") -> None:
|
||||
def __init__(self, asgi_app: ASGIApp) -> None:
|
||||
self.asgi_app = asgi_app
|
||||
|
||||
if (
|
||||
"server.init.before"
|
||||
in self.asgi_app.sanic_app.signal_router.name_index
|
||||
):
|
||||
warnings.warn(
|
||||
logger.debug(
|
||||
'You have set a listener for "before_server_start" '
|
||||
"in ASGI mode. "
|
||||
"It will be executed as early as possible, but not before "
|
||||
"the ASGI server is started."
|
||||
"the ASGI server is started.",
|
||||
extra={"verbosity": 1},
|
||||
)
|
||||
if (
|
||||
"server.shutdown.after"
|
||||
in self.asgi_app.sanic_app.signal_router.name_index
|
||||
):
|
||||
warnings.warn(
|
||||
logger.debug(
|
||||
'You have set a listener for "after_server_stop" '
|
||||
"in ASGI mode. "
|
||||
"It will be executed as late as possible, but not after "
|
||||
"the ASGI server is stopped."
|
||||
"the ASGI server is stopped.",
|
||||
extra={"verbosity": 1},
|
||||
)
|
||||
|
||||
async def startup(self) -> None:
|
||||
@@ -53,6 +61,13 @@ class Lifespan:
|
||||
await self.asgi_app.sanic_app._server_event("init", "before")
|
||||
await self.asgi_app.sanic_app._server_event("init", "after")
|
||||
|
||||
if self.asgi_app.sanic_app.config.USE_UVLOOP is not _default:
|
||||
warnings.warn(
|
||||
"You have set the USE_UVLOOP configuration option, but Sanic "
|
||||
"cannot control the event loop when running in ASGI mode."
|
||||
"This option will be ignored."
|
||||
)
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
"""
|
||||
Gather the listeners to fire on server stop.
|
||||
@@ -80,7 +95,7 @@ class Lifespan:
|
||||
|
||||
|
||||
class ASGIApp:
|
||||
sanic_app: "sanic.app.Sanic"
|
||||
sanic_app: Sanic
|
||||
request: Request
|
||||
transport: MockTransport
|
||||
lifespan: Lifespan
|
||||
@@ -149,6 +164,13 @@ class ASGIApp:
|
||||
instance.request_body = True
|
||||
instance.request.conn_info = ConnInfo(instance.transport)
|
||||
|
||||
await sanic_app.dispatch(
|
||||
"http.lifecycle.request",
|
||||
inline=True,
|
||||
context={"request": instance.request},
|
||||
fail_not_found=False,
|
||||
)
|
||||
|
||||
return instance
|
||||
|
||||
async def read(self) -> Optional[bytes]:
|
||||
|
||||
0
sanic/base/__init__.py
Normal file
0
sanic/base/__init__.py
Normal file
6
sanic/base/meta.py
Normal file
6
sanic/base/meta.py
Normal file
@@ -0,0 +1,6 @@
|
||||
class SanicMeta(type):
|
||||
@classmethod
|
||||
def __prepare__(metaclass, name, bases, **kwds):
|
||||
cls = super().__prepare__(metaclass, name, bases, **kwds)
|
||||
cls["__slots__"] = ()
|
||||
return cls
|
||||
@@ -1,8 +1,8 @@
|
||||
import re
|
||||
|
||||
from typing import Any, Tuple
|
||||
from warnings import warn
|
||||
from typing import Any
|
||||
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.exceptions import SanicException
|
||||
from sanic.mixins.exceptions import ExceptionMixin
|
||||
from sanic.mixins.listeners import ListenerMixin
|
||||
@@ -20,8 +20,9 @@ class BaseSanic(
|
||||
ListenerMixin,
|
||||
ExceptionMixin,
|
||||
SignalMixin,
|
||||
metaclass=SanicMeta,
|
||||
):
|
||||
__fake_slots__: Tuple[str, ...]
|
||||
__slots__ = ("name",)
|
||||
|
||||
def __init__(self, name: str = None, *args: Any, **kwargs: Any) -> None:
|
||||
class_name = self.__class__.__name__
|
||||
@@ -33,11 +34,10 @@ class BaseSanic(
|
||||
)
|
||||
|
||||
if not VALID_NAME.match(name):
|
||||
warn(
|
||||
f"{class_name} instance named '{name}' uses a format that is"
|
||||
f"deprecated. Starting in version 21.12, {class_name} objects "
|
||||
"must be named only using alphanumeric characters, _, or -.",
|
||||
DeprecationWarning,
|
||||
raise SanicException(
|
||||
f"{class_name} instance named '{name}' uses an invalid "
|
||||
"format. Names must begin with a character and may only "
|
||||
"contain alphanumeric characters, _, or -."
|
||||
)
|
||||
|
||||
self.name = name
|
||||
@@ -52,15 +52,12 @@ class BaseSanic(
|
||||
return f'{self.__class__.__name__}(name="{self.name}")'
|
||||
|
||||
def __setattr__(self, name: str, value: Any) -> None:
|
||||
# This is a temporary compat layer so we can raise a warning until
|
||||
# setting attributes on the app instance can be removed and deprecated
|
||||
# with a proper implementation of __slots__
|
||||
if name not in self.__fake_slots__:
|
||||
warn(
|
||||
try:
|
||||
super().__setattr__(name, value)
|
||||
except AttributeError as e:
|
||||
raise AttributeError(
|
||||
f"Setting variables on {self.__class__.__name__} instances is "
|
||||
"deprecated and will be removed in version 21.12. You should "
|
||||
f"change your {self.__class__.__name__} instance to use "
|
||||
"not allowed. You should change your "
|
||||
f"{self.__class__.__name__} instance to use "
|
||||
f"instance.ctx.{name} instead.",
|
||||
DeprecationWarning,
|
||||
)
|
||||
super().__setattr__(name, value)
|
||||
) from e
|
||||
@@ -21,10 +21,10 @@ from typing import (
|
||||
Union,
|
||||
)
|
||||
|
||||
from sanic_routing.exceptions import NotFound # type: ignore
|
||||
from sanic_routing.route import Route # type: ignore
|
||||
from sanic_routing.exceptions import NotFound
|
||||
from sanic_routing.route import Route
|
||||
|
||||
from sanic.base import BaseSanic
|
||||
from sanic.base.root import BaseSanic
|
||||
from sanic.blueprint_group import BlueprintGroup
|
||||
from sanic.exceptions import SanicException
|
||||
from sanic.helpers import Default, _default
|
||||
@@ -37,7 +37,7 @@ from sanic.models.handler_types import (
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic # noqa
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
def lazy(func, as_decorator=True):
|
||||
@@ -85,7 +85,7 @@ class Blueprint(BaseSanic):
|
||||
trailing */*
|
||||
"""
|
||||
|
||||
__fake_slots__ = (
|
||||
__slots__ = (
|
||||
"_apps",
|
||||
"_future_routes",
|
||||
"_future_statics",
|
||||
@@ -98,7 +98,6 @@ class Blueprint(BaseSanic):
|
||||
"host",
|
||||
"listeners",
|
||||
"middlewares",
|
||||
"name",
|
||||
"routes",
|
||||
"statics",
|
||||
"strict_slashes",
|
||||
@@ -107,7 +106,6 @@ class Blueprint(BaseSanic):
|
||||
"version_prefix",
|
||||
"websocket_routes",
|
||||
)
|
||||
__pre_registry__: Dict[Union[str, Default], Any] = defaultdict(list)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -349,6 +347,7 @@ class Blueprint(BaseSanic):
|
||||
future.static,
|
||||
version_prefix,
|
||||
error_format,
|
||||
future.route_context,
|
||||
)
|
||||
|
||||
if (self, apply_route) in app._future_registry:
|
||||
@@ -401,8 +400,9 @@ class Blueprint(BaseSanic):
|
||||
for future in self._future_signals:
|
||||
if (self, future) in app._future_registry:
|
||||
continue
|
||||
future.condition.update({"blueprint": self.name})
|
||||
app._apply_signal(future)
|
||||
future.condition.update({"__blueprint__": self.name})
|
||||
# Force exclusive to be False
|
||||
app._apply_signal(tuple((*future[:-1], False)))
|
||||
|
||||
self.routes += [route for route in routes if isinstance(route, Route)]
|
||||
self.websocket_routes += [
|
||||
@@ -427,7 +427,7 @@ class Blueprint(BaseSanic):
|
||||
|
||||
async def dispatch(self, *args, **kwargs):
|
||||
condition = kwargs.pop("condition", {})
|
||||
condition.update({"blueprint": self.name})
|
||||
condition.update({"__blueprint__": self.name})
|
||||
kwargs["condition"] = condition
|
||||
await asyncio.gather(
|
||||
*[app.dispatch(*args, **kwargs) for app in self.apps]
|
||||
@@ -462,30 +462,3 @@ class Blueprint(BaseSanic):
|
||||
):
|
||||
for app in apps:
|
||||
app._future_registry.update(set((bp, item) for item in futures))
|
||||
|
||||
def pre_register(
|
||||
self,
|
||||
name: Union[str, Default],
|
||||
url_prefix: Optional[str] = None,
|
||||
host: Optional[Union[List[str], str]] = None,
|
||||
version: Optional[Union[int, str, float]] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
version_prefix: Union[str, Default] = _default,
|
||||
) -> None:
|
||||
if not hasattr(self.ctx, "_prereg"):
|
||||
self.ctx._prereg = []
|
||||
self.ctx._prereg.append(name)
|
||||
self.__class__.__pre_registry__[name].append(
|
||||
{
|
||||
k: v
|
||||
for k, v in {
|
||||
"bp": self,
|
||||
"url_prefix": url_prefix,
|
||||
"host": host,
|
||||
"version": version,
|
||||
"strict_slashes": strict_slashes,
|
||||
"version_prefix": version_prefix,
|
||||
}.items()
|
||||
if v is not None and v is not _default
|
||||
}
|
||||
)
|
||||
|
||||
@@ -10,9 +10,7 @@ from typing import Any, List, Union
|
||||
|
||||
from sanic.app import Sanic
|
||||
from sanic.application.logo import get_logo
|
||||
from sanic.blueprints import Blueprint
|
||||
from sanic.cli.arguments import Group
|
||||
from sanic.helpers import _default
|
||||
from sanic.log import error_logger
|
||||
from sanic.simple import create_simple_server
|
||||
|
||||
@@ -22,7 +20,6 @@ class SanicArgumentParser(ArgumentParser):
|
||||
|
||||
|
||||
class SanicCLI:
|
||||
DEFAULT_APP_NAME = "SANIC"
|
||||
DESCRIPTION = indent(
|
||||
f"""
|
||||
{get_logo(True)}
|
||||
@@ -61,34 +58,41 @@ Or, a path to a directory to run as a simple HTTP server:
|
||||
os.environ.get("SANIC_RELOADER_PROCESS", "") != "true"
|
||||
)
|
||||
self.args: List[Any] = []
|
||||
self.groups: List[Group] = []
|
||||
|
||||
def attach(self):
|
||||
for group in Group._registry:
|
||||
group.create(self.parser).attach()
|
||||
instance = group.create(self.parser)
|
||||
instance.attach()
|
||||
self.groups.append(instance)
|
||||
|
||||
def run(self):
|
||||
# This is to provide backwards compat -v to display version
|
||||
legacy_version = len(sys.argv) == 2 and sys.argv[-1] == "-v"
|
||||
parse_args = ["--version"] if legacy_version else None
|
||||
|
||||
if not parse_args:
|
||||
parsed, unknown = self.parser.parse_known_args()
|
||||
if unknown and parsed.factory:
|
||||
for arg in unknown:
|
||||
if arg.startswith("--"):
|
||||
self.parser.add_argument(arg.split("=")[0])
|
||||
|
||||
self.args = self.parser.parse_args(args=parse_args)
|
||||
self._precheck()
|
||||
|
||||
try:
|
||||
app = self._get_app()
|
||||
kwargs = self._build_run_kwargs()
|
||||
app.run(**kwargs)
|
||||
except ValueError:
|
||||
error_logger.exception("Failed to run app")
|
||||
else:
|
||||
for http_version in self.args.http:
|
||||
app.prepare(**kwargs, version=http_version)
|
||||
|
||||
Sanic.serve()
|
||||
|
||||
def _precheck(self):
|
||||
if self.args.debug and self.main_process:
|
||||
error_logger.warning(
|
||||
"Starting in v22.3, --debug will no "
|
||||
"longer automatically run the auto-reloader.\n Switch to "
|
||||
"--dev to continue using that functionality."
|
||||
)
|
||||
|
||||
# # Custom TLS mismatch handling for better diagnostics
|
||||
if self.main_process and (
|
||||
# one of cert/key missing
|
||||
@@ -123,6 +127,14 @@ Or, a path to a directory to run as a simple HTTP server:
|
||||
delimiter = ":" if ":" in self.args.module else "."
|
||||
module_name, app_name = self.args.module.rsplit(delimiter, 1)
|
||||
|
||||
if module_name == "" and os.path.isdir(self.args.module):
|
||||
raise ValueError(
|
||||
"App not found.\n"
|
||||
" Please use --simple if you are passing a "
|
||||
"directory to sanic.\n"
|
||||
f" eg. sanic {self.args.module} --simple"
|
||||
)
|
||||
|
||||
if app_name.endswith("()"):
|
||||
self.args.factory = True
|
||||
app_name = app_name[:-2]
|
||||
@@ -130,24 +142,26 @@ Or, a path to a directory to run as a simple HTTP server:
|
||||
module = import_module(module_name)
|
||||
app = getattr(module, app_name, None)
|
||||
if self.args.factory:
|
||||
app = app()
|
||||
try:
|
||||
app = app(self.args)
|
||||
except TypeError:
|
||||
app = app()
|
||||
|
||||
app_type_name = type(app).__name__
|
||||
|
||||
if isinstance(app, Blueprint):
|
||||
bp = app
|
||||
name = (
|
||||
bp.ctx._prereg[0]
|
||||
if hasattr(bp.ctx, "_prereg")
|
||||
else _default
|
||||
)
|
||||
if name is _default:
|
||||
name = self.DEFAULT_APP_NAME
|
||||
app = Sanic(name)
|
||||
elif not isinstance(app, Sanic):
|
||||
if not isinstance(app, Sanic):
|
||||
if callable(app):
|
||||
solution = f"sanic {self.args.module} --factory"
|
||||
raise ValueError(
|
||||
"Module is not a Sanic app, it is a "
|
||||
f"{app_type_name}\n"
|
||||
" If this callable returns a "
|
||||
f"Sanic instance try: \n{solution}"
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
f"Module is not a Sanic app, it is a {app_type_name}\n"
|
||||
f" Perhaps you meant {self.args.module}.app?"
|
||||
f" Perhaps you meant {self.args.module}:app?"
|
||||
)
|
||||
except ImportError as e:
|
||||
if module_name.startswith(e.name):
|
||||
@@ -156,11 +170,14 @@ Or, a path to a directory to run as a simple HTTP server:
|
||||
" Example File: project/sanic_server.py -> app\n"
|
||||
" Example Module: project.sanic_server.app"
|
||||
)
|
||||
sys.exit(1)
|
||||
else:
|
||||
raise e
|
||||
return app
|
||||
|
||||
def _build_run_kwargs(self):
|
||||
for group in self.groups:
|
||||
group.prepare(self.args)
|
||||
ssl: Union[None, dict, str, list] = []
|
||||
if self.args.tlshost:
|
||||
ssl.append(None)
|
||||
@@ -185,18 +202,15 @@ Or, a path to a directory to run as a simple HTTP server:
|
||||
"unix": self.args.unix,
|
||||
"verbosity": self.args.verbosity or 0,
|
||||
"workers": self.args.workers,
|
||||
"auto_tls": self.args.auto_tls,
|
||||
}
|
||||
|
||||
if self.args.auto_reload:
|
||||
kwargs["auto_reload"] = True
|
||||
for maybe_arg in ("auto_reload", "dev"):
|
||||
if getattr(self.args, maybe_arg, False):
|
||||
kwargs[maybe_arg] = True
|
||||
|
||||
if self.args.path:
|
||||
if self.args.auto_reload or self.args.debug:
|
||||
kwargs["reload_dir"] = self.args.path
|
||||
else:
|
||||
error_logger.warning(
|
||||
"Ignoring '--reload-dir' since auto reloading was not "
|
||||
"enabled. If you would like to watch directories for "
|
||||
"changes, consider using --debug or --auto-reload."
|
||||
)
|
||||
kwargs["auto_reload"] = True
|
||||
kwargs["reload_dir"] = self.args.path
|
||||
|
||||
return kwargs
|
||||
|
||||
@@ -3,9 +3,10 @@ from __future__ import annotations
|
||||
from argparse import ArgumentParser, _ArgumentGroup
|
||||
from typing import List, Optional, Type, Union
|
||||
|
||||
from sanic_routing import __version__ as __routing_version__ # type: ignore
|
||||
from sanic_routing import __version__ as __routing_version__
|
||||
|
||||
from sanic import __version__
|
||||
from sanic.http.constants import HTTP
|
||||
|
||||
|
||||
class Group:
|
||||
@@ -38,6 +39,9 @@ class Group:
|
||||
"--no-" + args[0][2:], *args[1:], action="store_false", **kwargs
|
||||
)
|
||||
|
||||
def prepare(self, args) -> None:
|
||||
...
|
||||
|
||||
|
||||
class GeneralGroup(Group):
|
||||
name = None
|
||||
@@ -83,6 +87,44 @@ class ApplicationGroup(Group):
|
||||
)
|
||||
|
||||
|
||||
class HTTPVersionGroup(Group):
|
||||
name = "HTTP version"
|
||||
|
||||
def attach(self):
|
||||
http_values = [http.value for http in HTTP.__members__.values()]
|
||||
|
||||
self.container.add_argument(
|
||||
"--http",
|
||||
dest="http",
|
||||
action="append",
|
||||
choices=http_values,
|
||||
type=int,
|
||||
help=(
|
||||
"Which HTTP version to use: HTTP/1.1 or HTTP/3. Value should\n"
|
||||
"be either 1, or 3. [default 1]"
|
||||
),
|
||||
)
|
||||
self.container.add_argument(
|
||||
"-1",
|
||||
dest="http",
|
||||
action="append_const",
|
||||
const=1,
|
||||
help=("Run Sanic server using HTTP/1.1"),
|
||||
)
|
||||
self.container.add_argument(
|
||||
"-3",
|
||||
dest="http",
|
||||
action="append_const",
|
||||
const=3,
|
||||
help=("Run Sanic server using HTTP/3"),
|
||||
)
|
||||
|
||||
def prepare(self, args):
|
||||
if not args.http:
|
||||
args.http = [1]
|
||||
args.http = tuple(sorted(set(map(HTTP, args.http)), reverse=True))
|
||||
|
||||
|
||||
class SocketGroup(Group):
|
||||
name = "Socket binding"
|
||||
|
||||
@@ -92,7 +134,6 @@ class SocketGroup(Group):
|
||||
"--host",
|
||||
dest="host",
|
||||
type=str,
|
||||
default="127.0.0.1",
|
||||
help="Host address [default 127.0.0.1]",
|
||||
)
|
||||
self.container.add_argument(
|
||||
@@ -100,7 +141,6 @@ class SocketGroup(Group):
|
||||
"--port",
|
||||
dest="port",
|
||||
type=int,
|
||||
default=8000,
|
||||
help="Port to serve on [default 8000]",
|
||||
)
|
||||
self.container.add_argument(
|
||||
@@ -182,18 +222,6 @@ class DevelopmentGroup(Group):
|
||||
action="store_true",
|
||||
help="Run the server in debug mode",
|
||||
)
|
||||
self.container.add_argument(
|
||||
"-d",
|
||||
"--dev",
|
||||
dest="debug",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Currently is an alias for --debug. But starting in v22.3, \n"
|
||||
"--debug will no longer automatically trigger auto_restart. \n"
|
||||
"However, --dev will continue, effectively making it the \n"
|
||||
"same as debug + auto_reload."
|
||||
),
|
||||
)
|
||||
self.container.add_argument(
|
||||
"-r",
|
||||
"--reload",
|
||||
@@ -212,6 +240,22 @@ class DevelopmentGroup(Group):
|
||||
action="append",
|
||||
help="Extra directories to watch and reload on changes",
|
||||
)
|
||||
self.container.add_argument(
|
||||
"-d",
|
||||
"--dev",
|
||||
dest="dev",
|
||||
action="store_true",
|
||||
help=("debug + auto reload"),
|
||||
)
|
||||
self.container.add_argument(
|
||||
"--auto-tls",
|
||||
dest="auto_tls",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Create a temporary TLS certificate for local development "
|
||||
"(requires mkcert or trustme)"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class OutputGroup(Group):
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
import asyncio
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
|
||||
from sys import argv
|
||||
from typing import Awaitable
|
||||
|
||||
from multidict import CIMultiDict # type: ignore
|
||||
|
||||
|
||||
OS_IS_WINDOWS = os.name == "nt"
|
||||
UVLOOP_INSTALLED = False
|
||||
|
||||
try:
|
||||
import uvloop # type: ignore # noqa
|
||||
|
||||
UVLOOP_INSTALLED = True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
def enable_windows_color_support():
|
||||
@@ -39,12 +48,12 @@ class Header(CIMultiDict):
|
||||
return self.getall(key, default=[])
|
||||
|
||||
|
||||
use_trio = argv[0].endswith("hypercorn") and "trio" in argv
|
||||
use_trio = sys.argv[0].endswith("hypercorn") and "trio" in sys.argv
|
||||
|
||||
if use_trio: # pragma: no cover
|
||||
import trio # type: ignore
|
||||
|
||||
def stat_async(path):
|
||||
def stat_async(path) -> Awaitable[os.stat_result]:
|
||||
return trio.Path(path).stat()
|
||||
|
||||
open_async = trio.open_file
|
||||
@@ -64,7 +73,7 @@ def ctrlc_workaround_for_windows(app):
|
||||
"""Asyncio wakeups to allow receiving SIGINT in Python"""
|
||||
while not die:
|
||||
# If someone else stopped the app, just exit
|
||||
if app.is_stopping:
|
||||
if app.state.is_stopping:
|
||||
return
|
||||
# Windows Python blocks signal handlers while the event loop is
|
||||
# waiting for I/O. Frequent wakeups keep interrupts flowing.
|
||||
@@ -81,3 +90,7 @@ def ctrlc_workaround_for_windows(app):
|
||||
die = False
|
||||
signal.signal(signal.SIGINT, ctrlc_handler)
|
||||
app.add_task(stay_active)
|
||||
|
||||
|
||||
def is_atty() -> bool:
|
||||
return bool(sys.stdout and sys.stdout.isatty())
|
||||
|
||||
183
sanic/config.py
183
sanic/config.py
@@ -1,67 +1,88 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from inspect import isclass
|
||||
from inspect import getmembers, isclass, isdatadescriptor
|
||||
from os import environ
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
|
||||
from warnings import warn
|
||||
from typing import Any, Callable, Dict, Optional, Sequence, Union
|
||||
|
||||
from sanic.errorpages import check_error_format
|
||||
from sanic.constants import LocalCertCreator
|
||||
from sanic.errorpages import DEFAULT_FORMAT, check_error_format
|
||||
from sanic.helpers import Default, _default
|
||||
from sanic.http import Http
|
||||
from sanic.log import deprecation, error_logger
|
||||
from sanic.utils import load_module_from_file_location, str_to_bool
|
||||
|
||||
|
||||
if TYPE_CHECKING: # no cov
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
SANIC_PREFIX = "SANIC_"
|
||||
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"_FALLBACK_ERROR_FORMAT": _default,
|
||||
"ACCESS_LOG": True,
|
||||
"AUTO_EXTEND": True,
|
||||
"AUTO_RELOAD": False,
|
||||
"EVENT_AUTOREGISTER": False,
|
||||
"FALLBACK_ERROR_FORMAT": "auto",
|
||||
"FORWARDED_FOR_HEADER": "X-Forwarded-For",
|
||||
"FORWARDED_SECRET": None,
|
||||
"GRACEFUL_SHUTDOWN_TIMEOUT": 15.0, # 15 sec
|
||||
"KEEP_ALIVE_TIMEOUT": 5, # 5 seconds
|
||||
"KEEP_ALIVE": True,
|
||||
"LOCAL_CERT_CREATOR": LocalCertCreator.AUTO,
|
||||
"LOCAL_TLS_KEY": _default,
|
||||
"LOCAL_TLS_CERT": _default,
|
||||
"LOCALHOST": "localhost",
|
||||
"MOTD": True,
|
||||
"MOTD_DISPLAY": {},
|
||||
"NOISY_EXCEPTIONS": False,
|
||||
"PROXIES_COUNT": None,
|
||||
"REAL_IP_HEADER": None,
|
||||
"REGISTER": True,
|
||||
"REQUEST_BUFFER_SIZE": 65536, # 64 KiB
|
||||
"REQUEST_MAX_HEADER_SIZE": 8192, # 8 KiB, but cannot exceed 16384
|
||||
"REQUEST_ID_HEADER": "X-Request-ID",
|
||||
"REQUEST_MAX_SIZE": 100000000, # 100 megabytes
|
||||
"REQUEST_TIMEOUT": 60, # 60 seconds
|
||||
"RESPONSE_TIMEOUT": 60, # 60 seconds
|
||||
"WEBSOCKET_MAX_SIZE": 2 ** 20, # 1 megabyte
|
||||
"TLS_CERT_PASSWORD": "",
|
||||
"TOUCHUP": _default,
|
||||
"USE_UVLOOP": _default,
|
||||
"WEBSOCKET_MAX_SIZE": 2**20, # 1 megabyte
|
||||
"WEBSOCKET_PING_INTERVAL": 20,
|
||||
"WEBSOCKET_PING_TIMEOUT": 20,
|
||||
}
|
||||
|
||||
# These values will be removed from the Config object in v22.6 and moved
|
||||
# to the application state
|
||||
DEPRECATED_CONFIG = ("SERVER_RUNNING", "RELOADER_PROCESS", "RELOADED_FILES")
|
||||
|
||||
class Config(dict):
|
||||
|
||||
class DescriptorMeta(type):
|
||||
def __init__(cls, *_):
|
||||
cls.__setters__ = {name for name, _ in getmembers(cls, cls._is_setter)}
|
||||
|
||||
@staticmethod
|
||||
def _is_setter(member: object):
|
||||
return isdatadescriptor(member) and hasattr(member, "setter")
|
||||
|
||||
|
||||
class Config(dict, metaclass=DescriptorMeta):
|
||||
ACCESS_LOG: bool
|
||||
AUTO_EXTEND: bool
|
||||
AUTO_RELOAD: bool
|
||||
EVENT_AUTOREGISTER: bool
|
||||
FALLBACK_ERROR_FORMAT: str
|
||||
FORWARDED_FOR_HEADER: str
|
||||
FORWARDED_SECRET: Optional[str]
|
||||
GRACEFUL_SHUTDOWN_TIMEOUT: float
|
||||
KEEP_ALIVE_TIMEOUT: int
|
||||
KEEP_ALIVE: bool
|
||||
NOISY_EXCEPTIONS: bool
|
||||
LOCAL_CERT_CREATOR: Union[str, LocalCertCreator]
|
||||
LOCAL_TLS_KEY: Union[Path, str, Default]
|
||||
LOCAL_TLS_CERT: Union[Path, str, Default]
|
||||
LOCALHOST: str
|
||||
MOTD: bool
|
||||
MOTD_DISPLAY: Dict[str, str]
|
||||
NOISY_EXCEPTIONS: bool
|
||||
PROXIES_COUNT: Optional[int]
|
||||
REAL_IP_HEADER: Optional[str]
|
||||
REGISTER: bool
|
||||
REQUEST_BUFFER_SIZE: int
|
||||
REQUEST_MAX_HEADER_SIZE: int
|
||||
REQUEST_ID_HEADER: str
|
||||
@@ -69,6 +90,9 @@ class Config(dict):
|
||||
REQUEST_TIMEOUT: int
|
||||
RESPONSE_TIMEOUT: int
|
||||
SERVER_NAME: str
|
||||
TLS_CERT_PASSWORD: str
|
||||
TOUCHUP: Union[Default, bool]
|
||||
USE_UVLOOP: Union[Default, bool]
|
||||
WEBSOCKET_MAX_SIZE: int
|
||||
WEBSOCKET_PING_INTERVAL: int
|
||||
WEBSOCKET_PING_TIMEOUT: int
|
||||
@@ -76,17 +100,19 @@ class Config(dict):
|
||||
def __init__(
|
||||
self,
|
||||
defaults: Dict[str, Union[str, bool, int, float, None]] = None,
|
||||
load_env: Optional[Union[bool, str]] = True,
|
||||
env_prefix: Optional[str] = SANIC_PREFIX,
|
||||
keep_alive: Optional[bool] = None,
|
||||
*,
|
||||
app: Optional[Sanic] = None,
|
||||
converters: Optional[Sequence[Callable[[str], Any]]] = None,
|
||||
):
|
||||
defaults = defaults or {}
|
||||
super().__init__({**DEFAULT_CONFIG, **defaults})
|
||||
|
||||
self._app = app
|
||||
self._LOGO = ""
|
||||
self._converters = [str, str_to_bool, float, int]
|
||||
|
||||
if converters:
|
||||
for converter in converters:
|
||||
self.register_type(converter)
|
||||
|
||||
if keep_alive is not None:
|
||||
self.KEEP_ALIVE = keep_alive
|
||||
@@ -94,15 +120,6 @@ class Config(dict):
|
||||
if env_prefix != SANIC_PREFIX:
|
||||
if env_prefix:
|
||||
self.load_environment_vars(env_prefix)
|
||||
elif load_env is not True:
|
||||
if load_env:
|
||||
self.load_environment_vars(prefix=load_env)
|
||||
warn(
|
||||
"Use of load_env is deprecated and will be removed in "
|
||||
"21.12. Modify the configuration prefix by passing "
|
||||
"env_prefix instead.",
|
||||
DeprecationWarning,
|
||||
)
|
||||
else:
|
||||
self.load_environment_vars(SANIC_PREFIX)
|
||||
|
||||
@@ -123,9 +140,21 @@ class Config(dict):
|
||||
self.update({attr: value})
|
||||
|
||||
def update(self, *other, **kwargs) -> None:
|
||||
other_mapping = {k: v for item in other for k, v in dict(item).items()}
|
||||
super().update(*other, **kwargs)
|
||||
for attr, value in {**other_mapping, **kwargs}.items():
|
||||
kwargs.update({k: v for item in other for k, v in dict(item).items()})
|
||||
setters: Dict[str, Any] = {
|
||||
k: kwargs.pop(k)
|
||||
for k in {**kwargs}.keys()
|
||||
if k in self.__class__.__setters__
|
||||
}
|
||||
|
||||
for key, value in setters.items():
|
||||
try:
|
||||
super().__setattr__(key, value)
|
||||
except AttributeError:
|
||||
...
|
||||
|
||||
super().update(**kwargs)
|
||||
for attr, value in {**setters, **kwargs}.items():
|
||||
self._post_set(attr, value)
|
||||
|
||||
def _post_set(self, attr, value) -> None:
|
||||
@@ -136,31 +165,32 @@ class Config(dict):
|
||||
"REQUEST_MAX_SIZE",
|
||||
):
|
||||
self._configure_header_size()
|
||||
elif attr == "FALLBACK_ERROR_FORMAT":
|
||||
self._check_error_format()
|
||||
if self.app and value != self.app.error_handler.fallback:
|
||||
if self.app.error_handler.fallback != "auto":
|
||||
warn(
|
||||
"Overriding non-default ErrorHandler fallback "
|
||||
"value. Changing from "
|
||||
f"{self.app.error_handler.fallback} to {value}."
|
||||
)
|
||||
self.app.error_handler.fallback = value
|
||||
elif attr == "LOGO":
|
||||
self._LOGO = value
|
||||
warn(
|
||||
"Setting the config.LOGO is deprecated and will no longer "
|
||||
"be supported starting in v22.6.",
|
||||
DeprecationWarning,
|
||||
)
|
||||
|
||||
if attr == "LOCAL_CERT_CREATOR" and not isinstance(
|
||||
self.LOCAL_CERT_CREATOR, LocalCertCreator
|
||||
):
|
||||
self.LOCAL_CERT_CREATOR = LocalCertCreator[
|
||||
self.LOCAL_CERT_CREATOR.upper()
|
||||
]
|
||||
|
||||
@property
|
||||
def app(self):
|
||||
return self._app
|
||||
def FALLBACK_ERROR_FORMAT(self) -> str:
|
||||
if self._FALLBACK_ERROR_FORMAT is _default:
|
||||
return DEFAULT_FORMAT
|
||||
return self._FALLBACK_ERROR_FORMAT
|
||||
|
||||
@property
|
||||
def LOGO(self):
|
||||
return self._LOGO
|
||||
@FALLBACK_ERROR_FORMAT.setter
|
||||
def FALLBACK_ERROR_FORMAT(self, value):
|
||||
self._check_error_format(value)
|
||||
if (
|
||||
self._FALLBACK_ERROR_FORMAT is not _default
|
||||
and value != self._FALLBACK_ERROR_FORMAT
|
||||
):
|
||||
error_logger.warning(
|
||||
"Setting config.FALLBACK_ERROR_FORMAT on an already "
|
||||
"configured value may have unintended consequences."
|
||||
)
|
||||
self._FALLBACK_ERROR_FORMAT = value
|
||||
|
||||
def _configure_header_size(self):
|
||||
Http.set_header_max_size(
|
||||
@@ -169,8 +199,8 @@ class Config(dict):
|
||||
self.REQUEST_MAX_SIZE,
|
||||
)
|
||||
|
||||
def _check_error_format(self):
|
||||
check_error_format(self.FALLBACK_ERROR_FORMAT)
|
||||
def _check_error_format(self, format: Optional[str] = None):
|
||||
check_error_format(format or self.FALLBACK_ERROR_FORMAT)
|
||||
|
||||
def load_environment_vars(self, prefix=SANIC_PREFIX):
|
||||
"""
|
||||
@@ -184,20 +214,45 @@ class Config(dict):
|
||||
- ``float``
|
||||
- ``bool``
|
||||
|
||||
Anything else will be imported as a ``str``.
|
||||
Anything else will be imported as a ``str``. If you would like to add
|
||||
additional types to this list, you can use
|
||||
:meth:`sanic.config.Config.register_type`. Just make sure that they
|
||||
are registered before you instantiate your application.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class Foo:
|
||||
def __init__(self, name) -> None:
|
||||
self.name = name
|
||||
|
||||
|
||||
config = Config(converters=[Foo])
|
||||
app = Sanic(__name__, config=config)
|
||||
|
||||
`See user guide re: config
|
||||
<https://sanicframework.org/guide/deployment/configuration.html>`__
|
||||
"""
|
||||
lower_case_var_found = False
|
||||
for key, value in environ.items():
|
||||
if not key.startswith(prefix):
|
||||
continue
|
||||
if not key.isupper():
|
||||
lower_case_var_found = True
|
||||
|
||||
_, config_key = key.split(prefix, 1)
|
||||
|
||||
for converter in (int, float, str_to_bool, str):
|
||||
for converter in reversed(self._converters):
|
||||
try:
|
||||
self[config_key] = converter(value)
|
||||
break
|
||||
except ValueError:
|
||||
pass
|
||||
if lower_case_var_found:
|
||||
deprecation(
|
||||
"Lowercase environment variables will not be "
|
||||
"loaded into Sanic config beginning in v22.9.",
|
||||
22.9,
|
||||
)
|
||||
|
||||
def update_config(self, config: Union[bytes, str, dict, Any]):
|
||||
"""
|
||||
@@ -267,3 +322,17 @@ class Config(dict):
|
||||
self.update(config)
|
||||
|
||||
load = update_config
|
||||
|
||||
def register_type(self, converter: Callable[[str], Any]) -> None:
|
||||
"""
|
||||
Allows for adding custom function to cast from a string value to any
|
||||
other type. The function should raise ValueError if it is not the
|
||||
correct type.
|
||||
"""
|
||||
if converter in self._converters:
|
||||
error_logger.warning(
|
||||
f"Configuration value converter '{converter.__name__}' has "
|
||||
"already been registered"
|
||||
)
|
||||
return
|
||||
self._converters.append(converter)
|
||||
|
||||
@@ -24,5 +24,16 @@ class HTTPMethod(str, Enum):
|
||||
DELETE = auto()
|
||||
|
||||
|
||||
class LocalCertCreator(str, Enum):
|
||||
def _generate_next_value_(name, start, count, last_values):
|
||||
return name.upper()
|
||||
|
||||
AUTO = auto()
|
||||
TRUSTME = auto()
|
||||
MKCERT = auto()
|
||||
|
||||
|
||||
HTTP_METHODS = tuple(HTTPMethod.__members__.values())
|
||||
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
|
||||
DEFAULT_LOCAL_TLS_KEY = "key.pem"
|
||||
DEFAULT_LOCAL_TLS_CERT = "cert.pem"
|
||||
|
||||
@@ -19,7 +19,7 @@ import typing as t
|
||||
from functools import partial
|
||||
from traceback import extract_tb
|
||||
|
||||
from sanic.exceptions import InvalidUsage, SanicException
|
||||
from sanic.exceptions import BadRequest, SanicException
|
||||
from sanic.helpers import STATUS_CODES
|
||||
from sanic.request import Request
|
||||
from sanic.response import HTTPResponse, html, json, text
|
||||
@@ -34,6 +34,7 @@ except ImportError: # noqa
|
||||
from json import dumps
|
||||
|
||||
|
||||
DEFAULT_FORMAT = "auto"
|
||||
FALLBACK_TEXT = (
|
||||
"The server encountered an internal error and "
|
||||
"cannot complete your request."
|
||||
@@ -505,7 +506,7 @@ def exception_response(
|
||||
# $ curl localhost:8000 -d '{"foo": "bar"}'
|
||||
# And provide them with JSONRenderer
|
||||
renderer = JSONRenderer if request.json else base
|
||||
except InvalidUsage:
|
||||
except BadRequest:
|
||||
renderer = base
|
||||
else:
|
||||
renderer = RENDERERS_BY_CONFIG.get(render_format, renderer)
|
||||
|
||||
@@ -42,7 +42,7 @@ class NotFound(SanicException):
|
||||
quiet = True
|
||||
|
||||
|
||||
class InvalidUsage(SanicException):
|
||||
class BadRequest(SanicException):
|
||||
"""
|
||||
**Status**: 400 Bad Request
|
||||
"""
|
||||
@@ -51,7 +51,14 @@ class InvalidUsage(SanicException):
|
||||
quiet = True
|
||||
|
||||
|
||||
class MethodNotSupported(SanicException):
|
||||
InvalidUsage = BadRequest
|
||||
|
||||
|
||||
class BadURL(BadRequest):
|
||||
...
|
||||
|
||||
|
||||
class MethodNotAllowed(SanicException):
|
||||
"""
|
||||
**Status**: 405 Method Not Allowed
|
||||
"""
|
||||
@@ -64,6 +71,9 @@ class MethodNotSupported(SanicException):
|
||||
self.headers = {"Allow": ", ".join(allowed_methods)}
|
||||
|
||||
|
||||
MethodNotSupported = MethodNotAllowed
|
||||
|
||||
|
||||
class ServerError(SanicException):
|
||||
"""
|
||||
**Status**: 500 Internal Server Error
|
||||
@@ -125,19 +135,19 @@ class PayloadTooLarge(SanicException):
|
||||
quiet = True
|
||||
|
||||
|
||||
class HeaderNotFound(InvalidUsage):
|
||||
class HeaderNotFound(BadRequest):
|
||||
"""
|
||||
**Status**: 400 Bad Request
|
||||
"""
|
||||
|
||||
|
||||
class InvalidHeader(InvalidUsage):
|
||||
class InvalidHeader(BadRequest):
|
||||
"""
|
||||
**Status**: 400 Bad Request
|
||||
"""
|
||||
|
||||
|
||||
class ContentRangeError(SanicException):
|
||||
class RangeNotSatisfiable(SanicException):
|
||||
"""
|
||||
**Status**: 416 Range Not Satisfiable
|
||||
"""
|
||||
@@ -150,7 +160,10 @@ class ContentRangeError(SanicException):
|
||||
self.headers = {"Content-Range": f"bytes */{content_range.total}"}
|
||||
|
||||
|
||||
class HeaderExpectationFailed(SanicException):
|
||||
ContentRangeError = RangeNotSatisfiable
|
||||
|
||||
|
||||
class ExpectationFailed(SanicException):
|
||||
"""
|
||||
**Status**: 417 Expectation Failed
|
||||
"""
|
||||
@@ -159,6 +172,9 @@ class HeaderExpectationFailed(SanicException):
|
||||
quiet = True
|
||||
|
||||
|
||||
HeaderExpectationFailed = ExpectationFailed
|
||||
|
||||
|
||||
class Forbidden(SanicException):
|
||||
"""
|
||||
**Status**: 403 Forbidden
|
||||
@@ -168,7 +184,7 @@ class Forbidden(SanicException):
|
||||
quiet = True
|
||||
|
||||
|
||||
class InvalidRangeType(ContentRangeError):
|
||||
class InvalidRangeType(RangeNotSatisfiable):
|
||||
"""
|
||||
**Status**: 416 Range Not Satisfiable
|
||||
"""
|
||||
@@ -244,25 +260,3 @@ class InvalidSignal(SanicException):
|
||||
class WebsocketClosed(SanicException):
|
||||
quiet = True
|
||||
message = "Client has closed the websocket connection"
|
||||
|
||||
|
||||
def abort(status_code: int, message: Optional[Union[str, bytes]] = None):
|
||||
"""
|
||||
Raise an exception based on SanicException. Returns the HTTP response
|
||||
message appropriate for the given status code, unless provided.
|
||||
|
||||
STATUS_CODES from sanic.helpers for the given status code.
|
||||
|
||||
:param status_code: The HTTP status code to return.
|
||||
:param message: The HTTP response body. Defaults to the messages in
|
||||
"""
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"sanic.exceptions.abort has been marked as deprecated, and will be "
|
||||
"removed in release 21.12.\n To migrate your code, simply replace "
|
||||
"abort(status_code, msg) with raise SanicException(msg, status_code), "
|
||||
"or even better, raise an appropriate SanicException subclass."
|
||||
)
|
||||
|
||||
raise SanicException(message=message, status_code=status_code)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
from inspect import signature
|
||||
from typing import Dict, List, Optional, Tuple, Type
|
||||
from warnings import warn
|
||||
from __future__ import annotations
|
||||
|
||||
from sanic.errorpages import BaseRenderer, HTMLRenderer, exception_response
|
||||
from typing import Dict, List, Optional, Tuple, Type
|
||||
|
||||
from sanic.errorpages import BaseRenderer, TextRenderer, exception_response
|
||||
from sanic.exceptions import (
|
||||
ContentRangeError,
|
||||
HeaderNotFound,
|
||||
InvalidRangeType,
|
||||
RangeNotSatisfiable,
|
||||
)
|
||||
from sanic.log import error_logger
|
||||
from sanic.log import deprecation, error_logger
|
||||
from sanic.models.handler_types import RouteHandler
|
||||
from sanic.response import text
|
||||
|
||||
@@ -26,52 +26,27 @@ class ErrorHandler:
|
||||
|
||||
"""
|
||||
|
||||
# Beginning in v22.3, the base renderer will be TextRenderer
|
||||
def __init__(
|
||||
self, fallback: str = "auto", base: Type[BaseRenderer] = HTMLRenderer
|
||||
self,
|
||||
base: Type[BaseRenderer] = TextRenderer,
|
||||
):
|
||||
self.handlers: List[Tuple[Type[BaseException], RouteHandler]] = []
|
||||
self.cached_handlers: Dict[
|
||||
Tuple[Type[BaseException], Optional[str]], Optional[RouteHandler]
|
||||
] = {}
|
||||
self.debug = False
|
||||
self.fallback = fallback
|
||||
self.base = base
|
||||
|
||||
@classmethod
|
||||
def finalize(cls, error_handler, fallback: Optional[str] = None):
|
||||
if (
|
||||
fallback
|
||||
and fallback != "auto"
|
||||
and error_handler.fallback == "auto"
|
||||
):
|
||||
error_handler.fallback = fallback
|
||||
|
||||
if not isinstance(error_handler, cls):
|
||||
error_logger.warning(
|
||||
f"Error handler is non-conforming: {type(error_handler)}"
|
||||
)
|
||||
|
||||
sig = signature(error_handler.lookup)
|
||||
if len(sig.parameters) == 1:
|
||||
warn(
|
||||
"You are using a deprecated error handler. The lookup "
|
||||
"method should accept two positional parameters: "
|
||||
"(exception, route_name: Optional[str]). "
|
||||
"Until you upgrade your ErrorHandler.lookup, Blueprint "
|
||||
"specific exceptions will not work properly. Beginning "
|
||||
"in v22.3, the legacy style lookup method will not "
|
||||
"work at all.",
|
||||
DeprecationWarning,
|
||||
)
|
||||
error_handler._lookup = error_handler._legacy_lookup
|
||||
def finalize(cls, *args, **kwargs):
|
||||
deprecation(
|
||||
"ErrorHandler.finalize is deprecated and no longer needed. "
|
||||
"Please remove update your code to remove it. ",
|
||||
22.12,
|
||||
)
|
||||
|
||||
def _full_lookup(self, exception, route_name: Optional[str] = None):
|
||||
return self.lookup(exception, route_name)
|
||||
|
||||
def _legacy_lookup(self, exception, route_name: Optional[str] = None):
|
||||
return self.lookup(exception)
|
||||
|
||||
def add(self, exception, handler, route_names: Optional[List[str]] = None):
|
||||
"""
|
||||
Add a new exception handler to an already existing handler object.
|
||||
@@ -85,9 +60,6 @@ class ErrorHandler:
|
||||
|
||||
:return: None
|
||||
"""
|
||||
# self.handlers is deprecated and will be removed in version 22.3
|
||||
self.handlers.append((exception, handler))
|
||||
|
||||
if route_names:
|
||||
for route in route_names:
|
||||
self.cached_handlers[(exception, route)] = handler
|
||||
@@ -159,7 +131,7 @@ class ErrorHandler:
|
||||
except Exception:
|
||||
try:
|
||||
url = repr(request.url)
|
||||
except AttributeError:
|
||||
except AttributeError: # no cov
|
||||
url = "unknown"
|
||||
response_message = (
|
||||
"Exception raised in exception handler " '"%s" for uri: %s'
|
||||
@@ -188,12 +160,13 @@ class ErrorHandler:
|
||||
:return:
|
||||
"""
|
||||
self.log(request, exception)
|
||||
fallback = request.app.config.FALLBACK_ERROR_FORMAT
|
||||
return exception_response(
|
||||
request,
|
||||
exception,
|
||||
debug=self.debug,
|
||||
base=self.base,
|
||||
fallback=self.fallback,
|
||||
fallback=fallback,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -203,7 +176,7 @@ class ErrorHandler:
|
||||
if quiet is False or noisy is True:
|
||||
try:
|
||||
url = repr(request.url)
|
||||
except AttributeError:
|
||||
except AttributeError: # no cov
|
||||
url = "unknown"
|
||||
|
||||
error_logger.exception(
|
||||
@@ -246,18 +219,18 @@ class ContentRangeHandler:
|
||||
try:
|
||||
self.start = int(start_b) if start_b else None
|
||||
except ValueError:
|
||||
raise ContentRangeError(
|
||||
raise RangeNotSatisfiable(
|
||||
"'%s' is invalid for Content Range" % (start_b,), self
|
||||
)
|
||||
try:
|
||||
self.end = int(end_b) if end_b else None
|
||||
except ValueError:
|
||||
raise ContentRangeError(
|
||||
raise RangeNotSatisfiable(
|
||||
"'%s' is invalid for Content Range" % (end_b,), self
|
||||
)
|
||||
if self.end is None:
|
||||
if self.start is None:
|
||||
raise ContentRangeError(
|
||||
raise RangeNotSatisfiable(
|
||||
"Invalid for Content Range parameters", self
|
||||
)
|
||||
else:
|
||||
@@ -269,7 +242,7 @@ class ContentRangeHandler:
|
||||
self.start = self.total - self.end
|
||||
self.end = self.total - 1
|
||||
if self.start >= self.end:
|
||||
raise ContentRangeError(
|
||||
raise RangeNotSatisfiable(
|
||||
"Invalid for Content Range parameters", self
|
||||
)
|
||||
self.size = self.end - self.start + 1
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
|
||||
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
|
||||
from urllib.parse import unquote
|
||||
|
||||
from sanic.exceptions import InvalidHeader
|
||||
@@ -18,7 +18,7 @@ Options = Dict[str, Union[int, str]] # key=value fields in various headers
|
||||
OptionsIterable = Iterable[Tuple[str, str]] # May contain duplicate keys
|
||||
|
||||
_token, _quoted = r"([\w!#$%&'*+\-.^_`|~]+)", r'"([^"]*)"'
|
||||
_param = re.compile(fr";\s*{_token}=(?:{_token}|{_quoted})", re.ASCII)
|
||||
_param = re.compile(rf";\s*{_token}=(?:{_token}|{_quoted})", re.ASCII)
|
||||
_firefox_quote_escape = re.compile(r'\\"(?!; |\s*$)')
|
||||
_ipv6 = "(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}"
|
||||
_ipv6_re = re.compile(_ipv6)
|
||||
@@ -394,3 +394,17 @@ def parse_accept(accept: str) -> AcceptContainer:
|
||||
return AcceptContainer(
|
||||
sorted(accept_list, key=_sort_accept_value, reverse=True)
|
||||
)
|
||||
|
||||
|
||||
def parse_credentials(
|
||||
header: Optional[str],
|
||||
prefixes: Union[List, Tuple, Set] = None,
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Parses any header with the aim to retrieve any credentials from it."""
|
||||
if not prefixes or not isinstance(prefixes, (list, tuple, set)):
|
||||
prefixes = ("Basic", "Bearer", "Token")
|
||||
if header is not None:
|
||||
for prefix in prefixes:
|
||||
if prefix in header:
|
||||
return prefix, header.partition(prefix)[-1].strip()
|
||||
return None, header
|
||||
|
||||
6
sanic/http/__init__.py
Normal file
6
sanic/http/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from .constants import Stage
|
||||
from .http1 import Http
|
||||
from .http3 import Http3
|
||||
|
||||
|
||||
__all__ = ("Http", "Stage", "Http3")
|
||||
29
sanic/http/constants.py
Normal file
29
sanic/http/constants.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from enum import Enum, IntEnum
|
||||
|
||||
|
||||
class Stage(Enum):
|
||||
"""
|
||||
Enum for representing the stage of the request/response cycle
|
||||
|
||||
| ``IDLE`` Waiting for request
|
||||
| ``REQUEST`` Request headers being received
|
||||
| ``HANDLER`` Headers done, handler running
|
||||
| ``RESPONSE`` Response headers sent, body in progress
|
||||
| ``FAILED`` Unrecoverable state (error while sending response)
|
||||
|
|
||||
"""
|
||||
|
||||
IDLE = 0 # Waiting for request
|
||||
REQUEST = 1 # Request headers being received
|
||||
HANDLER = 3 # Headers done, handler running
|
||||
RESPONSE = 4 # Response headers sent, body in progress
|
||||
FAILED = 100 # Unrecoverable state (error while sending response)
|
||||
|
||||
|
||||
class HTTP(IntEnum):
|
||||
VERSION_1 = 1
|
||||
VERSION_3 = 3
|
||||
|
||||
def display(self) -> str:
|
||||
value = 1.1 if self.value == 1 else self.value
|
||||
return f"HTTP/{value}"
|
||||
@@ -8,66 +8,47 @@ if TYPE_CHECKING:
|
||||
from sanic.response import BaseHTTPResponse
|
||||
|
||||
from asyncio import CancelledError, sleep
|
||||
from enum import Enum
|
||||
|
||||
from sanic.compat import Header
|
||||
from sanic.exceptions import (
|
||||
HeaderExpectationFailed,
|
||||
InvalidUsage,
|
||||
BadRequest,
|
||||
ExpectationFailed,
|
||||
PayloadTooLarge,
|
||||
ServerError,
|
||||
ServiceUnavailable,
|
||||
)
|
||||
from sanic.headers import format_http1_response
|
||||
from sanic.helpers import has_message_body
|
||||
from sanic.http.constants import Stage
|
||||
from sanic.http.stream import Stream
|
||||
from sanic.log import access_logger, error_logger, logger
|
||||
from sanic.touchup import TouchUpMeta
|
||||
|
||||
|
||||
class Stage(Enum):
|
||||
"""
|
||||
Enum for representing the stage of the request/response cycle
|
||||
|
||||
| ``IDLE`` Waiting for request
|
||||
| ``REQUEST`` Request headers being received
|
||||
| ``HANDLER`` Headers done, handler running
|
||||
| ``RESPONSE`` Response headers sent, body in progress
|
||||
| ``FAILED`` Unrecoverable state (error while sending response)
|
||||
|
|
||||
"""
|
||||
|
||||
IDLE = 0 # Waiting for request
|
||||
REQUEST = 1 # Request headers being received
|
||||
HANDLER = 3 # Headers done, handler running
|
||||
RESPONSE = 4 # Response headers sent, body in progress
|
||||
FAILED = 100 # Unrecoverable state (error while sending response)
|
||||
|
||||
|
||||
HTTP_CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n"
|
||||
|
||||
|
||||
class Http(metaclass=TouchUpMeta):
|
||||
class Http(Stream, metaclass=TouchUpMeta):
|
||||
"""
|
||||
Internal helper for managing the HTTP request/response cycle
|
||||
Internal helper for managing the HTTP/1.1 request/response cycle
|
||||
|
||||
:raises ServerError:
|
||||
:raises PayloadTooLarge:
|
||||
:raises Exception:
|
||||
:raises InvalidUsage:
|
||||
:raises HeaderExpectationFailed:
|
||||
:raises BadRequest:
|
||||
:raises ExpectationFailed:
|
||||
:raises RuntimeError:
|
||||
:raises ServerError:
|
||||
:raises ServerError:
|
||||
:raises InvalidUsage:
|
||||
:raises InvalidUsage:
|
||||
:raises InvalidUsage:
|
||||
:raises BadRequest:
|
||||
:raises BadRequest:
|
||||
:raises BadRequest:
|
||||
:raises PayloadTooLarge:
|
||||
:raises RuntimeError:
|
||||
"""
|
||||
|
||||
HEADER_CEILING = 16_384
|
||||
HEADER_MAX_SIZE = 0
|
||||
|
||||
__touchup__ = (
|
||||
"http1_request_header",
|
||||
"http1_response_header",
|
||||
@@ -248,7 +229,7 @@ class Http(metaclass=TouchUpMeta):
|
||||
|
||||
headers.append(h)
|
||||
except Exception:
|
||||
raise InvalidUsage("Bad Request")
|
||||
raise BadRequest("Bad Request")
|
||||
|
||||
headers_instance = Header(headers)
|
||||
self.upgrade_websocket = (
|
||||
@@ -265,6 +246,7 @@ class Http(metaclass=TouchUpMeta):
|
||||
transport=self.protocol.transport,
|
||||
app=self.protocol.app,
|
||||
)
|
||||
self.protocol.request_class._current.set(request)
|
||||
await self.dispatch(
|
||||
"http.lifecycle.request",
|
||||
inline=True,
|
||||
@@ -281,7 +263,7 @@ class Http(metaclass=TouchUpMeta):
|
||||
if expect.lower() == "100-continue":
|
||||
self.expecting_continue = True
|
||||
else:
|
||||
raise HeaderExpectationFailed(f"Unknown Expect: {expect}")
|
||||
raise ExpectationFailed(f"Unknown Expect: {expect}")
|
||||
|
||||
if headers.getone("transfer-encoding", None) == "chunked":
|
||||
self.request_body = "chunked"
|
||||
@@ -352,6 +334,12 @@ class Http(metaclass=TouchUpMeta):
|
||||
self.response_func = self.head_response_ignored
|
||||
|
||||
headers["connection"] = "keep-alive" if self.keep_alive else "close"
|
||||
|
||||
# This header may be removed or modified by the AltSvcCheck Touchup
|
||||
# service. At server start, we either remove this header from ever
|
||||
# being assigned, or we change the value as required.
|
||||
headers["alt-svc"] = ""
|
||||
|
||||
ret = format_http1_response(status, res.processed_headers)
|
||||
if data:
|
||||
ret += data
|
||||
@@ -510,7 +498,7 @@ class Http(metaclass=TouchUpMeta):
|
||||
|
||||
if len(buf) > 64:
|
||||
self.keep_alive = False
|
||||
raise InvalidUsage("Bad chunked encoding")
|
||||
raise BadRequest("Bad chunked encoding")
|
||||
|
||||
await self._receive_more()
|
||||
|
||||
@@ -518,14 +506,14 @@ class Http(metaclass=TouchUpMeta):
|
||||
size = int(buf[2:pos].split(b";", 1)[0].decode(), 16)
|
||||
except Exception:
|
||||
self.keep_alive = False
|
||||
raise InvalidUsage("Bad chunked encoding")
|
||||
raise BadRequest("Bad chunked encoding")
|
||||
|
||||
if size <= 0:
|
||||
self.request_body = None
|
||||
|
||||
if size < 0:
|
||||
self.keep_alive = False
|
||||
raise InvalidUsage("Bad chunked encoding")
|
||||
raise BadRequest("Bad chunked encoding")
|
||||
|
||||
# Consume CRLF, chunk size 0 and the two CRLF that follow
|
||||
pos += 4
|
||||
406
sanic/http/http3.py
Normal file
406
sanic/http/http3.py
Normal file
@@ -0,0 +1,406 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from ssl import SSLContext
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Tuple,
|
||||
Union,
|
||||
cast,
|
||||
)
|
||||
|
||||
from sanic.compat import Header
|
||||
from sanic.constants import LocalCertCreator
|
||||
from sanic.exceptions import PayloadTooLarge, SanicException, ServerError
|
||||
from sanic.helpers import has_message_body
|
||||
from sanic.http.constants import Stage
|
||||
from sanic.http.stream import Stream
|
||||
from sanic.http.tls.context import CertSelector, CertSimple, SanicSSLContext
|
||||
from sanic.log import Colors, logger
|
||||
from sanic.models.protocol_types import TransportProtocol
|
||||
from sanic.models.server_types import ConnInfo
|
||||
|
||||
|
||||
try:
|
||||
from aioquic.h0.connection import H0_ALPN, H0Connection
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import (
|
||||
DatagramReceived,
|
||||
DataReceived,
|
||||
H3Event,
|
||||
HeadersReceived,
|
||||
WebTransportStreamDataReceived,
|
||||
)
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
from aioquic.tls import SessionTicket
|
||||
|
||||
HTTP3_AVAILABLE = True
|
||||
except ModuleNotFoundError: # no cov
|
||||
HTTP3_AVAILABLE = False
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic
|
||||
from sanic.request import Request
|
||||
from sanic.response import BaseHTTPResponse
|
||||
from sanic.server.protocols.http_protocol import Http3Protocol
|
||||
|
||||
HttpConnection = Union[H0Connection, H3Connection]
|
||||
|
||||
|
||||
class HTTP3Transport(TransportProtocol):
|
||||
__slots__ = ("_protocol",)
|
||||
|
||||
def __init__(self, protocol: Http3Protocol):
|
||||
self._protocol = protocol
|
||||
|
||||
def get_protocol(self) -> Http3Protocol:
|
||||
return self._protocol
|
||||
|
||||
def get_extra_info(self, info: str, default: Any = None) -> Any:
|
||||
if (
|
||||
info in ("socket", "sockname", "peername")
|
||||
and self._protocol._transport
|
||||
):
|
||||
return self._protocol._transport.get_extra_info(info, default)
|
||||
elif info == "network_paths":
|
||||
return self._protocol._quic._network_paths
|
||||
elif info == "ssl_context":
|
||||
return self._protocol.app.state.ssl
|
||||
return default
|
||||
|
||||
|
||||
class Receiver(ABC):
|
||||
future: asyncio.Future
|
||||
|
||||
def __init__(self, transmit, protocol, request: Request) -> None:
|
||||
self.transmit = transmit
|
||||
self.protocol = protocol
|
||||
self.request = request
|
||||
|
||||
@abstractmethod
|
||||
async def run(self): # no cov
|
||||
...
|
||||
|
||||
|
||||
class HTTPReceiver(Receiver, Stream):
|
||||
stage: Stage
|
||||
request: Request
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.request_body = None
|
||||
self.stage = Stage.IDLE
|
||||
self.headers_sent = False
|
||||
self.response: Optional[BaseHTTPResponse] = None
|
||||
self.request_max_size = self.protocol.request_max_size
|
||||
self.request_bytes = 0
|
||||
|
||||
async def run(self, exception: Optional[Exception] = None):
|
||||
self.stage = Stage.HANDLER
|
||||
self.head_only = self.request.method.upper() == "HEAD"
|
||||
|
||||
if exception:
|
||||
logger.info( # no cov
|
||||
f"{Colors.BLUE}[exception]: "
|
||||
f"{Colors.RED}{exception}{Colors.END}",
|
||||
exc_info=True,
|
||||
extra={"verbosity": 1},
|
||||
)
|
||||
await self.error_response(exception)
|
||||
else:
|
||||
try:
|
||||
logger.info( # no cov
|
||||
f"{Colors.BLUE}[request]:{Colors.END} {self.request}",
|
||||
extra={"verbosity": 1},
|
||||
)
|
||||
await self.protocol.request_handler(self.request)
|
||||
except Exception as e: # no cov
|
||||
# This should largely be handled within the request handler.
|
||||
# But, just in case...
|
||||
await self.run(e)
|
||||
self.stage = Stage.IDLE
|
||||
|
||||
async def error_response(self, exception: Exception) -> None:
|
||||
"""
|
||||
Handle response when exception encountered
|
||||
"""
|
||||
# From request and handler states we can respond, otherwise be silent
|
||||
app = self.protocol.app
|
||||
|
||||
await app.handle_exception(self.request, exception)
|
||||
|
||||
def _prepare_headers(
|
||||
self, response: BaseHTTPResponse
|
||||
) -> List[Tuple[bytes, bytes]]:
|
||||
size = len(response.body) if response.body else 0
|
||||
headers = response.headers
|
||||
status = response.status
|
||||
|
||||
if not has_message_body(status) and (
|
||||
size
|
||||
or "content-length" in headers
|
||||
or "transfer-encoding" in headers
|
||||
):
|
||||
headers.pop("content-length", None)
|
||||
headers.pop("transfer-encoding", None)
|
||||
logger.warning( # no cov
|
||||
f"Message body set in response on {self.request.path}. "
|
||||
f"A {status} response may only have headers, no body."
|
||||
)
|
||||
elif "content-length" not in headers:
|
||||
if size:
|
||||
headers["content-length"] = size
|
||||
else:
|
||||
headers["transfer-encoding"] = "chunked"
|
||||
|
||||
headers = [
|
||||
(b":status", str(response.status).encode()),
|
||||
*response.processed_headers,
|
||||
]
|
||||
return headers
|
||||
|
||||
def send_headers(self) -> None:
|
||||
logger.debug( # no cov
|
||||
f"{Colors.BLUE}[send]: {Colors.GREEN}HEADERS{Colors.END}",
|
||||
extra={"verbosity": 2},
|
||||
)
|
||||
if not self.response:
|
||||
raise RuntimeError("no response")
|
||||
|
||||
response = self.response
|
||||
headers = self._prepare_headers(response)
|
||||
|
||||
self.protocol.connection.send_headers(
|
||||
stream_id=self.request.stream_id,
|
||||
headers=headers,
|
||||
)
|
||||
self.headers_sent = True
|
||||
self.stage = Stage.RESPONSE
|
||||
|
||||
if self.response.body and not self.head_only:
|
||||
self._send(self.response.body, False)
|
||||
elif self.head_only:
|
||||
self.future.cancel()
|
||||
|
||||
def respond(self, response: BaseHTTPResponse) -> BaseHTTPResponse:
|
||||
logger.debug( # no cov
|
||||
f"{Colors.BLUE}[respond]:{Colors.END} {response}",
|
||||
extra={"verbosity": 2},
|
||||
)
|
||||
|
||||
if self.stage is not Stage.HANDLER:
|
||||
self.stage = Stage.FAILED
|
||||
raise RuntimeError("Response already started")
|
||||
|
||||
# Disconnect any earlier but unused response object
|
||||
if self.response is not None:
|
||||
self.response.stream = None
|
||||
|
||||
self.response, response.stream = response, self
|
||||
|
||||
return response
|
||||
|
||||
def receive_body(self, data: bytes) -> None:
|
||||
self.request_bytes += len(data)
|
||||
if self.request_bytes > self.request_max_size:
|
||||
raise PayloadTooLarge("Request body exceeds the size limit")
|
||||
|
||||
self.request.body += data
|
||||
|
||||
async def send(self, data: bytes, end_stream: bool) -> None:
|
||||
logger.debug( # no cov
|
||||
f"{Colors.BLUE}[send]: {Colors.GREEN}data={data.decode()} "
|
||||
f"end_stream={end_stream}{Colors.END}",
|
||||
extra={"verbosity": 2},
|
||||
)
|
||||
self._send(data, end_stream)
|
||||
|
||||
def _send(self, data: bytes, end_stream: bool) -> None:
|
||||
if not self.headers_sent:
|
||||
self.send_headers()
|
||||
if self.stage is not Stage.RESPONSE:
|
||||
raise ServerError(f"not ready to send: {self.stage}")
|
||||
|
||||
# Chunked
|
||||
if (
|
||||
self.response
|
||||
and self.response.headers.get("transfer-encoding") == "chunked"
|
||||
):
|
||||
size = len(data)
|
||||
if end_stream:
|
||||
data = (
|
||||
b"%x\r\n%b\r\n0\r\n\r\n" % (size, data)
|
||||
if size
|
||||
else b"0\r\n\r\n"
|
||||
)
|
||||
elif size:
|
||||
data = b"%x\r\n%b\r\n" % (size, data)
|
||||
|
||||
logger.debug( # no cov
|
||||
f"{Colors.BLUE}[transmitting]{Colors.END}",
|
||||
extra={"verbosity": 2},
|
||||
)
|
||||
self.protocol.connection.send_data(
|
||||
stream_id=self.request.stream_id,
|
||||
data=data,
|
||||
end_stream=end_stream,
|
||||
)
|
||||
self.transmit()
|
||||
|
||||
if end_stream:
|
||||
self.stage = Stage.IDLE
|
||||
|
||||
|
||||
class WebsocketReceiver(Receiver): # noqa
|
||||
async def run(self):
|
||||
...
|
||||
|
||||
|
||||
class WebTransportReceiver(Receiver): # noqa
|
||||
async def run(self):
|
||||
...
|
||||
|
||||
|
||||
class Http3:
|
||||
"""
|
||||
Internal helper for managing the HTTP/3 request/response cycle
|
||||
"""
|
||||
|
||||
if HTTP3_AVAILABLE:
|
||||
HANDLER_PROPERTY_MAPPING = {
|
||||
DataReceived: "stream_id",
|
||||
HeadersReceived: "stream_id",
|
||||
DatagramReceived: "flow_id",
|
||||
WebTransportStreamDataReceived: "session_id",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
protocol: Http3Protocol,
|
||||
transmit: Callable[[], None],
|
||||
) -> None:
|
||||
self.protocol = protocol
|
||||
self.transmit = transmit
|
||||
self.receivers: Dict[int, Receiver] = {}
|
||||
|
||||
def http_event_received(self, event: H3Event) -> None:
|
||||
logger.debug( # no cov
|
||||
f"{Colors.BLUE}[http_event_received]: "
|
||||
f"{Colors.YELLOW}{event}{Colors.END}",
|
||||
extra={"verbosity": 2},
|
||||
)
|
||||
receiver, created_new = self.get_or_make_receiver(event)
|
||||
receiver = cast(HTTPReceiver, receiver)
|
||||
|
||||
if isinstance(event, HeadersReceived) and created_new:
|
||||
receiver.future = asyncio.ensure_future(receiver.run())
|
||||
elif isinstance(event, DataReceived):
|
||||
try:
|
||||
receiver.receive_body(event.data)
|
||||
except Exception as e:
|
||||
receiver.future.cancel()
|
||||
receiver.future = asyncio.ensure_future(receiver.run(e))
|
||||
else:
|
||||
... # Intentionally here to help out Touchup
|
||||
logger.debug( # no cov
|
||||
f"{Colors.RED}DOING NOTHING{Colors.END}",
|
||||
extra={"verbosity": 2},
|
||||
)
|
||||
|
||||
def get_or_make_receiver(self, event: H3Event) -> Tuple[Receiver, bool]:
|
||||
if (
|
||||
isinstance(event, HeadersReceived)
|
||||
and event.stream_id not in self.receivers
|
||||
):
|
||||
request = self._make_request(event)
|
||||
receiver = HTTPReceiver(self.transmit, self.protocol, request)
|
||||
request.stream = receiver
|
||||
|
||||
self.receivers[event.stream_id] = receiver
|
||||
return receiver, True
|
||||
else:
|
||||
ident = getattr(event, self.HANDLER_PROPERTY_MAPPING[type(event)])
|
||||
return self.receivers[ident], False
|
||||
|
||||
def get_receiver_by_stream_id(self, stream_id: int) -> Receiver:
|
||||
return self.receivers[stream_id]
|
||||
|
||||
def _make_request(self, event: HeadersReceived) -> Request:
|
||||
headers = Header(((k.decode(), v.decode()) for k, v in event.headers))
|
||||
method = headers[":method"]
|
||||
path = headers[":path"]
|
||||
scheme = headers.pop(":scheme", "")
|
||||
authority = headers.pop(":authority", "")
|
||||
|
||||
if authority:
|
||||
headers["host"] = authority
|
||||
|
||||
transport = HTTP3Transport(self.protocol)
|
||||
request = self.protocol.request_class(
|
||||
path.encode(),
|
||||
headers,
|
||||
"3",
|
||||
method,
|
||||
transport,
|
||||
self.protocol.app,
|
||||
b"",
|
||||
)
|
||||
request.conn_info = ConnInfo(transport)
|
||||
request._stream_id = event.stream_id
|
||||
request._scheme = scheme
|
||||
|
||||
return request
|
||||
|
||||
|
||||
class SessionTicketStore:
|
||||
"""
|
||||
Simple in-memory store for session tickets.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.tickets: Dict[bytes, SessionTicket] = {}
|
||||
|
||||
def add(self, ticket: SessionTicket) -> None:
|
||||
self.tickets[ticket.ticket] = ticket
|
||||
|
||||
def pop(self, label: bytes) -> Optional[SessionTicket]:
|
||||
return self.tickets.pop(label, None)
|
||||
|
||||
|
||||
def get_config(
|
||||
app: Sanic, ssl: Union[SanicSSLContext, CertSelector, SSLContext]
|
||||
):
|
||||
# TODO:
|
||||
# - proper selection needed if servince with multiple certs insted of
|
||||
# just taking the first
|
||||
if isinstance(ssl, CertSelector):
|
||||
ssl = cast(SanicSSLContext, ssl.sanic_select[0])
|
||||
if app.config.LOCAL_CERT_CREATOR is LocalCertCreator.TRUSTME:
|
||||
raise SanicException(
|
||||
"Sorry, you cannot currently use trustme as a local certificate "
|
||||
"generator for an HTTP/3 server. This is not yet supported. You "
|
||||
"should be able to use mkcert instead. For more information, see: "
|
||||
"https://github.com/aiortc/aioquic/issues/295."
|
||||
)
|
||||
if not isinstance(ssl, CertSimple):
|
||||
raise SanicException("SSLContext is not CertSimple")
|
||||
|
||||
config = QuicConfiguration(
|
||||
alpn_protocols=H3_ALPN + H0_ALPN + ["siduck"],
|
||||
is_client=False,
|
||||
max_datagram_frame_size=65536,
|
||||
)
|
||||
password = app.config.TLS_CERT_PASSWORD or None
|
||||
|
||||
config.load_cert_chain(
|
||||
ssl.sanic["cert"], ssl.sanic["key"], password=password
|
||||
)
|
||||
|
||||
return config
|
||||
27
sanic/http/stream.py
Normal file
27
sanic/http/stream.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Optional, Tuple, Union
|
||||
|
||||
from sanic.http.constants import Stage
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic.response import BaseHTTPResponse
|
||||
from sanic.server.protocols.http_protocol import HttpProtocol
|
||||
|
||||
|
||||
class Stream:
|
||||
stage: Stage
|
||||
response: Optional[BaseHTTPResponse]
|
||||
protocol: HttpProtocol
|
||||
url: Optional[str]
|
||||
request_body: Optional[bytes]
|
||||
request_max_size: Union[int, float]
|
||||
|
||||
__touchup__: Tuple[str, ...] = tuple()
|
||||
__slots__ = ()
|
||||
|
||||
def respond(
|
||||
self, response: BaseHTTPResponse
|
||||
) -> BaseHTTPResponse: # no cov
|
||||
raise NotImplementedError("Not implemented")
|
||||
5
sanic/http/tls/__init__.py
Normal file
5
sanic/http/tls/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .context import process_to_context
|
||||
from .creators import get_ssl_context
|
||||
|
||||
|
||||
__all__ = ("get_ssl_context", "process_to_context")
|
||||
@@ -1,7 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import ssl
|
||||
|
||||
from typing import Iterable, Optional, Union
|
||||
from typing import Any, Dict, Iterable, Optional, Union
|
||||
|
||||
from sanic.log import logger
|
||||
|
||||
@@ -77,65 +79,6 @@ def load_cert_dir(p: str) -> ssl.SSLContext:
|
||||
return CertSimple(certfile, keyfile)
|
||||
|
||||
|
||||
class CertSimple(ssl.SSLContext):
|
||||
"""A wrapper for creating SSLContext with a sanic attribute."""
|
||||
|
||||
def __new__(cls, cert, key, **kw):
|
||||
# try common aliases, rename to cert/key
|
||||
certfile = kw["cert"] = kw.pop("certificate", None) or cert
|
||||
keyfile = kw["key"] = kw.pop("keyfile", None) or key
|
||||
password = kw.pop("password", None)
|
||||
if not certfile or not keyfile:
|
||||
raise ValueError("SSL dict needs filenames for cert and key.")
|
||||
subject = {}
|
||||
if "names" not in kw:
|
||||
cert = ssl._ssl._test_decode_cert(certfile) # type: ignore
|
||||
kw["names"] = [
|
||||
name
|
||||
for t, name in cert["subjectAltName"]
|
||||
if t in ["DNS", "IP Address"]
|
||||
]
|
||||
subject = {k: v for item in cert["subject"] for k, v in item}
|
||||
self = create_context(certfile, keyfile, password)
|
||||
self.__class__ = cls
|
||||
self.sanic = {**subject, **kw}
|
||||
return self
|
||||
|
||||
def __init__(self, cert, key, **kw):
|
||||
pass # Do not call super().__init__ because it is already initialized
|
||||
|
||||
|
||||
class CertSelector(ssl.SSLContext):
|
||||
"""Automatically select SSL certificate based on the hostname that the
|
||||
client is trying to access, via SSL SNI. Paths to certificate folders
|
||||
with privkey.pem and fullchain.pem in them should be provided, and
|
||||
will be matched in the order given whenever there is a new connection.
|
||||
"""
|
||||
|
||||
def __new__(cls, ctxs):
|
||||
return super().__new__(cls)
|
||||
|
||||
def __init__(self, ctxs: Iterable[Optional[ssl.SSLContext]]):
|
||||
super().__init__()
|
||||
self.sni_callback = selector_sni_callback # type: ignore
|
||||
self.sanic_select = []
|
||||
self.sanic_fallback = None
|
||||
all_names = []
|
||||
for i, ctx in enumerate(ctxs):
|
||||
if not ctx:
|
||||
continue
|
||||
names = dict(getattr(ctx, "sanic", {})).get("names", [])
|
||||
all_names += names
|
||||
self.sanic_select.append(ctx)
|
||||
if i == 0:
|
||||
self.sanic_fallback = ctx
|
||||
if not all_names:
|
||||
raise ValueError(
|
||||
"No certificates with SubjectAlternativeNames found."
|
||||
)
|
||||
logger.info(f"Certificate vhosts: {', '.join(all_names)}")
|
||||
|
||||
|
||||
def find_cert(self: CertSelector, server_name: str):
|
||||
"""Find the first certificate that matches the given SNI.
|
||||
|
||||
@@ -194,3 +137,73 @@ def server_name_callback(
|
||||
) -> None:
|
||||
"""Store the received SNI as sslobj.sanic_server_name."""
|
||||
sslobj.sanic_server_name = server_name # type: ignore
|
||||
|
||||
|
||||
class SanicSSLContext(ssl.SSLContext):
|
||||
sanic: Dict[str, os.PathLike]
|
||||
|
||||
@classmethod
|
||||
def create_from_ssl_context(cls, context: ssl.SSLContext):
|
||||
context.__class__ = cls
|
||||
return context
|
||||
|
||||
|
||||
class CertSimple(SanicSSLContext):
|
||||
"""A wrapper for creating SSLContext with a sanic attribute."""
|
||||
|
||||
sanic: Dict[str, Any]
|
||||
|
||||
def __new__(cls, cert, key, **kw):
|
||||
# try common aliases, rename to cert/key
|
||||
certfile = kw["cert"] = kw.pop("certificate", None) or cert
|
||||
keyfile = kw["key"] = kw.pop("keyfile", None) or key
|
||||
password = kw.pop("password", None)
|
||||
if not certfile or not keyfile:
|
||||
raise ValueError("SSL dict needs filenames for cert and key.")
|
||||
subject = {}
|
||||
if "names" not in kw:
|
||||
cert = ssl._ssl._test_decode_cert(certfile) # type: ignore
|
||||
kw["names"] = [
|
||||
name
|
||||
for t, name in cert["subjectAltName"]
|
||||
if t in ["DNS", "IP Address"]
|
||||
]
|
||||
subject = {k: v for item in cert["subject"] for k, v in item}
|
||||
self = create_context(certfile, keyfile, password)
|
||||
self.__class__ = cls
|
||||
self.sanic = {**subject, **kw}
|
||||
return self
|
||||
|
||||
def __init__(self, cert, key, **kw):
|
||||
pass # Do not call super().__init__ because it is already initialized
|
||||
|
||||
|
||||
class CertSelector(ssl.SSLContext):
|
||||
"""Automatically select SSL certificate based on the hostname that the
|
||||
client is trying to access, via SSL SNI. Paths to certificate folders
|
||||
with privkey.pem and fullchain.pem in them should be provided, and
|
||||
will be matched in the order given whenever there is a new connection.
|
||||
"""
|
||||
|
||||
def __new__(cls, ctxs):
|
||||
return super().__new__(cls)
|
||||
|
||||
def __init__(self, ctxs: Iterable[Optional[ssl.SSLContext]]):
|
||||
super().__init__()
|
||||
self.sni_callback = selector_sni_callback # type: ignore
|
||||
self.sanic_select = []
|
||||
self.sanic_fallback = None
|
||||
all_names = []
|
||||
for i, ctx in enumerate(ctxs):
|
||||
if not ctx:
|
||||
continue
|
||||
names = dict(getattr(ctx, "sanic", {})).get("names", [])
|
||||
all_names += names
|
||||
self.sanic_select.append(ctx)
|
||||
if i == 0:
|
||||
self.sanic_fallback = ctx
|
||||
if not all_names:
|
||||
raise ValueError(
|
||||
"No certificates with SubjectAlternativeNames found."
|
||||
)
|
||||
logger.info(f"Certificate vhosts: {', '.join(all_names)}")
|
||||
278
sanic/http/tls/creators.py
Normal file
278
sanic/http/tls/creators.py
Normal file
@@ -0,0 +1,278 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from types import ModuleType
|
||||
from typing import TYPE_CHECKING, Optional, Tuple, Type, Union, cast
|
||||
|
||||
from sanic.application.constants import Mode
|
||||
from sanic.application.spinner import loading
|
||||
from sanic.constants import (
|
||||
DEFAULT_LOCAL_TLS_CERT,
|
||||
DEFAULT_LOCAL_TLS_KEY,
|
||||
LocalCertCreator,
|
||||
)
|
||||
from sanic.exceptions import SanicException
|
||||
from sanic.helpers import Default
|
||||
from sanic.http.tls.context import CertSimple, SanicSSLContext
|
||||
|
||||
|
||||
try:
|
||||
import trustme
|
||||
|
||||
TRUSTME_INSTALLED = True
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
trustme = ModuleType("trustme")
|
||||
TRUSTME_INSTALLED = False
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
# Only allow secure ciphers, notably leaving out AES-CBC mode
|
||||
# OpenSSL chooses ECDSA or RSA depending on the cert in use
|
||||
CIPHERS_TLS12 = [
|
||||
"ECDHE-ECDSA-CHACHA20-POLY1305",
|
||||
"ECDHE-ECDSA-AES256-GCM-SHA384",
|
||||
"ECDHE-ECDSA-AES128-GCM-SHA256",
|
||||
"ECDHE-RSA-CHACHA20-POLY1305",
|
||||
"ECDHE-RSA-AES256-GCM-SHA384",
|
||||
"ECDHE-RSA-AES128-GCM-SHA256",
|
||||
]
|
||||
|
||||
|
||||
def _make_path(maybe_path: Union[Path, str], tmpdir: Optional[Path]) -> Path:
|
||||
if isinstance(maybe_path, Path):
|
||||
return maybe_path
|
||||
else:
|
||||
path = Path(maybe_path)
|
||||
if not path.exists():
|
||||
if not tmpdir:
|
||||
raise RuntimeError("Reached an unknown state. No tmpdir.")
|
||||
return tmpdir / maybe_path
|
||||
|
||||
return path
|
||||
|
||||
|
||||
def get_ssl_context(
|
||||
app: Sanic, ssl: Optional[ssl.SSLContext]
|
||||
) -> ssl.SSLContext:
|
||||
if ssl:
|
||||
return ssl
|
||||
|
||||
if app.state.mode is Mode.PRODUCTION:
|
||||
raise SanicException(
|
||||
"Cannot run Sanic as an HTTPS server in PRODUCTION mode "
|
||||
"without passing a TLS certificate. If you are developing "
|
||||
"locally, please enable DEVELOPMENT mode and Sanic will "
|
||||
"generate a localhost TLS certificate. For more information "
|
||||
"please see: ___."
|
||||
)
|
||||
|
||||
creator = CertCreator.select(
|
||||
app,
|
||||
cast(LocalCertCreator, app.config.LOCAL_CERT_CREATOR),
|
||||
app.config.LOCAL_TLS_KEY,
|
||||
app.config.LOCAL_TLS_CERT,
|
||||
)
|
||||
context = creator.generate_cert(app.config.LOCALHOST)
|
||||
return context
|
||||
|
||||
|
||||
class CertCreator(ABC):
|
||||
def __init__(self, app, key, cert) -> None:
|
||||
self.app = app
|
||||
self.key = key
|
||||
self.cert = cert
|
||||
self.tmpdir = None
|
||||
|
||||
if isinstance(self.key, Default) or isinstance(self.cert, Default):
|
||||
self.tmpdir = Path(mkdtemp())
|
||||
|
||||
key = (
|
||||
DEFAULT_LOCAL_TLS_KEY
|
||||
if isinstance(self.key, Default)
|
||||
else self.key
|
||||
)
|
||||
cert = (
|
||||
DEFAULT_LOCAL_TLS_CERT
|
||||
if isinstance(self.cert, Default)
|
||||
else self.cert
|
||||
)
|
||||
|
||||
self.key_path = _make_path(key, self.tmpdir)
|
||||
self.cert_path = _make_path(cert, self.tmpdir)
|
||||
|
||||
@abstractmethod
|
||||
def check_supported(self) -> None: # no cov
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def generate_cert(self, localhost: str) -> ssl.SSLContext: # no cov
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def select(
|
||||
cls,
|
||||
app: Sanic,
|
||||
cert_creator: LocalCertCreator,
|
||||
local_tls_key,
|
||||
local_tls_cert,
|
||||
) -> CertCreator:
|
||||
|
||||
creator: Optional[CertCreator] = None
|
||||
|
||||
cert_creator_options: Tuple[
|
||||
Tuple[Type[CertCreator], LocalCertCreator], ...
|
||||
] = (
|
||||
(MkcertCreator, LocalCertCreator.MKCERT),
|
||||
(TrustmeCreator, LocalCertCreator.TRUSTME),
|
||||
)
|
||||
for creator_class, local_creator in cert_creator_options:
|
||||
creator = cls._try_select(
|
||||
app,
|
||||
creator,
|
||||
creator_class,
|
||||
local_creator,
|
||||
cert_creator,
|
||||
local_tls_key,
|
||||
local_tls_cert,
|
||||
)
|
||||
if creator:
|
||||
break
|
||||
|
||||
if not creator:
|
||||
raise SanicException(
|
||||
"Sanic could not find package to create a TLS certificate. "
|
||||
"You must have either mkcert or trustme installed. See "
|
||||
"_____ for more details."
|
||||
)
|
||||
|
||||
return creator
|
||||
|
||||
@staticmethod
|
||||
def _try_select(
|
||||
app: Sanic,
|
||||
creator: Optional[CertCreator],
|
||||
creator_class: Type[CertCreator],
|
||||
creator_requirement: LocalCertCreator,
|
||||
creator_requested: LocalCertCreator,
|
||||
local_tls_key,
|
||||
local_tls_cert,
|
||||
):
|
||||
if creator or (
|
||||
creator_requested is not LocalCertCreator.AUTO
|
||||
and creator_requested is not creator_requirement
|
||||
):
|
||||
return creator
|
||||
|
||||
instance = creator_class(app, local_tls_key, local_tls_cert)
|
||||
try:
|
||||
instance.check_supported()
|
||||
except SanicException:
|
||||
if creator_requested is creator_requirement:
|
||||
raise
|
||||
else:
|
||||
return None
|
||||
|
||||
return instance
|
||||
|
||||
|
||||
class MkcertCreator(CertCreator):
|
||||
def check_supported(self) -> None:
|
||||
try:
|
||||
subprocess.run( # nosec B603 B607
|
||||
["mkcert", "-help"],
|
||||
check=True,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
except Exception as e:
|
||||
raise SanicException(
|
||||
"Sanic is attempting to use mkcert to generate local TLS "
|
||||
"certificates since you did not supply a certificate, but "
|
||||
"one is required. Sanic cannot proceed since mkcert does not "
|
||||
"appear to be installed. Alternatively, you can use trustme. "
|
||||
"Please install mkcert, trustme, or supply TLS certificates "
|
||||
"to proceed. Installation instructions can be found here: "
|
||||
"https://github.com/FiloSottile/mkcert.\n"
|
||||
"Find out more information about your options here: "
|
||||
"_____"
|
||||
) from e
|
||||
|
||||
def generate_cert(self, localhost: str) -> ssl.SSLContext:
|
||||
try:
|
||||
if not self.cert_path.exists():
|
||||
message = "Generating TLS certificate"
|
||||
# TODO: Validate input for security
|
||||
with loading(message):
|
||||
cmd = [
|
||||
"mkcert",
|
||||
"-key-file",
|
||||
str(self.key_path),
|
||||
"-cert-file",
|
||||
str(self.cert_path),
|
||||
localhost,
|
||||
]
|
||||
resp = subprocess.run( # nosec B603
|
||||
cmd,
|
||||
check=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
sys.stdout.write("\r" + " " * (len(message) + 4))
|
||||
sys.stdout.flush()
|
||||
sys.stdout.write(resp.stdout)
|
||||
finally:
|
||||
|
||||
@self.app.main_process_stop
|
||||
async def cleanup(*_): # no cov
|
||||
if self.tmpdir:
|
||||
with suppress(FileNotFoundError):
|
||||
self.key_path.unlink()
|
||||
self.cert_path.unlink()
|
||||
self.tmpdir.rmdir()
|
||||
|
||||
return CertSimple(self.cert_path, self.key_path)
|
||||
|
||||
|
||||
class TrustmeCreator(CertCreator):
|
||||
def check_supported(self) -> None:
|
||||
if not TRUSTME_INSTALLED:
|
||||
raise SanicException(
|
||||
"Sanic is attempting to use trustme to generate local TLS "
|
||||
"certificates since you did not supply a certificate, but "
|
||||
"one is required. Sanic cannot proceed since trustme does not "
|
||||
"appear to be installed. Alternatively, you can use mkcert. "
|
||||
"Please install mkcert, trustme, or supply TLS certificates "
|
||||
"to proceed. Installation instructions can be found here: "
|
||||
"https://github.com/python-trio/trustme.\n"
|
||||
"Find out more information about your options here: "
|
||||
"_____"
|
||||
)
|
||||
|
||||
def generate_cert(self, localhost: str) -> ssl.SSLContext:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
sanic_context = SanicSSLContext.create_from_ssl_context(context)
|
||||
sanic_context.sanic = {
|
||||
"cert": self.cert_path.absolute(),
|
||||
"key": self.key_path.absolute(),
|
||||
}
|
||||
ca = trustme.CA()
|
||||
server_cert = ca.issue_cert(localhost)
|
||||
server_cert.configure_cert(sanic_context)
|
||||
ca.configure_trust(context)
|
||||
|
||||
ca.cert_pem.write_to_path(str(self.cert_path.absolute()))
|
||||
server_cert.private_key_and_cert_chain_pem.write_to_path(
|
||||
str(self.key_path.absolute())
|
||||
)
|
||||
|
||||
return context
|
||||
41
sanic/log.py
41
sanic/log.py
@@ -3,9 +3,12 @@ import sys
|
||||
|
||||
from enum import Enum
|
||||
from typing import Any, Dict
|
||||
from warnings import warn
|
||||
|
||||
from sanic.compat import is_atty
|
||||
|
||||
|
||||
LOGGING_CONFIG_DEFAULTS: Dict[str, Any] = dict(
|
||||
LOGGING_CONFIG_DEFAULTS: Dict[str, Any] = dict( # no cov
|
||||
version=1,
|
||||
disable_existing_loggers=False,
|
||||
loggers={
|
||||
@@ -54,27 +57,53 @@ LOGGING_CONFIG_DEFAULTS: Dict[str, Any] = dict(
|
||||
},
|
||||
},
|
||||
)
|
||||
"""
|
||||
Defult logging configuration
|
||||
"""
|
||||
|
||||
|
||||
class Colors(str, Enum):
|
||||
class Colors(str, Enum): # no cov
|
||||
END = "\033[0m"
|
||||
BLUE = "\033[01;34m"
|
||||
GREEN = "\033[01;32m"
|
||||
YELLOW = "\033[01;33m"
|
||||
PURPLE = "\033[01;35m"
|
||||
RED = "\033[01;31m"
|
||||
SANIC = "\033[38;2;255;13;104m"
|
||||
YELLOW = "\033[01;33m"
|
||||
|
||||
|
||||
logger = logging.getLogger("sanic.root")
|
||||
class VerbosityFilter(logging.Filter):
|
||||
verbosity: int = 0
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
verbosity = getattr(record, "verbosity", 0)
|
||||
return verbosity <= self.verbosity
|
||||
|
||||
|
||||
_verbosity_filter = VerbosityFilter()
|
||||
|
||||
logger = logging.getLogger("sanic.root") # no cov
|
||||
"""
|
||||
General Sanic logger
|
||||
"""
|
||||
logger.addFilter(_verbosity_filter)
|
||||
|
||||
error_logger = logging.getLogger("sanic.error")
|
||||
error_logger = logging.getLogger("sanic.error") # no cov
|
||||
"""
|
||||
Logger used by Sanic for error logging
|
||||
"""
|
||||
error_logger.addFilter(_verbosity_filter)
|
||||
|
||||
access_logger = logging.getLogger("sanic.access")
|
||||
access_logger = logging.getLogger("sanic.access") # no cov
|
||||
"""
|
||||
Logger used by Sanic for access logging
|
||||
"""
|
||||
access_logger.addFilter(_verbosity_filter)
|
||||
|
||||
|
||||
def deprecation(message: str, version: float): # no cov
|
||||
version_info = f"[DEPRECATION v{version}] "
|
||||
if is_atty():
|
||||
version_info = f"{Colors.RED}{version_info}"
|
||||
message = f"{Colors.YELLOW}{message}{Colors.END}"
|
||||
warn(version_info + message, DeprecationWarning)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from typing import Set
|
||||
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.models.futures import FutureException
|
||||
|
||||
|
||||
class ExceptionMixin:
|
||||
class ExceptionMixin(metaclass=SanicMeta):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_exceptions: Set[FutureException] = set()
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from enum import Enum, auto
|
||||
from functools import partial
|
||||
from typing import List, Optional, Union
|
||||
from typing import Callable, List, Optional, Union, overload
|
||||
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.exceptions import BadRequest
|
||||
from sanic.models.futures import FutureListener
|
||||
from sanic.models.handler_types import ListenerType, Sanic
|
||||
|
||||
@@ -16,21 +18,44 @@ class ListenerEvent(str, Enum):
|
||||
AFTER_SERVER_STOP = "server.shutdown.after"
|
||||
MAIN_PROCESS_START = auto()
|
||||
MAIN_PROCESS_STOP = auto()
|
||||
RELOAD_PROCESS_START = auto()
|
||||
RELOAD_PROCESS_STOP = auto()
|
||||
|
||||
|
||||
class ListenerMixin:
|
||||
class ListenerMixin(metaclass=SanicMeta):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_listeners: List[FutureListener] = []
|
||||
|
||||
def _apply_listener(self, listener: FutureListener):
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
@overload
|
||||
def listener(
|
||||
self,
|
||||
listener_or_event: ListenerType[Sanic],
|
||||
event_or_none: str,
|
||||
apply: bool = ...,
|
||||
) -> ListenerType[Sanic]:
|
||||
...
|
||||
|
||||
@overload
|
||||
def listener(
|
||||
self,
|
||||
listener_or_event: str,
|
||||
event_or_none: None = ...,
|
||||
apply: bool = ...,
|
||||
) -> Callable[[ListenerType[Sanic]], ListenerType[Sanic]]:
|
||||
...
|
||||
|
||||
def listener(
|
||||
self,
|
||||
listener_or_event: Union[ListenerType[Sanic], str],
|
||||
event_or_none: Optional[str] = None,
|
||||
apply: bool = True,
|
||||
) -> ListenerType[Sanic]:
|
||||
) -> Union[
|
||||
ListenerType[Sanic],
|
||||
Callable[[ListenerType[Sanic]], ListenerType[Sanic]],
|
||||
]:
|
||||
"""
|
||||
Create a listener from a decorated function.
|
||||
|
||||
@@ -48,7 +73,9 @@ class ListenerMixin:
|
||||
:param event: event to listen to
|
||||
"""
|
||||
|
||||
def register_listener(listener, event):
|
||||
def register_listener(
|
||||
listener: ListenerType[Sanic], event: str
|
||||
) -> ListenerType[Sanic]:
|
||||
nonlocal apply
|
||||
|
||||
future_listener = FutureListener(listener, event)
|
||||
@@ -58,6 +85,10 @@ class ListenerMixin:
|
||||
return listener
|
||||
|
||||
if callable(listener_or_event):
|
||||
if event_or_none is None:
|
||||
raise BadRequest(
|
||||
"Invalid event registration: Missing event name."
|
||||
)
|
||||
return register_listener(listener_or_event, event_or_none)
|
||||
else:
|
||||
return partial(register_listener, event=listener_or_event)
|
||||
@@ -72,6 +103,16 @@ class ListenerMixin:
|
||||
) -> ListenerType[Sanic]:
|
||||
return self.listener(listener, "main_process_stop")
|
||||
|
||||
def reload_process_start(
|
||||
self, listener: ListenerType[Sanic]
|
||||
) -> ListenerType[Sanic]:
|
||||
return self.listener(listener, "reload_process_start")
|
||||
|
||||
def reload_process_stop(
|
||||
self, listener: ListenerType[Sanic]
|
||||
) -> ListenerType[Sanic]:
|
||||
return self.listener(listener, "reload_process_stop")
|
||||
|
||||
def before_server_start(
|
||||
self, listener: ListenerType[Sanic]
|
||||
) -> ListenerType[Sanic]:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
from functools import partial
|
||||
from typing import List
|
||||
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.models.futures import FutureMiddleware
|
||||
|
||||
|
||||
class MiddlewareMixin:
|
||||
class MiddlewareMixin(metaclass=SanicMeta):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_middleware: List[FutureMiddleware] = []
|
||||
|
||||
@@ -15,9 +16,9 @@ class MiddlewareMixin:
|
||||
self, middleware_or_request, attach_to="request", apply=True
|
||||
):
|
||||
"""
|
||||
Decorate and register middleware to be called before a request.
|
||||
Can either be called as *@app.middleware* or
|
||||
*@app.middleware('request')*
|
||||
Decorate and register middleware to be called before a request
|
||||
is handled or after a response is created. Can either be called as
|
||||
*@app.middleware* or *@app.middleware('request')*.
|
||||
|
||||
`See user guide re: middleware
|
||||
<https://sanicframework.org/guide/basics/middleware.html>`__
|
||||
@@ -46,12 +47,25 @@ class MiddlewareMixin:
|
||||
)
|
||||
|
||||
def on_request(self, middleware=None):
|
||||
"""Register a middleware to be called before a request is handled.
|
||||
|
||||
This is the same as *@app.middleware('request')*.
|
||||
|
||||
:param: middleware: A callable that takes in request.
|
||||
"""
|
||||
if callable(middleware):
|
||||
return self.middleware(middleware, "request")
|
||||
else:
|
||||
return partial(self.middleware, attach_to="request")
|
||||
|
||||
def on_response(self, middleware=None):
|
||||
"""Register a middleware to be called after a response is created.
|
||||
|
||||
This is the same as *@app.middleware('response')*.
|
||||
|
||||
:param: middleware:
|
||||
A callable that takes in a request and its response.
|
||||
"""
|
||||
if callable(middleware):
|
||||
return self.middleware(middleware, "response")
|
||||
else:
|
||||
|
||||
@@ -1,40 +1,54 @@
|
||||
from ast import NodeVisitor, Return, parse
|
||||
from contextlib import suppress
|
||||
from functools import partial, wraps
|
||||
from inspect import getsource, signature
|
||||
from mimetypes import guess_type
|
||||
from os import path
|
||||
from pathlib import PurePath
|
||||
from re import sub
|
||||
from pathlib import Path, PurePath
|
||||
from textwrap import dedent
|
||||
from time import gmtime, strftime
|
||||
from typing import Any, Callable, Iterable, List, Optional, Set, Tuple, Union
|
||||
from typing import (
|
||||
Any,
|
||||
Callable,
|
||||
Iterable,
|
||||
List,
|
||||
Optional,
|
||||
Set,
|
||||
Tuple,
|
||||
Union,
|
||||
cast,
|
||||
)
|
||||
from urllib.parse import unquote
|
||||
|
||||
from sanic_routing.route import Route # type: ignore
|
||||
from sanic_routing.route import Route
|
||||
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.compat import stat_async
|
||||
from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS
|
||||
from sanic.errorpages import RESPONSE_MAPPING
|
||||
from sanic.exceptions import (
|
||||
ContentRangeError,
|
||||
FileNotFound,
|
||||
HeaderNotFound,
|
||||
InvalidUsage,
|
||||
)
|
||||
from sanic.exceptions import FileNotFound, HeaderNotFound, RangeNotSatisfiable
|
||||
from sanic.handlers import ContentRangeHandler
|
||||
from sanic.log import error_logger
|
||||
from sanic.models.futures import FutureRoute, FutureStatic
|
||||
from sanic.models.handler_types import RouteHandler
|
||||
from sanic.response import HTTPResponse, file, file_stream
|
||||
from sanic.views import CompositionView
|
||||
from sanic.types import HashableDict
|
||||
|
||||
|
||||
RouteWrapper = Callable[
|
||||
[RouteHandler], Union[RouteHandler, Tuple[Route, RouteHandler]]
|
||||
]
|
||||
RESTRICTED_ROUTE_CONTEXT = (
|
||||
"ignore_body",
|
||||
"stream",
|
||||
"hosts",
|
||||
"static",
|
||||
"error_format",
|
||||
"websocket",
|
||||
)
|
||||
|
||||
|
||||
class RouteMixin:
|
||||
class RouteMixin(metaclass=SanicMeta):
|
||||
name: str
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
@@ -65,10 +79,20 @@ class RouteMixin:
|
||||
static: bool = False,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
**ctx_kwargs: Any,
|
||||
) -> RouteWrapper:
|
||||
"""
|
||||
Decorate a function to be registered as a route
|
||||
|
||||
|
||||
**Example using context kwargs**
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.route(..., ctx_foo="foobar")
|
||||
async def route_handler(request: Request):
|
||||
assert request.route.ctx.foo == "foobar"
|
||||
|
||||
:param uri: path of the URL
|
||||
:param methods: list or tuple of methods allowed
|
||||
:param host: the host, if required
|
||||
@@ -80,6 +104,8 @@ class RouteMixin:
|
||||
body (eg. GET requests)
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: tuple of routes, decorated function
|
||||
"""
|
||||
|
||||
@@ -94,6 +120,8 @@ class RouteMixin:
|
||||
if not methods and not websocket:
|
||||
methods = frozenset({"GET"})
|
||||
|
||||
route_context = self._build_route_context(ctx_kwargs)
|
||||
|
||||
def decorator(handler):
|
||||
nonlocal uri
|
||||
nonlocal methods
|
||||
@@ -152,6 +180,7 @@ class RouteMixin:
|
||||
static,
|
||||
version_prefix,
|
||||
error_format,
|
||||
route_context,
|
||||
)
|
||||
|
||||
self._future_routes.add(route)
|
||||
@@ -196,6 +225,7 @@ class RouteMixin:
|
||||
stream: bool = False,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""A helper method to register class instance or
|
||||
functions as a handler to the application url
|
||||
@@ -212,6 +242,8 @@ class RouteMixin:
|
||||
:param stream: boolean specifying if the handler is a stream handler
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: function or class instance
|
||||
"""
|
||||
# Handle HTTPMethodView differently
|
||||
@@ -226,14 +258,6 @@ class RouteMixin:
|
||||
if hasattr(_handler, "is_stream"):
|
||||
stream = True
|
||||
|
||||
# handle composition view differently
|
||||
if isinstance(handler, CompositionView):
|
||||
methods = handler.handlers.keys()
|
||||
for _handler in handler.handlers.values():
|
||||
if hasattr(_handler, "is_stream"):
|
||||
stream = True
|
||||
break
|
||||
|
||||
if strict_slashes is None:
|
||||
strict_slashes = self.strict_slashes
|
||||
|
||||
@@ -247,6 +271,7 @@ class RouteMixin:
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
)(handler)
|
||||
return handler
|
||||
|
||||
@@ -261,7 +286,8 @@ class RouteMixin:
|
||||
ignore_body: bool = True,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **GET** *HTTP* method
|
||||
|
||||
@@ -273,18 +299,24 @@ class RouteMixin:
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"GET"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"GET"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def post(
|
||||
@@ -297,7 +329,8 @@ class RouteMixin:
|
||||
name: Optional[str] = None,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **POST** *HTTP* method
|
||||
|
||||
@@ -309,18 +342,24 @@ class RouteMixin:
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"POST"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"POST"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def put(
|
||||
@@ -333,7 +372,8 @@ class RouteMixin:
|
||||
name: Optional[str] = None,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **PUT** *HTTP* method
|
||||
|
||||
@@ -345,18 +385,24 @@ class RouteMixin:
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"PUT"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"PUT"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def head(
|
||||
@@ -369,7 +415,8 @@ class RouteMixin:
|
||||
ignore_body: bool = True,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **HEAD** *HTTP* method
|
||||
|
||||
@@ -389,18 +436,24 @@ class RouteMixin:
|
||||
:type ignore_body: bool, optional
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"HEAD"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"HEAD"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def options(
|
||||
@@ -413,7 +466,8 @@ class RouteMixin:
|
||||
ignore_body: bool = True,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **OPTIONS** *HTTP* method
|
||||
|
||||
@@ -433,18 +487,24 @@ class RouteMixin:
|
||||
:type ignore_body: bool, optional
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"OPTIONS"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"OPTIONS"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def patch(
|
||||
@@ -457,7 +517,8 @@ class RouteMixin:
|
||||
name: Optional[str] = None,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **PATCH** *HTTP* method
|
||||
|
||||
@@ -479,18 +540,24 @@ class RouteMixin:
|
||||
:type ignore_body: bool, optional
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"PATCH"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"PATCH"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def delete(
|
||||
@@ -503,7 +570,8 @@ class RouteMixin:
|
||||
ignore_body: bool = True,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
) -> RouteWrapper:
|
||||
**ctx_kwargs,
|
||||
) -> RouteHandler:
|
||||
"""
|
||||
Add an API URL under the **DELETE** *HTTP* method
|
||||
|
||||
@@ -515,18 +583,24 @@ class RouteMixin:
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"DELETE"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
return cast(
|
||||
RouteHandler,
|
||||
self.route(
|
||||
uri,
|
||||
methods=frozenset({"DELETE"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
ignore_body=ignore_body,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
def websocket(
|
||||
@@ -540,6 +614,7 @@ class RouteMixin:
|
||||
apply: bool = True,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
**ctx_kwargs,
|
||||
):
|
||||
"""
|
||||
Decorate a function to be registered as a websocket route
|
||||
@@ -553,6 +628,8 @@ class RouteMixin:
|
||||
be used with :func:`url_for`
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: tuple of routes, decorated function
|
||||
"""
|
||||
return self.route(
|
||||
@@ -567,6 +644,7 @@ class RouteMixin:
|
||||
websocket=True,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
)
|
||||
|
||||
def add_websocket_route(
|
||||
@@ -580,6 +658,7 @@ class RouteMixin:
|
||||
name: Optional[str] = None,
|
||||
version_prefix: str = "/v",
|
||||
error_format: Optional[str] = None,
|
||||
**ctx_kwargs,
|
||||
):
|
||||
"""
|
||||
A helper method to register a function as a websocket route.
|
||||
@@ -598,6 +677,8 @@ class RouteMixin:
|
||||
be used with :func:`url_for`
|
||||
:param version_prefix: URL path that should be before the version
|
||||
value; default: ``/v``
|
||||
:param ctx_kwargs: Keyword arguments that begin with a ctx_* prefix
|
||||
will be appended to the route context (``route.ctx``)
|
||||
:return: Objected decorated by :func:`websocket`
|
||||
"""
|
||||
return self.websocket(
|
||||
@@ -609,6 +690,7 @@ class RouteMixin:
|
||||
name=name,
|
||||
version_prefix=version_prefix,
|
||||
error_format=error_format,
|
||||
**ctx_kwargs,
|
||||
)(handler)
|
||||
|
||||
def static(
|
||||
@@ -718,32 +800,40 @@ class RouteMixin:
|
||||
content_type=None,
|
||||
__file_uri__=None,
|
||||
):
|
||||
# Using this to determine if the URL is trying to break out of the path
|
||||
# served. os.path.realpath seems to be very slow
|
||||
if __file_uri__ and "../" in __file_uri__:
|
||||
raise InvalidUsage("Invalid URL")
|
||||
# Merge served directory and requested file if provided
|
||||
# Strip all / that in the beginning of the URL to help prevent python
|
||||
# from herping a derp and treating the uri as an absolute path
|
||||
root_path = file_path = file_or_directory
|
||||
if __file_uri__:
|
||||
file_path = path.join(
|
||||
file_or_directory, sub("^[/]*", "", __file_uri__)
|
||||
)
|
||||
file_path_raw = Path(unquote(file_or_directory))
|
||||
root_path = file_path = file_path_raw.resolve()
|
||||
not_found = FileNotFound(
|
||||
"File not found",
|
||||
path=file_or_directory,
|
||||
relative_url=__file_uri__,
|
||||
)
|
||||
|
||||
# URL decode the path sent by the browser otherwise we won't be able to
|
||||
# match filenames which got encoded (filenames with spaces etc)
|
||||
file_path = path.abspath(unquote(file_path))
|
||||
if not file_path.startswith(path.abspath(unquote(root_path))):
|
||||
error_logger.exception(
|
||||
f"File not found: path={file_or_directory}, "
|
||||
f"relative_url={__file_uri__}"
|
||||
)
|
||||
raise FileNotFound(
|
||||
"File not found",
|
||||
path=file_or_directory,
|
||||
relative_url=__file_uri__,
|
||||
)
|
||||
if __file_uri__:
|
||||
# Strip all / that in the beginning of the URL to help prevent
|
||||
# python from herping a derp and treating the uri as an
|
||||
# absolute path
|
||||
unquoted_file_uri = unquote(__file_uri__).lstrip("/")
|
||||
file_path_raw = Path(file_or_directory, unquoted_file_uri)
|
||||
file_path = file_path_raw.resolve()
|
||||
if (
|
||||
file_path < root_path and not file_path_raw.is_symlink()
|
||||
) or ".." in file_path_raw.parts:
|
||||
error_logger.exception(
|
||||
f"File not found: path={file_or_directory}, "
|
||||
f"relative_url={__file_uri__}"
|
||||
)
|
||||
raise not_found
|
||||
|
||||
try:
|
||||
file_path.relative_to(root_path)
|
||||
except ValueError:
|
||||
if not file_path_raw.is_symlink():
|
||||
error_logger.exception(
|
||||
f"File not found: path={file_or_directory}, "
|
||||
f"relative_url={__file_uri__}"
|
||||
)
|
||||
raise not_found
|
||||
try:
|
||||
headers = {}
|
||||
# Check if the client has been sent this file before
|
||||
@@ -808,14 +898,10 @@ class RouteMixin:
|
||||
file_path, headers=headers, _range=_range
|
||||
)
|
||||
return await file(file_path, headers=headers, _range=_range)
|
||||
except ContentRangeError:
|
||||
except RangeNotSatisfiable:
|
||||
raise
|
||||
except FileNotFoundError:
|
||||
raise FileNotFound(
|
||||
"File not found",
|
||||
path=file_or_directory,
|
||||
relative_url=__file_uri__,
|
||||
)
|
||||
raise not_found
|
||||
except Exception:
|
||||
error_logger.exception(
|
||||
f"Exception in static request handler: "
|
||||
@@ -918,19 +1004,16 @@ class RouteMixin:
|
||||
|
||||
return route
|
||||
|
||||
def _determine_error_format(self, handler) -> Optional[str]:
|
||||
if not isinstance(handler, CompositionView):
|
||||
try:
|
||||
src = dedent(getsource(handler))
|
||||
tree = parse(src)
|
||||
http_response_types = self._get_response_types(tree)
|
||||
def _determine_error_format(self, handler) -> str:
|
||||
with suppress(OSError, TypeError):
|
||||
src = dedent(getsource(handler))
|
||||
tree = parse(src)
|
||||
http_response_types = self._get_response_types(tree)
|
||||
|
||||
if len(http_response_types) == 1:
|
||||
return next(iter(http_response_types))
|
||||
except (OSError, TypeError):
|
||||
...
|
||||
if len(http_response_types) == 1:
|
||||
return next(iter(http_response_types))
|
||||
|
||||
return None
|
||||
return ""
|
||||
|
||||
def _get_response_types(self, node):
|
||||
types = set()
|
||||
@@ -939,7 +1022,7 @@ class RouteMixin:
|
||||
def visit_Return(self, node: Return) -> Any:
|
||||
nonlocal types
|
||||
|
||||
try:
|
||||
with suppress(AttributeError):
|
||||
checks = [node.value.func.id] # type: ignore
|
||||
if node.value.keywords: # type: ignore
|
||||
checks += [
|
||||
@@ -951,9 +1034,32 @@ class RouteMixin:
|
||||
for check in checks:
|
||||
if check in RESPONSE_MAPPING:
|
||||
types.add(RESPONSE_MAPPING[check])
|
||||
except AttributeError:
|
||||
...
|
||||
|
||||
HttpResponseVisitor().visit(node)
|
||||
|
||||
return types
|
||||
|
||||
def _build_route_context(self, raw):
|
||||
ctx_kwargs = {
|
||||
key.replace("ctx_", ""): raw.pop(key)
|
||||
for key in {**raw}.keys()
|
||||
if key.startswith("ctx_")
|
||||
}
|
||||
restricted = [
|
||||
key for key in ctx_kwargs.keys() if key in RESTRICTED_ROUTE_CONTEXT
|
||||
]
|
||||
if restricted:
|
||||
restricted_arguments = ", ".join(restricted)
|
||||
raise AttributeError(
|
||||
"Cannot use restricted route context: "
|
||||
f"{restricted_arguments}. This limitation is only in place "
|
||||
"until v22.9 when the restricted names will no longer be in"
|
||||
"conflict. See https://github.com/sanic-org/sanic/issues/2303 "
|
||||
"for more information."
|
||||
)
|
||||
if raw:
|
||||
unexpected_arguments = ", ".join(raw.keys())
|
||||
raise TypeError(
|
||||
f"Unexpected keyword arguments: {unexpected_arguments}"
|
||||
)
|
||||
return HashableDict(ctx_kwargs)
|
||||
|
||||
797
sanic/mixins/runner.py
Normal file
797
sanic/mixins/runner.py
Normal file
@@ -0,0 +1,797 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
|
||||
from asyncio import (
|
||||
AbstractEventLoop,
|
||||
CancelledError,
|
||||
Protocol,
|
||||
all_tasks,
|
||||
get_event_loop,
|
||||
get_running_loop,
|
||||
new_event_loop,
|
||||
)
|
||||
from contextlib import suppress
|
||||
from functools import partial
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from socket import socket
|
||||
from ssl import SSLContext
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Set,
|
||||
Tuple,
|
||||
Type,
|
||||
Union,
|
||||
cast,
|
||||
)
|
||||
|
||||
from sanic import reloader_helpers
|
||||
from sanic.application.logo import get_logo
|
||||
from sanic.application.motd import MOTD
|
||||
from sanic.application.state import ApplicationServerInfo, Mode, ServerStage
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.compat import OS_IS_WINDOWS, is_atty
|
||||
from sanic.helpers import _default
|
||||
from sanic.http.constants import HTTP
|
||||
from sanic.http.tls import get_ssl_context, process_to_context
|
||||
from sanic.log import Colors, deprecation, error_logger, logger
|
||||
from sanic.models.handler_types import ListenerType
|
||||
from sanic.server import Signal as ServerSignal
|
||||
from sanic.server import try_use_uvloop
|
||||
from sanic.server.async_server import AsyncioServer
|
||||
from sanic.server.events import trigger_events
|
||||
from sanic.server.protocols.http_protocol import HttpProtocol
|
||||
from sanic.server.protocols.websocket_protocol import WebSocketProtocol
|
||||
from sanic.server.runners import serve, serve_multiple, serve_single
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic
|
||||
from sanic.application.state import ApplicationState
|
||||
from sanic.config import Config
|
||||
|
||||
SANIC_PACKAGES = ("sanic-routing", "sanic-testing", "sanic-ext")
|
||||
|
||||
if sys.version_info < (3, 8):
|
||||
HTTPVersion = Union[HTTP, int]
|
||||
else:
|
||||
from typing import Literal
|
||||
|
||||
HTTPVersion = Union[HTTP, Literal[1], Literal[3]]
|
||||
|
||||
|
||||
class RunnerMixin(metaclass=SanicMeta):
|
||||
_app_registry: Dict[str, Sanic]
|
||||
asgi: bool
|
||||
config: Config
|
||||
listeners: Dict[str, List[ListenerType[Any]]]
|
||||
state: ApplicationState
|
||||
websocket_enabled: bool
|
||||
|
||||
def make_coffee(self, *args, **kwargs):
|
||||
self.state.coffee = True
|
||||
self.run(*args, **kwargs)
|
||||
|
||||
def run(
|
||||
self,
|
||||
host: Optional[str] = None,
|
||||
port: Optional[int] = None,
|
||||
*,
|
||||
dev: bool = False,
|
||||
debug: bool = False,
|
||||
auto_reload: Optional[bool] = None,
|
||||
version: HTTPVersion = HTTP.VERSION_1,
|
||||
ssl: Union[None, SSLContext, dict, str, list, tuple] = None,
|
||||
sock: Optional[socket] = None,
|
||||
workers: int = 1,
|
||||
protocol: Optional[Type[Protocol]] = None,
|
||||
backlog: int = 100,
|
||||
register_sys_signals: bool = True,
|
||||
access_log: Optional[bool] = None,
|
||||
unix: Optional[str] = None,
|
||||
loop: AbstractEventLoop = None,
|
||||
reload_dir: Optional[Union[List[str], str]] = None,
|
||||
noisy_exceptions: Optional[bool] = None,
|
||||
motd: bool = True,
|
||||
fast: bool = False,
|
||||
verbosity: int = 0,
|
||||
motd_display: Optional[Dict[str, str]] = None,
|
||||
auto_tls: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Run the HTTP Server and listen until keyboard interrupt or term
|
||||
signal. On termination, drain connections before closing.
|
||||
|
||||
:param host: Address to host on
|
||||
:type host: str
|
||||
:param port: Port to host on
|
||||
:type port: int
|
||||
:param debug: Enables debug output (slows server)
|
||||
:type debug: bool
|
||||
:param auto_reload: Reload app whenever its source code is changed.
|
||||
Enabled by default in debug mode.
|
||||
:type auto_relaod: bool
|
||||
:param ssl: SSLContext, or location of certificate and key
|
||||
for SSL encryption of worker(s)
|
||||
:type ssl: str, dict, SSLContext or list
|
||||
:param sock: Socket for the server to accept connections from
|
||||
:type sock: socket
|
||||
:param workers: Number of processes received before it is respected
|
||||
:type workers: int
|
||||
:param protocol: Subclass of asyncio Protocol class
|
||||
:type protocol: type[Protocol]
|
||||
:param backlog: a number of unaccepted connections that the system
|
||||
will allow before refusing new connections
|
||||
:type backlog: int
|
||||
:param register_sys_signals: Register SIG* events
|
||||
:type register_sys_signals: bool
|
||||
:param access_log: Enables writing access logs (slows server)
|
||||
:type access_log: bool
|
||||
:param unix: Unix socket to listen on instead of TCP port
|
||||
:type unix: str
|
||||
:param noisy_exceptions: Log exceptions that are normally considered
|
||||
to be quiet/silent
|
||||
:type noisy_exceptions: bool
|
||||
:return: Nothing
|
||||
"""
|
||||
self.prepare(
|
||||
host=host,
|
||||
port=port,
|
||||
dev=dev,
|
||||
debug=debug,
|
||||
auto_reload=auto_reload,
|
||||
version=version,
|
||||
ssl=ssl,
|
||||
sock=sock,
|
||||
workers=workers,
|
||||
protocol=protocol,
|
||||
backlog=backlog,
|
||||
register_sys_signals=register_sys_signals,
|
||||
access_log=access_log,
|
||||
unix=unix,
|
||||
loop=loop,
|
||||
reload_dir=reload_dir,
|
||||
noisy_exceptions=noisy_exceptions,
|
||||
motd=motd,
|
||||
fast=fast,
|
||||
verbosity=verbosity,
|
||||
motd_display=motd_display,
|
||||
auto_tls=auto_tls,
|
||||
)
|
||||
|
||||
self.__class__.serve(primary=self) # type: ignore
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
host: Optional[str] = None,
|
||||
port: Optional[int] = None,
|
||||
*,
|
||||
dev: bool = False,
|
||||
debug: bool = False,
|
||||
auto_reload: Optional[bool] = None,
|
||||
version: HTTPVersion = HTTP.VERSION_1,
|
||||
ssl: Union[None, SSLContext, dict, str, list, tuple] = None,
|
||||
sock: Optional[socket] = None,
|
||||
workers: int = 1,
|
||||
protocol: Optional[Type[Protocol]] = None,
|
||||
backlog: int = 100,
|
||||
register_sys_signals: bool = True,
|
||||
access_log: Optional[bool] = None,
|
||||
unix: Optional[str] = None,
|
||||
loop: AbstractEventLoop = None,
|
||||
reload_dir: Optional[Union[List[str], str]] = None,
|
||||
noisy_exceptions: Optional[bool] = None,
|
||||
motd: bool = True,
|
||||
fast: bool = False,
|
||||
verbosity: int = 0,
|
||||
motd_display: Optional[Dict[str, str]] = None,
|
||||
auto_tls: bool = False,
|
||||
) -> None:
|
||||
if version == 3 and self.state.server_info:
|
||||
raise RuntimeError(
|
||||
"Serving HTTP/3 instances as a secondary server is "
|
||||
"not supported. There can only be a single HTTP/3 worker "
|
||||
"and it must be the first instance prepared."
|
||||
)
|
||||
|
||||
if dev:
|
||||
debug = True
|
||||
auto_reload = True
|
||||
|
||||
self.state.verbosity = verbosity
|
||||
if not self.state.auto_reload:
|
||||
self.state.auto_reload = bool(auto_reload)
|
||||
|
||||
if fast and workers != 1:
|
||||
raise RuntimeError("You cannot use both fast=True and workers=X")
|
||||
|
||||
if motd_display:
|
||||
self.config.MOTD_DISPLAY.update(motd_display)
|
||||
|
||||
if reload_dir:
|
||||
if isinstance(reload_dir, str):
|
||||
reload_dir = [reload_dir]
|
||||
|
||||
for directory in reload_dir:
|
||||
direc = Path(directory)
|
||||
if not direc.is_dir():
|
||||
logger.warning(
|
||||
f"Directory {directory} could not be located"
|
||||
)
|
||||
self.state.reload_dirs.add(Path(directory))
|
||||
|
||||
if loop is not None:
|
||||
raise TypeError(
|
||||
"loop is not a valid argument. To use an existing loop, "
|
||||
"change to create_server().\nSee more: "
|
||||
"https://sanic.readthedocs.io/en/latest/sanic/deploying.html"
|
||||
"#asynchronous-support"
|
||||
)
|
||||
|
||||
if (
|
||||
self.__class__.should_auto_reload()
|
||||
and os.environ.get("SANIC_SERVER_RUNNING") != "true"
|
||||
): # no cov
|
||||
return
|
||||
|
||||
if sock is None:
|
||||
host, port = self.get_address(host, port, version, auto_tls)
|
||||
|
||||
if protocol is None:
|
||||
protocol = (
|
||||
WebSocketProtocol if self.websocket_enabled else HttpProtocol
|
||||
)
|
||||
|
||||
# Set explicitly passed configuration values
|
||||
for attribute, value in {
|
||||
"ACCESS_LOG": access_log,
|
||||
"AUTO_RELOAD": auto_reload,
|
||||
"MOTD": motd,
|
||||
"NOISY_EXCEPTIONS": noisy_exceptions,
|
||||
}.items():
|
||||
if value is not None:
|
||||
setattr(self.config, attribute, value)
|
||||
|
||||
if fast:
|
||||
self.state.fast = True
|
||||
try:
|
||||
workers = len(os.sched_getaffinity(0))
|
||||
except AttributeError: # no cov
|
||||
workers = os.cpu_count() or 1
|
||||
|
||||
server_settings = self._helper(
|
||||
host=host,
|
||||
port=port,
|
||||
debug=debug,
|
||||
version=version,
|
||||
ssl=ssl,
|
||||
sock=sock,
|
||||
unix=unix,
|
||||
workers=workers,
|
||||
protocol=protocol,
|
||||
backlog=backlog,
|
||||
register_sys_signals=register_sys_signals,
|
||||
auto_tls=auto_tls,
|
||||
)
|
||||
self.state.server_info.append(
|
||||
ApplicationServerInfo(settings=server_settings)
|
||||
)
|
||||
|
||||
if self.config.USE_UVLOOP is True or (
|
||||
self.config.USE_UVLOOP is _default and not OS_IS_WINDOWS
|
||||
):
|
||||
try_use_uvloop()
|
||||
|
||||
async def create_server(
|
||||
self,
|
||||
host: Optional[str] = None,
|
||||
port: Optional[int] = None,
|
||||
*,
|
||||
debug: bool = False,
|
||||
ssl: Union[None, SSLContext, dict, str, list, tuple] = None,
|
||||
sock: Optional[socket] = None,
|
||||
protocol: Type[Protocol] = None,
|
||||
backlog: int = 100,
|
||||
access_log: Optional[bool] = None,
|
||||
unix: Optional[str] = None,
|
||||
return_asyncio_server: bool = False,
|
||||
asyncio_server_kwargs: Dict[str, Any] = None,
|
||||
noisy_exceptions: Optional[bool] = None,
|
||||
) -> Optional[AsyncioServer]:
|
||||
"""
|
||||
Asynchronous version of :func:`run`.
|
||||
|
||||
This method will take care of the operations necessary to invoke
|
||||
the *before_start* events via :func:`trigger_events` method invocation
|
||||
before starting the *sanic* app in Async mode.
|
||||
|
||||
.. note::
|
||||
This does not support multiprocessing and is not the preferred
|
||||
way to run a :class:`Sanic` application.
|
||||
|
||||
:param host: Address to host on
|
||||
:type host: str
|
||||
:param port: Port to host on
|
||||
:type port: int
|
||||
:param debug: Enables debug output (slows server)
|
||||
:type debug: bool
|
||||
:param ssl: SSLContext, or location of certificate and key
|
||||
for SSL encryption of worker(s)
|
||||
:type ssl: SSLContext or dict
|
||||
:param sock: Socket for the server to accept connections from
|
||||
:type sock: socket
|
||||
:param protocol: Subclass of asyncio Protocol class
|
||||
:type protocol: type[Protocol]
|
||||
:param backlog: a number of unaccepted connections that the system
|
||||
will allow before refusing new connections
|
||||
:type backlog: int
|
||||
:param access_log: Enables writing access logs (slows server)
|
||||
:type access_log: bool
|
||||
:param return_asyncio_server: flag that defines whether there's a need
|
||||
to return asyncio.Server or
|
||||
start it serving right away
|
||||
:type return_asyncio_server: bool
|
||||
:param asyncio_server_kwargs: key-value arguments for
|
||||
asyncio/uvloop create_server method
|
||||
:type asyncio_server_kwargs: dict
|
||||
:param noisy_exceptions: Log exceptions that are normally considered
|
||||
to be quiet/silent
|
||||
:type noisy_exceptions: bool
|
||||
:return: AsyncioServer if return_asyncio_server is true, else Nothing
|
||||
"""
|
||||
|
||||
if sock is None:
|
||||
host, port = host, port = self.get_address(host, port)
|
||||
|
||||
if protocol is None:
|
||||
protocol = (
|
||||
WebSocketProtocol if self.websocket_enabled else HttpProtocol
|
||||
)
|
||||
|
||||
# Set explicitly passed configuration values
|
||||
for attribute, value in {
|
||||
"ACCESS_LOG": access_log,
|
||||
"NOISY_EXCEPTIONS": noisy_exceptions,
|
||||
}.items():
|
||||
if value is not None:
|
||||
setattr(self.config, attribute, value)
|
||||
|
||||
server_settings = self._helper(
|
||||
host=host,
|
||||
port=port,
|
||||
debug=debug,
|
||||
ssl=ssl,
|
||||
sock=sock,
|
||||
unix=unix,
|
||||
loop=get_event_loop(),
|
||||
protocol=protocol,
|
||||
backlog=backlog,
|
||||
run_async=return_asyncio_server,
|
||||
)
|
||||
|
||||
if self.config.USE_UVLOOP is not _default:
|
||||
error_logger.warning(
|
||||
"You are trying to change the uvloop configuration, but "
|
||||
"this is only effective when using the run(...) method. "
|
||||
"When using the create_server(...) method Sanic will use "
|
||||
"the already existing loop."
|
||||
)
|
||||
|
||||
main_start = server_settings.pop("main_start", None)
|
||||
main_stop = server_settings.pop("main_stop", None)
|
||||
if main_start or main_stop:
|
||||
logger.warning(
|
||||
"Listener events for the main process are not available "
|
||||
"with create_server()"
|
||||
)
|
||||
|
||||
return await serve(
|
||||
asyncio_server_kwargs=asyncio_server_kwargs, **server_settings
|
||||
)
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
This kills the Sanic
|
||||
"""
|
||||
if self.state.stage is not ServerStage.STOPPED:
|
||||
self.shutdown_tasks(timeout=0)
|
||||
for task in all_tasks():
|
||||
with suppress(AttributeError):
|
||||
if task.get_name() == "RunServer":
|
||||
task.cancel()
|
||||
get_event_loop().stop()
|
||||
|
||||
def _helper(
|
||||
self,
|
||||
host: Optional[str] = None,
|
||||
port: Optional[int] = None,
|
||||
debug: bool = False,
|
||||
version: HTTPVersion = HTTP.VERSION_1,
|
||||
ssl: Union[None, SSLContext, dict, str, list, tuple] = None,
|
||||
sock: Optional[socket] = None,
|
||||
unix: Optional[str] = None,
|
||||
workers: int = 1,
|
||||
loop: AbstractEventLoop = None,
|
||||
protocol: Type[Protocol] = HttpProtocol,
|
||||
backlog: int = 100,
|
||||
register_sys_signals: bool = True,
|
||||
run_async: bool = False,
|
||||
auto_tls: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
"""Helper function used by `run` and `create_server`."""
|
||||
if self.config.PROXIES_COUNT and self.config.PROXIES_COUNT < 0:
|
||||
raise ValueError(
|
||||
"PROXIES_COUNT cannot be negative. "
|
||||
"https://sanic.readthedocs.io/en/latest/sanic/config.html"
|
||||
"#proxy-configuration"
|
||||
)
|
||||
|
||||
if not self.state.is_debug:
|
||||
self.state.mode = Mode.DEBUG if debug else Mode.PRODUCTION
|
||||
|
||||
if isinstance(version, int):
|
||||
version = HTTP(version)
|
||||
|
||||
ssl = process_to_context(ssl)
|
||||
if version is HTTP.VERSION_3 or auto_tls:
|
||||
if TYPE_CHECKING:
|
||||
self = cast(Sanic, self)
|
||||
ssl = get_ssl_context(self, ssl)
|
||||
|
||||
self.state.host = host or ""
|
||||
self.state.port = port or 0
|
||||
self.state.workers = workers
|
||||
self.state.ssl = ssl
|
||||
self.state.unix = unix
|
||||
self.state.sock = sock
|
||||
|
||||
server_settings = {
|
||||
"protocol": protocol,
|
||||
"host": host,
|
||||
"port": port,
|
||||
"version": version,
|
||||
"sock": sock,
|
||||
"unix": unix,
|
||||
"ssl": ssl,
|
||||
"app": self,
|
||||
"signal": ServerSignal(),
|
||||
"loop": loop,
|
||||
"register_sys_signals": register_sys_signals,
|
||||
"backlog": backlog,
|
||||
}
|
||||
|
||||
self.motd(server_settings=server_settings)
|
||||
|
||||
if is_atty() and not self.state.is_debug:
|
||||
error_logger.warning(
|
||||
f"{Colors.YELLOW}Sanic is running in PRODUCTION mode. "
|
||||
"Consider using '--debug' or '--dev' while actively "
|
||||
f"developing your application.{Colors.END}"
|
||||
)
|
||||
|
||||
# Register start/stop events
|
||||
for event_name, settings_name, reverse in (
|
||||
("main_process_start", "main_start", False),
|
||||
("main_process_stop", "main_stop", True),
|
||||
):
|
||||
listeners = self.listeners[event_name].copy()
|
||||
if reverse:
|
||||
listeners.reverse()
|
||||
# Prepend sanic to the arguments when listeners are triggered
|
||||
listeners = [partial(listener, self) for listener in listeners]
|
||||
server_settings[settings_name] = listeners # type: ignore
|
||||
|
||||
if run_async:
|
||||
server_settings["run_async"] = True
|
||||
|
||||
return server_settings
|
||||
|
||||
def motd(
|
||||
self,
|
||||
serve_location: str = "",
|
||||
server_settings: Optional[Dict[str, Any]] = None,
|
||||
):
|
||||
if serve_location:
|
||||
deprecation(
|
||||
"Specifying a serve_location in the MOTD is deprecated and "
|
||||
"will be removed.",
|
||||
22.9,
|
||||
)
|
||||
else:
|
||||
serve_location = self.get_server_location(server_settings)
|
||||
if self.config.MOTD:
|
||||
mode = [f"{self.state.mode},"]
|
||||
if self.state.fast:
|
||||
mode.append("goin' fast")
|
||||
if self.state.asgi:
|
||||
mode.append("ASGI")
|
||||
else:
|
||||
if self.state.workers == 1:
|
||||
mode.append("single worker")
|
||||
else:
|
||||
mode.append(f"w/ {self.state.workers} workers")
|
||||
|
||||
if server_settings:
|
||||
server = ", ".join(
|
||||
(
|
||||
self.state.server,
|
||||
server_settings["version"].display(), # type: ignore
|
||||
)
|
||||
)
|
||||
else:
|
||||
server = "ASGI" if self.asgi else "unknown" # type: ignore
|
||||
|
||||
display = {
|
||||
"mode": " ".join(mode),
|
||||
"server": server,
|
||||
"python": platform.python_version(),
|
||||
"platform": platform.platform(),
|
||||
}
|
||||
extra = {}
|
||||
if self.config.AUTO_RELOAD:
|
||||
reload_display = "enabled"
|
||||
if self.state.reload_dirs:
|
||||
reload_display += ", ".join(
|
||||
[
|
||||
"",
|
||||
*(
|
||||
str(path.absolute())
|
||||
for path in self.state.reload_dirs
|
||||
),
|
||||
]
|
||||
)
|
||||
display["auto-reload"] = reload_display
|
||||
|
||||
packages = []
|
||||
for package_name in SANIC_PACKAGES:
|
||||
module_name = package_name.replace("-", "_")
|
||||
try:
|
||||
module = import_module(module_name)
|
||||
packages.append(
|
||||
f"{package_name}=={module.__version__}" # type: ignore
|
||||
)
|
||||
except ImportError:
|
||||
...
|
||||
|
||||
if packages:
|
||||
display["packages"] = ", ".join(packages)
|
||||
|
||||
if self.config.MOTD_DISPLAY:
|
||||
extra.update(self.config.MOTD_DISPLAY)
|
||||
|
||||
logo = get_logo(coffee=self.state.coffee)
|
||||
|
||||
MOTD.output(logo, serve_location, display, extra)
|
||||
|
||||
@property
|
||||
def serve_location(self) -> str:
|
||||
try:
|
||||
server_settings = self.state.server_info[0].settings
|
||||
return self.get_server_location(server_settings)
|
||||
except IndexError:
|
||||
location = "ASGI" if self.asgi else "unknown" # type: ignore
|
||||
return f"http://<{location}>"
|
||||
|
||||
@staticmethod
|
||||
def get_server_location(
|
||||
server_settings: Optional[Dict[str, Any]] = None
|
||||
) -> str:
|
||||
serve_location = ""
|
||||
proto = "http"
|
||||
if not server_settings:
|
||||
return serve_location
|
||||
|
||||
if server_settings["ssl"] is not None:
|
||||
proto = "https"
|
||||
if server_settings["unix"]:
|
||||
serve_location = f'{server_settings["unix"]} {proto}://...'
|
||||
elif server_settings["sock"]:
|
||||
serve_location = (
|
||||
f'{server_settings["sock"].getsockname()} {proto}://...'
|
||||
)
|
||||
elif server_settings["host"] and server_settings["port"]:
|
||||
# colon(:) is legal for a host only in an ipv6 address
|
||||
display_host = (
|
||||
f'[{server_settings["host"]}]'
|
||||
if ":" in server_settings["host"]
|
||||
else server_settings["host"]
|
||||
)
|
||||
serve_location = (
|
||||
f'{proto}://{display_host}:{server_settings["port"]}'
|
||||
)
|
||||
|
||||
return serve_location
|
||||
|
||||
@staticmethod
|
||||
def get_address(
|
||||
host: Optional[str],
|
||||
port: Optional[int],
|
||||
version: HTTPVersion = HTTP.VERSION_1,
|
||||
auto_tls: bool = False,
|
||||
) -> Tuple[str, int]:
|
||||
host = host or "127.0.0.1"
|
||||
port = port or (8443 if (version == 3 or auto_tls) else 8000)
|
||||
return host, port
|
||||
|
||||
@classmethod
|
||||
def should_auto_reload(cls) -> bool:
|
||||
return any(app.state.auto_reload for app in cls._app_registry.values())
|
||||
|
||||
@classmethod
|
||||
def serve(cls, primary: Optional[Sanic] = None) -> None:
|
||||
apps = list(cls._app_registry.values())
|
||||
|
||||
if not primary:
|
||||
try:
|
||||
primary = apps[0]
|
||||
except IndexError:
|
||||
raise RuntimeError("Did not find any applications.")
|
||||
|
||||
reloader_start = primary.listeners.get("reload_process_start")
|
||||
reloader_stop = primary.listeners.get("reload_process_stop")
|
||||
# We want to run auto_reload if ANY of the applications have it enabled
|
||||
if (
|
||||
cls.should_auto_reload()
|
||||
and os.environ.get("SANIC_SERVER_RUNNING") != "true"
|
||||
): # no cov
|
||||
loop = new_event_loop()
|
||||
trigger_events(reloader_start, loop, primary)
|
||||
reload_dirs: Set[Path] = primary.state.reload_dirs.union(
|
||||
*(app.state.reload_dirs for app in apps)
|
||||
)
|
||||
reloader_helpers.watchdog(1.0, reload_dirs)
|
||||
trigger_events(reloader_stop, loop, primary)
|
||||
return
|
||||
|
||||
# This exists primarily for unit testing
|
||||
if not primary.state.server_info: # no cov
|
||||
for app in apps:
|
||||
app.state.server_info.clear()
|
||||
return
|
||||
|
||||
primary_server_info = primary.state.server_info[0]
|
||||
primary.before_server_start(partial(primary._start_servers, apps=apps))
|
||||
|
||||
try:
|
||||
primary_server_info.stage = ServerStage.SERVING
|
||||
|
||||
if primary.state.workers > 1 and os.name != "posix": # no cov
|
||||
logger.warn(
|
||||
f"Multiprocessing is currently not supported on {os.name},"
|
||||
" using workers=1 instead"
|
||||
)
|
||||
primary.state.workers = 1
|
||||
if primary.state.workers == 1:
|
||||
serve_single(primary_server_info.settings)
|
||||
elif primary.state.workers == 0:
|
||||
raise RuntimeError("Cannot serve with no workers")
|
||||
else:
|
||||
serve_multiple(
|
||||
primary_server_info.settings, primary.state.workers
|
||||
)
|
||||
except BaseException:
|
||||
error_logger.exception(
|
||||
"Experienced exception while trying to serve"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
primary_server_info.stage = ServerStage.STOPPED
|
||||
logger.info("Server Stopped")
|
||||
for app in apps:
|
||||
app.state.server_info.clear()
|
||||
app.router.reset()
|
||||
app.signal_router.reset()
|
||||
|
||||
async def _start_servers(
|
||||
self,
|
||||
primary: Sanic,
|
||||
_,
|
||||
apps: List[Sanic],
|
||||
) -> None:
|
||||
for app in apps:
|
||||
if (
|
||||
app.name is not primary.name
|
||||
and app.state.workers != primary.state.workers
|
||||
and app.state.server_info
|
||||
):
|
||||
message = (
|
||||
f"The primary application {repr(primary)} is running "
|
||||
f"with {primary.state.workers} worker(s). All "
|
||||
"application instances will run with the same number. "
|
||||
f"You requested {repr(app)} to run with "
|
||||
f"{app.state.workers} worker(s), which will be ignored "
|
||||
"in favor of the primary application."
|
||||
)
|
||||
if is_atty():
|
||||
message = "".join(
|
||||
[
|
||||
Colors.YELLOW,
|
||||
message,
|
||||
Colors.END,
|
||||
]
|
||||
)
|
||||
error_logger.warning(message, exc_info=True)
|
||||
for server_info in app.state.server_info:
|
||||
if server_info.stage is not ServerStage.SERVING:
|
||||
app.state.primary = False
|
||||
handlers = [
|
||||
*server_info.settings.pop("main_start", []),
|
||||
*server_info.settings.pop("main_stop", []),
|
||||
]
|
||||
if handlers:
|
||||
error_logger.warning(
|
||||
f"Sanic found {len(handlers)} listener(s) on "
|
||||
"secondary applications attached to the main "
|
||||
"process. These will be ignored since main "
|
||||
"process listeners can only be attached to your "
|
||||
"primary application: "
|
||||
f"{repr(primary)}"
|
||||
)
|
||||
|
||||
if not server_info.settings["loop"]:
|
||||
server_info.settings["loop"] = get_running_loop()
|
||||
|
||||
try:
|
||||
server_info.server = await serve(
|
||||
**server_info.settings,
|
||||
run_async=True,
|
||||
reuse_port=bool(primary.state.workers - 1),
|
||||
)
|
||||
except OSError as e: # no cov
|
||||
first_message = (
|
||||
"An OSError was detected on startup. "
|
||||
"The encountered error was: "
|
||||
)
|
||||
second_message = str(e)
|
||||
if is_atty():
|
||||
message_parts = [
|
||||
Colors.YELLOW,
|
||||
first_message,
|
||||
Colors.RED,
|
||||
second_message,
|
||||
Colors.END,
|
||||
]
|
||||
else:
|
||||
message_parts = [first_message, second_message]
|
||||
message = "".join(message_parts)
|
||||
error_logger.warning(message, exc_info=True)
|
||||
continue
|
||||
primary.add_task(
|
||||
self._run_server(app, server_info), name="RunServer"
|
||||
)
|
||||
|
||||
async def _run_server(
|
||||
self,
|
||||
app: RunnerMixin,
|
||||
server_info: ApplicationServerInfo,
|
||||
) -> None:
|
||||
|
||||
try:
|
||||
# We should never get to this point without a server
|
||||
# This is primarily to keep mypy happy
|
||||
if not server_info.server: # no cov
|
||||
raise RuntimeError("Could not locate AsyncioServer")
|
||||
if app.state.stage is ServerStage.STOPPED:
|
||||
server_info.stage = ServerStage.SERVING
|
||||
await server_info.server.startup()
|
||||
await server_info.server.before_start()
|
||||
await server_info.server.after_start()
|
||||
await server_info.server.serve_forever()
|
||||
except CancelledError:
|
||||
# We should never get to this point without a server
|
||||
# This is primarily to keep mypy happy
|
||||
if not server_info.server: # no cov
|
||||
raise RuntimeError("Could not locate AsyncioServer")
|
||||
await server_info.server.before_stop()
|
||||
await server_info.server.close()
|
||||
await server_info.server.after_stop()
|
||||
finally:
|
||||
server_info.stage = ServerStage.STOPPED
|
||||
server_info.server = None
|
||||
@@ -1,17 +1,14 @@
|
||||
from enum import Enum
|
||||
from typing import Any, Callable, Dict, Optional, Set, Union
|
||||
|
||||
from sanic.base.meta import SanicMeta
|
||||
from sanic.models.futures import FutureSignal
|
||||
from sanic.models.handler_types import SignalHandler
|
||||
from sanic.signals import Signal
|
||||
from sanic.types import HashableDict
|
||||
|
||||
|
||||
class HashableDict(dict):
|
||||
def __hash__(self):
|
||||
return hash(tuple(sorted(self.items())))
|
||||
|
||||
|
||||
class SignalMixin:
|
||||
class SignalMixin(metaclass=SanicMeta):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_signals: Set[FutureSignal] = set()
|
||||
|
||||
@@ -24,6 +21,7 @@ class SignalMixin:
|
||||
*,
|
||||
apply: bool = True,
|
||||
condition: Dict[str, Any] = None,
|
||||
exclusive: bool = True,
|
||||
) -> Callable[[SignalHandler], SignalHandler]:
|
||||
"""
|
||||
For creating a signal handler, used similar to a route handler:
|
||||
@@ -36,17 +34,22 @@ class SignalMixin:
|
||||
|
||||
:param event: Representation of the event in ``one.two.three`` form
|
||||
:type event: str
|
||||
:param apply: For lazy evaluation, defaults to True
|
||||
:param apply: For lazy evaluation, defaults to ``True``
|
||||
:type apply: bool, optional
|
||||
:param condition: For use with the ``condition`` argument in dispatch
|
||||
filtering, defaults to None
|
||||
filtering, defaults to ``None``
|
||||
:param exclusive: When ``True``, the signal can only be dispatched
|
||||
when the condition has been met. When ``False``, the signal can
|
||||
be dispatched either with or without it. *THIS IS INAPPLICABLE TO
|
||||
BLUEPRINT SIGNALS. THEY ARE ALWAYS NON-EXCLUSIVE*, defaults
|
||||
to ``True``
|
||||
:type condition: Dict[str, Any], optional
|
||||
"""
|
||||
event_value = str(event.value) if isinstance(event, Enum) else event
|
||||
|
||||
def decorator(handler: SignalHandler):
|
||||
future_signal = FutureSignal(
|
||||
handler, event_value, HashableDict(condition or {})
|
||||
handler, event_value, HashableDict(condition or {}), exclusive
|
||||
)
|
||||
self._future_signals.add(future_signal)
|
||||
|
||||
@@ -62,6 +65,7 @@ class SignalMixin:
|
||||
handler: Optional[Callable[..., Any]],
|
||||
event: str,
|
||||
condition: Dict[str, Any] = None,
|
||||
exclusive: bool = True,
|
||||
):
|
||||
if not handler:
|
||||
|
||||
@@ -69,7 +73,9 @@ class SignalMixin:
|
||||
...
|
||||
|
||||
handler = noop
|
||||
self.signal(event=event, condition=condition)(handler)
|
||||
self.signal(event=event, condition=condition, exclusive=exclusive)(
|
||||
handler
|
||||
)
|
||||
return handler
|
||||
|
||||
def event(self, event: str):
|
||||
|
||||
@@ -3,7 +3,8 @@ import sys
|
||||
|
||||
from typing import Any, Awaitable, Callable, MutableMapping, Optional, Union
|
||||
|
||||
from sanic.exceptions import InvalidUsage
|
||||
from sanic.exceptions import BadRequest
|
||||
from sanic.models.protocol_types import TransportProtocol
|
||||
from sanic.server.websockets.connection import WebSocketConnection
|
||||
|
||||
|
||||
@@ -13,7 +14,7 @@ ASGISend = Callable[[ASGIMessage], Awaitable[None]]
|
||||
ASGIReceive = Callable[[], Awaitable[ASGIMessage]]
|
||||
|
||||
|
||||
class MockProtocol:
|
||||
class MockProtocol: # no cov
|
||||
def __init__(self, transport: "MockTransport", loop):
|
||||
# This should be refactored when < 3.8 support is dropped
|
||||
self.transport = transport
|
||||
@@ -56,7 +57,7 @@ class MockProtocol:
|
||||
await self._not_paused.wait()
|
||||
|
||||
|
||||
class MockTransport:
|
||||
class MockTransport(TransportProtocol): # no cov
|
||||
_protocol: Optional[MockProtocol]
|
||||
|
||||
def __init__(
|
||||
@@ -68,23 +69,25 @@ class MockTransport:
|
||||
self._protocol = None
|
||||
self.loop = None
|
||||
|
||||
def get_protocol(self) -> MockProtocol:
|
||||
def get_protocol(self) -> MockProtocol: # type: ignore
|
||||
if not self._protocol:
|
||||
self._protocol = MockProtocol(self, self.loop)
|
||||
return self._protocol
|
||||
|
||||
def get_extra_info(self, info: str) -> Union[str, bool, None]:
|
||||
def get_extra_info(
|
||||
self, info: str, default=None
|
||||
) -> Optional[Union[str, bool]]:
|
||||
if info == "peername":
|
||||
return self.scope.get("client")
|
||||
elif info == "sslcontext":
|
||||
return self.scope.get("scheme") in ["https", "wss"]
|
||||
return None
|
||||
return default
|
||||
|
||||
def get_websocket_connection(self) -> WebSocketConnection:
|
||||
try:
|
||||
return self._websocket_connection
|
||||
except AttributeError:
|
||||
raise InvalidUsage("Improper websocket connection.")
|
||||
raise BadRequest("Improper websocket connection.")
|
||||
|
||||
def create_websocket_connection(
|
||||
self, send: ASGISend, receive: ASGIReceive
|
||||
|
||||
@@ -7,6 +7,7 @@ from sanic.models.handler_types import (
|
||||
MiddlewareType,
|
||||
SignalHandler,
|
||||
)
|
||||
from sanic.types import HashableDict
|
||||
|
||||
|
||||
class FutureRoute(NamedTuple):
|
||||
@@ -25,6 +26,7 @@ class FutureRoute(NamedTuple):
|
||||
static: bool
|
||||
version_prefix: str
|
||||
error_format: Optional[str]
|
||||
route_context: HashableDict
|
||||
|
||||
|
||||
class FutureListener(NamedTuple):
|
||||
@@ -60,6 +62,7 @@ class FutureSignal(NamedTuple):
|
||||
handler: SignalHandler
|
||||
event: str
|
||||
condition: Optional[Dict[str, str]]
|
||||
exclusive: bool
|
||||
|
||||
|
||||
class FutureRegistry(set):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user