Compare commits
300 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7be5f0ed3d | ||
|
|
938d2b5923 | ||
|
|
13630a79ad | ||
|
|
2586989eb7 | ||
|
|
6763e2bb0a | ||
|
|
15a8b5c894 | ||
|
|
8a2ea626c6 | ||
|
|
01f238de79 | ||
|
|
7bed5a5c3c | ||
|
|
2fea954dcf | ||
|
|
d4660d0ca7 | ||
|
|
824f41d6e0 | ||
|
|
1165663ec1 | ||
|
|
b1a57a8b62 | ||
|
|
d76925cf35 | ||
|
|
400f54c7ec | ||
|
|
ec7e4390e8 | ||
|
|
5ca8bb85cd | ||
|
|
5c624f8b76 | ||
|
|
2c25af8cf5 | ||
|
|
be905e0009 | ||
|
|
0d2d62eae5 | ||
|
|
00a1ee0cb6 | ||
|
|
f0d44822bc | ||
|
|
e771e4e019 | ||
|
|
82e5f57edd | ||
|
|
93a697f6ea | ||
|
|
a733d32715 | ||
|
|
c41d7136e8 | ||
|
|
bb65dda277 | ||
|
|
e1e9a7cf20 | ||
|
|
27f64ddae2 | ||
|
|
4b968dc611 | ||
|
|
170177feb0 | ||
|
|
eef44ae179 | ||
|
|
161efc67a3 | ||
|
|
dbfc11f4c5 | ||
|
|
e5ea4f5019 | ||
|
|
62d0b05309 | ||
|
|
aae8f13d9a | ||
|
|
eac900d363 | ||
|
|
cd0c3d3eea | ||
|
|
b461cc338c | ||
|
|
7c34b57e92 | ||
|
|
c35a53fe24 | ||
|
|
055c78b475 | ||
|
|
a9a52ef1e9 | ||
|
|
a760989354 | ||
|
|
dee95fd1c0 | ||
|
|
9c48c7d39b | ||
|
|
fc5e3b4ede | ||
|
|
baf96275bf | ||
|
|
3a45d3291b | ||
|
|
c7307c1f85 | ||
|
|
dec46d5c4a | ||
|
|
93313e6385 | ||
|
|
070236677c | ||
|
|
6b86921c7a | ||
|
|
8f3e076661 | ||
|
|
37f0a51063 | ||
|
|
d6343c367f | ||
|
|
bad9fd0258 | ||
|
|
d402d0362e | ||
|
|
209579f280 | ||
|
|
9e23e75fb4 | ||
|
|
8f8c00a99d | ||
|
|
bb5501f4c4 | ||
|
|
d3cbcf0e46 | ||
|
|
15502182e3 | ||
|
|
375319038f | ||
|
|
4c29846cb1 | ||
|
|
c942a5c51c | ||
|
|
a913e712a7 | ||
|
|
7f63ad5484 | ||
|
|
a498c29ec9 | ||
|
|
973c315790 | ||
|
|
aea2e4e7f4 | ||
|
|
55a5ab4be1 | ||
|
|
5377a6eee3 | ||
|
|
6057da71f3 | ||
|
|
e91b3d40a2 | ||
|
|
b89f9a57e0 | ||
|
|
b850e49cb3 | ||
|
|
6b68c3702e | ||
|
|
5f17e9591b | ||
|
|
64f0496d9e | ||
|
|
0d5b2a0f69 | ||
|
|
c08b153cee | ||
|
|
a434ffa8b7 | ||
|
|
967c4e6a4e | ||
|
|
3f1e9ff528 | ||
|
|
96cc49e31e | ||
|
|
94e5f82a81 | ||
|
|
ffca01ffff | ||
|
|
0165c9c644 | ||
|
|
7b47a4bebc | ||
|
|
a46ea4fc59 | ||
|
|
4358a7eefd | ||
|
|
b958cdc151 | ||
|
|
afb527b37c | ||
|
|
65b76f2762 | ||
|
|
e54685d34d | ||
|
|
6009e6d35d | ||
|
|
d5f09dd9d8 | ||
|
|
ffae6f56c5 | ||
|
|
838563c751 | ||
|
|
83705b91c2 | ||
|
|
5abeae8f46 | ||
|
|
693f2a5014 | ||
|
|
5545264cea | ||
|
|
e04f206c50 | ||
|
|
e9459792a4 | ||
|
|
dadf76ce72 | ||
|
|
33d7f4da6b | ||
|
|
5f79291b55 | ||
|
|
792a72bdf4 | ||
|
|
c32e7fd678 | ||
|
|
76ef641743 | ||
|
|
1f0f4ef5d5 | ||
|
|
933d005e5d | ||
|
|
f8f215772c | ||
|
|
a0066e5752 | ||
|
|
976a4c764d | ||
|
|
0d7e2f0d67 | ||
|
|
6c03dd87b1 | ||
|
|
0c252e7904 | ||
|
|
8f4e0ad3c8 | ||
|
|
95b5260b27 | ||
|
|
2f48e81e0b | ||
|
|
7028eae083 | ||
|
|
574a9c27a6 | ||
|
|
f9414f89f3 | ||
|
|
fcdbeb7bd4 | ||
|
|
206992fe40 | ||
|
|
31337ba92a | ||
|
|
150d75b7c6 | ||
|
|
7475897a03 | ||
|
|
449bc417a3 | ||
|
|
262f89f2b6 | ||
|
|
38337446cf | ||
|
|
ac1331ea4c | ||
|
|
2b947e831f | ||
|
|
112715eb80 | ||
|
|
ea9cf365bc | ||
|
|
b9b3b4051a | ||
|
|
ecb6db29e6 | ||
|
|
6515dde64b | ||
|
|
01d2a2aa3c | ||
|
|
39e12accb8 | ||
|
|
39fe6ea5b1 | ||
|
|
fc4b7df088 | ||
|
|
35f28f7a64 | ||
|
|
614be40438 | ||
|
|
bde0428d0c | ||
|
|
63567c2ae4 | ||
|
|
ec10f337b6 | ||
|
|
d0f0e73e96 | ||
|
|
b4fe2c8a6b | ||
|
|
33da0771d1 | ||
|
|
75994cd915 | ||
|
|
c0839afdde | ||
|
|
5961da3f57 | ||
|
|
41f1809351 | ||
|
|
5fbdcb62e4 | ||
|
|
677b83e9f8 | ||
|
|
6a5c8becac | ||
|
|
fd23b99d60 | ||
|
|
634b586df3 | ||
|
|
4ca3e98082 | ||
|
|
d18a776964 | ||
|
|
d6b4d7d265 | ||
|
|
33ee4c21b3 | ||
|
|
a026cd7195 | ||
|
|
7b1bce8d90 | ||
|
|
217a7c5161 | ||
|
|
2949e3422d | ||
|
|
16ea99b0c0 | ||
|
|
19b84ce9f0 | ||
|
|
e5aed4c067 | ||
|
|
9e048bc0c3 | ||
|
|
5d7b0735ce | ||
|
|
12521cd5b4 | ||
|
|
7dbd3eb5e8 | ||
|
|
96364aacc0 | ||
|
|
fc18f86964 | ||
|
|
fb3d368a78 | ||
|
|
f41435fae3 | ||
|
|
5928c50057 | ||
|
|
1de4bcef55 | ||
|
|
7b7559309d | ||
|
|
066df2c142 | ||
|
|
0c4a9b1dce | ||
|
|
65a7060d3b | ||
|
|
3483e7b061 | ||
|
|
13094e02bc | ||
|
|
ed777e9d5b | ||
|
|
8ad80a282a | ||
|
|
0b7eb49839 | ||
|
|
de3b40c2e6 | ||
|
|
efa0aaf2c2 | ||
|
|
bd4e1cdc1e | ||
|
|
eb8df1fc18 | ||
|
|
9a8e49751d | ||
|
|
58e15134fd | ||
|
|
875be11ae5 | ||
|
|
3f7c9ea3f5 | ||
|
|
33aa4daac8 | ||
|
|
58e4087d4b | ||
|
|
0072fd1573 | ||
|
|
5d5ed10a45 | ||
|
|
5ee8ee7b04 | ||
|
|
521ae7f60e | ||
|
|
27c8c12420 | ||
|
|
3d1f100781 | ||
|
|
16d36fc17f | ||
|
|
eddb5bad91 | ||
|
|
23e1b5ee3f | ||
|
|
9e053bef19 | ||
|
|
cf234fca15 | ||
|
|
050a563e1d | ||
|
|
c347ff742e | ||
|
|
db1c819fe1 | ||
|
|
9f2818ee29 | ||
|
|
26aa6d23c7 | ||
|
|
ec7e894eb3 | ||
|
|
71a08382d6 | ||
|
|
09224f8676 | ||
|
|
008b8ac394 | ||
|
|
a357add14e | ||
|
|
0cfd7b528b | ||
|
|
9ba4fe05df | ||
|
|
35786b4b74 | ||
|
|
c7430d805a | ||
|
|
8a3fbb555f | ||
|
|
a62c84a954 | ||
|
|
4aba74d050 | ||
|
|
ab2cb88cf4 | ||
|
|
e79ec7d7e0 | ||
|
|
ccdb74a9a7 | ||
|
|
7b96d633db | ||
|
|
938c49b899 | ||
|
|
761eef7d96 | ||
|
|
83511a0ba7 | ||
|
|
cf9ccdae47 | ||
|
|
d81096fdc0 | ||
|
|
6c8e20a859 | ||
|
|
6239fa4f56 | ||
|
|
1b324ae981 | ||
|
|
bedf68a9b2 | ||
|
|
496e87e4ba | ||
|
|
fa4f85eb32 | ||
|
|
1b1dfedc74 | ||
|
|
230941ff4f | ||
|
|
4658e0f2f3 | ||
|
|
7c3c532dae | ||
|
|
7c04c9a227 | ||
|
|
44973125c1 | ||
|
|
6aaccd1e8b | ||
|
|
e7001b0074 | ||
|
|
aacbd022cf | ||
|
|
ae1874ce34 | ||
|
|
8abba597a8 | ||
|
|
9987893963 | ||
|
|
638322d905 | ||
|
|
ae40f960ff | ||
|
|
d969fdc19f | ||
|
|
710024125e | ||
|
|
9a39aff803 | ||
|
|
78e912ea45 | ||
|
|
aa6ea5b5a0 | ||
|
|
48800e657f | ||
|
|
120f0262f7 | ||
|
|
4db075ffc1 | ||
|
|
60b4efad67 | ||
|
|
319388d78b | ||
|
|
ce71514d71 | ||
|
|
7833d70d9e | ||
|
|
16961fab9d | ||
|
|
861e87347a | ||
|
|
91f6abaa81 | ||
|
|
d380b52f9a | ||
|
|
d656a06a19 | ||
|
|
258dbee3b9 | ||
|
|
6b9287b076 | ||
|
|
dac0514441 | ||
|
|
bffdb3b5c2 | ||
|
|
e908ca8cef | ||
|
|
801595e24a | ||
|
|
ba9b432993 | ||
|
|
b565072ed9 | ||
|
|
caa1b4d69b | ||
|
|
865536c5c4 | ||
|
|
784d5cce52 | ||
|
|
0fd08c6114 | ||
|
|
cd779b6e4f | ||
|
|
3430907046 | ||
|
|
2f776eba85 | ||
|
|
b9cd2ed1f1 | ||
|
|
3411a12c40 | ||
|
|
28899356c8 |
@@ -12,6 +12,17 @@ environment:
|
||||
PYTHON_VERSION: "3.7.x"
|
||||
PYTHON_ARCH: "64"
|
||||
|
||||
- TOXENV: py38-no-ext
|
||||
PYTHON: "C:\\Python38-x64"
|
||||
PYTHON_VERSION: "3.8.x"
|
||||
PYTHON_ARCH: "64"
|
||||
|
||||
# - TOXENV: py39-no-ext
|
||||
# PYTHON: "C:\\Python39-x64\\python"
|
||||
# PYTHONPATH: "C:\\Python39-x64"
|
||||
# PYTHON_VERSION: "3.9.x"
|
||||
# PYTHON_ARCH: "64"
|
||||
|
||||
init: SET "PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
|
||||
|
||||
install:
|
||||
|
||||
3
.github/CODEOWNERS
vendored
Normal file
3
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
* @sanic-org/sanic-release-managers
|
||||
/sanic/ @sanic-org/framework
|
||||
/tests/ @sanic-org/framework
|
||||
12
.github/FUNDING.yml
vendored
Normal file
12
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: sanic-org # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Questions and Help
|
||||
url: https://community.sanicframework.org/c/questions-and-help
|
||||
about: Do you need help with Sanic? Ask your questions here.
|
||||
13
.github/ISSUE_TEMPLATE/help-wanted.md
vendored
13
.github/ISSUE_TEMPLATE/help-wanted.md
vendored
@@ -1,13 +0,0 @@
|
||||
---
|
||||
name: Help wanted
|
||||
about: Do you need help? Try community.sanicframework.org
|
||||
|
||||
---
|
||||
|
||||
*DELETE ALL BEFORE POSTING*
|
||||
*Post your HELP WANTED questions on [the community forum](https://community.sanicframework.org/)*.
|
||||
|
||||
Checkout the community forum before posting any question here.
|
||||
We prefer if you put these kinds of questions here:
|
||||
|
||||
https://community.sanicframework.org/c/questions-and-help
|
||||
67
.github/workflows/codeql-analysis.yml
vendored
Normal file
67
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ master ]
|
||||
schedule:
|
||||
- cron: '25 16 * * 0'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'python' ]
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||
# Learn more:
|
||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
||||
64
.travis.yml
64
.travis.yml
@@ -5,12 +5,6 @@ cache:
|
||||
- $HOME/.cache/pip
|
||||
matrix:
|
||||
include:
|
||||
- env: TOX_ENV=py36
|
||||
python: 3.6
|
||||
name: "Python 3.6 with Extensions"
|
||||
- env: TOX_ENV=py36-no-ext
|
||||
python: 3.6
|
||||
name: "Python 3.6 without Extensions"
|
||||
- env: TOX_ENV=py37
|
||||
python: 3.7
|
||||
dist: xenial
|
||||
@@ -21,41 +15,69 @@ matrix:
|
||||
dist: xenial
|
||||
sudo: true
|
||||
name: "Python 3.7 without Extensions"
|
||||
- env: TOX_ENV=type-checking
|
||||
python: 3.6
|
||||
name: "Python 3.6 Type checks"
|
||||
- env: TOX_ENV=py38
|
||||
python: 3.8
|
||||
dist: xenial
|
||||
sudo: true
|
||||
name: "Python 3.8 with Extensions"
|
||||
- env: TOX_ENV=py38-no-ext
|
||||
python: 3.8
|
||||
dist: xenial
|
||||
sudo: true
|
||||
name: "Python 3.8 without Extensions"
|
||||
- env: TOX_ENV=py39
|
||||
python: 3.9
|
||||
dist: bionic
|
||||
sudo: true
|
||||
name: "Python 3.9 with Extensions"
|
||||
- env: TOX_ENV=py39-no-ext
|
||||
python: 3.9
|
||||
dist: bionic
|
||||
sudo: true
|
||||
name: "Python 3.9 without Extensions"
|
||||
- env: TOX_ENV=type-checking
|
||||
python: 3.7
|
||||
name: "Python 3.7 Type checks"
|
||||
- env: TOX_ENV=lint
|
||||
python: 3.6
|
||||
name: "Python 3.6 Linter checks"
|
||||
- env: TOX_ENV=check
|
||||
python: 3.6
|
||||
name: "Python 3.6 Package checks"
|
||||
- env: TOX_ENV=type-checking
|
||||
python: 3.8
|
||||
name: "Python 3.8 Type checks"
|
||||
- env: TOX_ENV=type-checking
|
||||
python: 3.9
|
||||
dist: bionic
|
||||
name: "Python 3.9 Type checks"
|
||||
- env: TOX_ENV=security
|
||||
python: 3.7
|
||||
dist: xenial
|
||||
sudo: true
|
||||
name: "Python 3.7 Bandit security scan"
|
||||
- env: TOX_ENV=security
|
||||
python: 3.8
|
||||
dist: xenial
|
||||
sudo: true
|
||||
name: "Python 3.8 Bandit security scan"
|
||||
- env: TOX_ENV=security
|
||||
python: 3.9
|
||||
dist: bionic
|
||||
sudo: true
|
||||
name: "Python 3.9 Bandit security scan"
|
||||
- env: TOX_ENV=docs
|
||||
python: 3.7
|
||||
dist: xenial
|
||||
sudo: true
|
||||
name: "Python 3.7 Documentation tests"
|
||||
- env: TOX_ENV=pyNightly
|
||||
python: 'nightly'
|
||||
python: "nightly"
|
||||
name: "Python nightly with Extensions"
|
||||
- env: TOX_ENV=pyNightly-no-ext
|
||||
python: 'nightly'
|
||||
name: "Python nightly Extensions"
|
||||
python: "nightly"
|
||||
name: "Python nightly without Extensions"
|
||||
allow_failures:
|
||||
- env: TOX_ENV=pyNightly
|
||||
python: 'nightly'
|
||||
python: "nightly"
|
||||
name: "Python nightly with Extensions"
|
||||
- env: TOX_ENV=pyNightly-no-ext
|
||||
python: 'nightly'
|
||||
name: "Python nightly Extensions"
|
||||
python: "nightly"
|
||||
name: "Python nightly without Extensions"
|
||||
install:
|
||||
- pip install -U tox
|
||||
- pip install codecov
|
||||
|
||||
794
CHANGELOG.rst
794
CHANGELOG.rst
@@ -1,5 +1,675 @@
|
||||
Version 21.3.1
|
||||
--------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
* `#2076 <https://github.com/sanic-org/sanic/pull/2076>`_
|
||||
Static files inside subfolders are not accessible (404)
|
||||
|
||||
Version 21.3.0
|
||||
--------------
|
||||
|
||||
`Release Notes <https://sanicframework.org/en/guide/release-notes/v21.3.html>`_
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1876 <https://github.com/sanic-org/sanic/pull/1876>`_
|
||||
Unified streaming server
|
||||
|
||||
*
|
||||
`#2005 <https://github.com/sanic-org/sanic/pull/2005>`_
|
||||
New ``Request.id`` property
|
||||
|
||||
*
|
||||
`#2008 <https://github.com/sanic-org/sanic/pull/2008>`_
|
||||
Allow Pathlib Path objects to be passed to ``app.static()`` helper
|
||||
|
||||
*
|
||||
`#2010 <https://github.com/sanic-org/sanic/pull/2010>`_, `#2031 <https://github.com/sanic-org/sanic/pull/2031>`_
|
||||
New startup-optimized router
|
||||
|
||||
*
|
||||
`#2018 <https://github.com/sanic-org/sanic/pull/2018>`_
|
||||
`#2064 <https://github.com/sanic-org/sanic/pull/2064>`_
|
||||
Listeners for main server process
|
||||
|
||||
*
|
||||
`#2032 <https://github.com/sanic-org/sanic/pull/2032>`_
|
||||
Add raw header info to request object
|
||||
|
||||
*
|
||||
`#2042 <https://github.com/sanic-org/sanic/pull/2042>`_
|
||||
`#2060 <https://github.com/sanic-org/sanic/pull/2060>`_
|
||||
`#2061 <https://github.com/sanic-org/sanic/pull/2061>`_
|
||||
Introduce Signals API
|
||||
|
||||
*
|
||||
`#2043 <https://github.com/sanic-org/sanic/pull/2043>`_
|
||||
Add ``__str__`` and ``__repr__`` to Sanic and Blueprint
|
||||
|
||||
*
|
||||
`#2047 <https://github.com/sanic-org/sanic/pull/2047>`_
|
||||
Enable versioning and strict slash on BlueprintGroup
|
||||
|
||||
*
|
||||
`#2053 <https://github.com/sanic-org/sanic/pull/2053>`_
|
||||
Make ``get_app`` name argument optional
|
||||
|
||||
*
|
||||
`#2055 <https://github.com/sanic-org/sanic/pull/2055>`_
|
||||
JSON encoder change via app
|
||||
|
||||
*
|
||||
`#2063 <https://github.com/sanic-org/sanic/pull/2063>`_
|
||||
App and connection level context objects
|
||||
|
||||
Bugfixes and issues resolved
|
||||
****************************
|
||||
|
||||
* Resolve `#1420 <https://github.com/sanic-org/sanic/pull/1420>`_
|
||||
``url_for`` where ``strict_slashes`` are on for a path ending in ``/``
|
||||
* Resolve `#1525 <https://github.com/sanic-org/sanic/pull/1525>`_
|
||||
Routing is incorrect with some special characters
|
||||
* Resolve `#1653 <https://github.com/sanic-org/sanic/pull/1653>`_
|
||||
ASGI headers in body
|
||||
* Resolve `#1722 <https://github.com/sanic-org/sanic/pull/1722>`_
|
||||
Using curl in chunk mode
|
||||
* Resolve `#1730 <https://github.com/sanic-org/sanic/pull/1730>`_
|
||||
Extra content in ASGI streaming response
|
||||
* Resolve `#1749 <https://github.com/sanic-org/sanic/pull/1749>`_
|
||||
Restore broken middleware edge cases
|
||||
* Resolve `#1785 <https://github.com/sanic-org/sanic/pull/1785>`_
|
||||
`#1804 <https://github.com/sanic-org/sanic/pull/1804>`_
|
||||
Synchronous error handlers
|
||||
* Resolve `#1790 <https://github.com/sanic-org/sanic/pull/1790>`_
|
||||
Protocol errors did not support async error handlers #1790
|
||||
* Resolve `#1824 <https://github.com/sanic-org/sanic/pull/1824>`_
|
||||
Timeout on specific methods
|
||||
* Resolve `#1875 <https://github.com/sanic-org/sanic/pull/1875>`_
|
||||
Response timeout error from all routes after returning several timeouts from a specific route
|
||||
* Resolve `#1988 <https://github.com/sanic-org/sanic/pull/1988>`_
|
||||
Handling of safe methods with body
|
||||
|
||||
*
|
||||
`#2001 <https://github.com/sanic-org/sanic/pull/2001>`_
|
||||
Raise ValueError when cookie max-age is not an integer
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
|
||||
*
|
||||
`#2007 <https://github.com/sanic-org/sanic/pull/2007>`_
|
||||
* Config using ``from_envvar``
|
||||
* Config using ``from_pyfile``
|
||||
* Config using ``from_object``
|
||||
*
|
||||
`#2009 <https://github.com/sanic-org/sanic/pull/2009>`_
|
||||
Remove Sanic test client to its own package
|
||||
|
||||
*
|
||||
`#2036 <https://github.com/sanic-org/sanic/pull/2036>`_,
|
||||
`#2037 <https://github.com/sanic-org/sanic/pull/2037>`_
|
||||
Drop Python 3.6 support
|
||||
|
||||
* ``Request.endpoint`` deprecated in favor of ``Request.name``
|
||||
* handler type name prefixes removed (static, websocket, etc)
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
|
||||
*
|
||||
`#1995 <https://github.com/sanic-org/sanic/pull/1995>`_
|
||||
Create FUNDING.yml
|
||||
|
||||
*
|
||||
`#2013 <https://github.com/sanic-org/sanic/pull/2013>`_
|
||||
Add codeql to CI pipeline
|
||||
|
||||
*
|
||||
`#2038 <https://github.com/sanic-org/sanic/pull/2038>`_
|
||||
Codecov configuration updates
|
||||
|
||||
*
|
||||
`#2049 <https://github.com/sanic-org/sanic/pull/2049>`_
|
||||
Updated setup.py to use ``find_packages``
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
|
||||
*
|
||||
`#1218 <https://github.com/sanic-org/sanic/pull/1218>`_
|
||||
Documentation for sanic.log.* is missing
|
||||
|
||||
*
|
||||
`#1608 <https://github.com/sanic-org/sanic/pull/1608>`_
|
||||
Add documentation on calver and LTS
|
||||
|
||||
*
|
||||
`#1731 <https://github.com/sanic-org/sanic/pull/1731>`_
|
||||
Support mounting application elsewhere than at root path
|
||||
|
||||
*
|
||||
`#2006 <https://github.com/sanic-org/sanic/pull/2006>`_
|
||||
Upgraded type annotations and improved docstrings and API documentation
|
||||
|
||||
*
|
||||
`#2052 <https://github.com/sanic-org/sanic/pull/2052>`_
|
||||
Fix some examples and docs
|
||||
|
||||
Miscellaneous
|
||||
*************
|
||||
|
||||
* ``Request.route`` property
|
||||
* Better websocket subprotocols support
|
||||
* Resolve bug with middleware in Blueprint Group when passed callable
|
||||
* Moves common logic between Blueprint and Sanic into mixins
|
||||
* Route naming changed to be more consistent
|
||||
* request endpoint is the route name
|
||||
* route names are fully namespaced
|
||||
* Some new convenience decorators:
|
||||
* ``@app.main_process_start``
|
||||
* ``@app.main_process_stop``
|
||||
* ``@app.before_server_start``
|
||||
* ``@app.after_server_start``
|
||||
* ``@app.before_server_stop``
|
||||
* ``@app.after_server_stop``
|
||||
* ``@app.on_request``
|
||||
* ``@app.on_response``
|
||||
* Fixes ``Allow`` header that did not include ``HEAD``
|
||||
* Using "name" keyword in ``url_for`` for a "static" route where name does not exist
|
||||
* Cannot have multiple ``app.static()`` without using the named param
|
||||
* Using "filename" keyword in ``url_for`` on a file route
|
||||
* ``unquote`` in route def (not automatic)
|
||||
* ``routes_all`` is tuples
|
||||
* Handler arguments are kwarg only
|
||||
* ``request.match_info`` is now a cached (and not computed) property
|
||||
* Unknown static file mimetype is sent as ``application/octet-stream``
|
||||
* ``_host`` keyword in ``url_for``
|
||||
* Add charset default to ``utf-8`` for text and js content types if not specified
|
||||
* Version for a route can be str, float, or int
|
||||
* Route has ctx property
|
||||
* App has ``routes_static``, ``routes_dynamic``, ``routes_regex``
|
||||
|
||||
*
|
||||
`#2044 <https://github.com/sanic-org/sanic/pull/2044>`_
|
||||
Code cleanup and refactoring
|
||||
*
|
||||
`#2072 <https://github.com/sanic-org/sanic/pull/2072>`_
|
||||
Remove ``BaseSanic`` metaclass
|
||||
*
|
||||
`#2074 <https://github.com/sanic-org/sanic/pull/2074>`_
|
||||
Performance adjustments in ``handle_request_``
|
||||
|
||||
Version 20.12.3
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#2021 <https://github.com/sanic-org/sanic/pull/2021>`_
|
||||
Remove prefix from websocket handler name
|
||||
|
||||
Version 20.12.2
|
||||
---------------
|
||||
|
||||
Dependencies
|
||||
************
|
||||
|
||||
*
|
||||
`#2026 <https://github.com/sanic-org/sanic/pull/2026>`_
|
||||
Fix uvloop to 0.14 because 0.15 drops Python 3.6 support
|
||||
|
||||
*
|
||||
`#2029 <https://github.com/sanic-org/sanic/pull/2029>`_
|
||||
Remove old chardet requirement, add in hard multidict requirement
|
||||
|
||||
Version 19.12.5
|
||||
---------------
|
||||
|
||||
Dependencies
|
||||
************
|
||||
|
||||
*
|
||||
`#2025 <https://github.com/sanic-org/sanic/pull/2025>`_
|
||||
Fix uvloop to 0.14 because 0.15 drops Python 3.6 support
|
||||
|
||||
*
|
||||
`#2027 <https://github.com/sanic-org/sanic/pull/2027>`_
|
||||
Remove old chardet requirement, add in hard multidict requirement
|
||||
|
||||
Version 20.12.0
|
||||
---------------
|
||||
|
||||
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
|
||||
|
||||
*
|
||||
`#1954 <https://github.com/sanic-org/sanic/pull/1954>`_
|
||||
Fix static routes registration on a blueprint
|
||||
|
||||
*
|
||||
`#1961 <https://github.com/sanic-org/sanic/pull/1961>`_
|
||||
Add Python 3.9 support
|
||||
|
||||
*
|
||||
`#1962 <https://github.com/sanic-org/sanic/pull/1962>`_
|
||||
Sanic CLI upgrade
|
||||
|
||||
*
|
||||
`#1967 <https://github.com/sanic-org/sanic/pull/1967>`_
|
||||
Update aiofile version requirements
|
||||
|
||||
*
|
||||
`#1969 <https://github.com/sanic-org/sanic/pull/1969>`_
|
||||
Update multidict version requirements
|
||||
|
||||
*
|
||||
`#1970 <https://github.com/sanic-org/sanic/pull/1970>`_
|
||||
Add py.typed file
|
||||
|
||||
*
|
||||
`#1972 <https://github.com/sanic-org/sanic/pull/1972>`_
|
||||
Speed optimization in request handler
|
||||
|
||||
*
|
||||
`#1979 <https://github.com/sanic-org/sanic/pull/1979>`_
|
||||
Add app registry and Sanic class level app retrieval
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1965 <https://github.com/sanic-org/sanic/pull/1965>`_
|
||||
Fix Chunked Transport-Encoding in ASGI streaming response
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
|
||||
*
|
||||
`#1981 <https://github.com/sanic-org/sanic/pull/1981>`_
|
||||
Cleanup and remove deprecated code
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
|
||||
*
|
||||
`#1956 <https://github.com/sanic-org/sanic/pull/1956>`_
|
||||
Fix load module test
|
||||
|
||||
*
|
||||
`#1973 <https://github.com/sanic-org/sanic/pull/1973>`_
|
||||
Transition Travis from .org to .com
|
||||
|
||||
*
|
||||
`#1986 <https://github.com/sanic-org/sanic/pull/1986>`_
|
||||
Update tox requirements
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
|
||||
*
|
||||
`#1951 <https://github.com/sanic-org/sanic/pull/1951>`_
|
||||
Documentation improvements
|
||||
|
||||
*
|
||||
`#1983 <https://github.com/sanic-org/sanic/pull/1983>`_
|
||||
Remove duplicate contents in testing.rst
|
||||
|
||||
*
|
||||
`#1984 <https://github.com/sanic-org/sanic/pull/1984>`_
|
||||
Fix typo in routing.rst
|
||||
|
||||
|
||||
Version 20.9.1
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1954 <https://github.com/sanic-org/sanic/pull/1954>`_
|
||||
Fix static route registration on blueprints
|
||||
*
|
||||
`#1957 <https://github.com/sanic-org/sanic/pull/1957>`_
|
||||
Removes duplicate headers in ASGI streaming body
|
||||
|
||||
|
||||
Version 19.12.3
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1959 <https://github.com/sanic-org/sanic/pull/1959>`_
|
||||
Removes duplicate headers in ASGI streaming body
|
||||
|
||||
|
||||
Version 20.9.0
|
||||
---------------
|
||||
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1887 <https://github.com/sanic-org/sanic/pull/1887>`_
|
||||
Pass subprotocols in websockets (both sanic server and ASGI)
|
||||
|
||||
*
|
||||
`#1894 <https://github.com/sanic-org/sanic/pull/1894>`_
|
||||
Automatically set ``test_mode`` flag on app instance
|
||||
|
||||
*
|
||||
`#1903 <https://github.com/sanic-org/sanic/pull/1903>`_
|
||||
Add new unified method for updating app values
|
||||
|
||||
*
|
||||
`#1906 <https://github.com/sanic-org/sanic/pull/1906>`_,
|
||||
`#1909 <https://github.com/sanic-org/sanic/pull/1909>`_
|
||||
Adds WEBSOCKET_PING_TIMEOUT and WEBSOCKET_PING_INTERVAL configuration values
|
||||
|
||||
*
|
||||
`#1935 <https://github.com/sanic-org/sanic/pull/1935>`_
|
||||
httpx version dependency updated, it is slated for removal as a dependency in v20.12
|
||||
|
||||
*
|
||||
`#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
|
||||
********
|
||||
|
||||
*
|
||||
`#1897 <https://github.com/sanic-org/sanic/pull/1897>`_
|
||||
Resolves exception from unread bytes in stream
|
||||
|
||||
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
|
||||
************************
|
||||
|
||||
*
|
||||
`#1890 <https://github.com/sanic-org/sanic/pull/1890>`_,
|
||||
`#1891 <https://github.com/sanic-org/sanic/pull/1891>`_
|
||||
Update isort calls to be compatible with new API
|
||||
|
||||
*
|
||||
`#1893 <https://github.com/sanic-org/sanic/pull/1893>`_
|
||||
Remove version section from setup.cfg
|
||||
|
||||
*
|
||||
`#1924 <https://github.com/sanic-org/sanic/pull/1924>`_
|
||||
Adding --strict-markers for pytest
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
|
||||
*
|
||||
`#1922 <https://github.com/sanic-org/sanic/pull/1922>`_
|
||||
Add explicit ASGI compliance to the README
|
||||
|
||||
|
||||
Version 20.6.3
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1884 <https://github.com/sanic-org/sanic/pull/1884>`_
|
||||
Revert change to multiprocessing mode
|
||||
|
||||
|
||||
Version 20.6.2
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1641 <https://github.com/sanic-org/sanic/pull/1641>`_
|
||||
Socket binding implemented properly for IPv6 and UNIX sockets
|
||||
|
||||
|
||||
Version 20.6.1
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1760 <https://github.com/sanic-org/sanic/pull/1760>`_
|
||||
Add version parameter to websocket routes
|
||||
|
||||
*
|
||||
`#1866 <https://github.com/sanic-org/sanic/pull/1866>`_
|
||||
Add ``sanic`` as an entry point command
|
||||
|
||||
*
|
||||
`#1880 <https://github.com/sanic-org/sanic/pull/1880>`_
|
||||
Add handler names for websockets for url_for usage
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1776 <https://github.com/sanic-org/sanic/pull/1776>`_
|
||||
Bug fix for host parameter issue with lists
|
||||
|
||||
*
|
||||
`#1842 <https://github.com/sanic-org/sanic/pull/1842>`_
|
||||
Fix static _handler pickling error
|
||||
|
||||
*
|
||||
`#1827 <https://github.com/sanic-org/sanic/pull/1827>`_
|
||||
Fix reloader on OSX py38 and Windows
|
||||
|
||||
*
|
||||
`#1848 <https://github.com/sanic-org/sanic/pull/1848>`_
|
||||
Reverse named_response_middlware execution order, to match normal response middleware execution order
|
||||
|
||||
*
|
||||
`#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
|
||||
*************************
|
||||
|
||||
*
|
||||
`#1739 <https://github.com/sanic-org/sanic/pull/1739>`_
|
||||
Deprecate body_bytes to merge into body
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
|
||||
*
|
||||
`#1852 <https://github.com/sanic-org/sanic/pull/1852>`_
|
||||
Fix naming of CI test env on Python nightlies
|
||||
|
||||
*
|
||||
`#1857 <https://github.com/sanic-org/sanic/pull/1857>`_
|
||||
Adjust websockets version to setup.py
|
||||
|
||||
*
|
||||
`#1869 <https://github.com/sanic-org/sanic/pull/1869>`_
|
||||
Wrap run()'s "protocol" type annotation in Optional[]
|
||||
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
|
||||
*
|
||||
`#1846 <https://github.com/sanic-org/sanic/pull/1846>`_
|
||||
Update docs to clarify response middleware execution order
|
||||
|
||||
*
|
||||
`#1865 <https://github.com/sanic-org/sanic/pull/1865>`_
|
||||
Fixing rst format issue that was hiding documentation
|
||||
|
||||
|
||||
Version 20.6.0
|
||||
---------------
|
||||
|
||||
*Released, but unintentionally ommitting PR #1880, so was replaced by 20.6.1*
|
||||
|
||||
|
||||
Version 20.3.0
|
||||
---------------
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1762 <https://github.com/sanic-org/sanic/pull/1762>`_
|
||||
Add ``srv.start_serving()`` and ``srv.serve_forever()`` to ``AsyncioServer``
|
||||
|
||||
*
|
||||
`#1767 <https://github.com/sanic-org/sanic/pull/1767>`_
|
||||
Make Sanic usable on ``hypercorn -k trio myweb.app``
|
||||
|
||||
*
|
||||
`#1768 <https://github.com/sanic-org/sanic/pull/1768>`_
|
||||
No tracebacks on normal errors and prettier error pages
|
||||
|
||||
*
|
||||
`#1769 <https://github.com/sanic-org/sanic/pull/1769>`_
|
||||
Code cleanup in file responses
|
||||
|
||||
*
|
||||
`#1793 <https://github.com/sanic-org/sanic/pull/1793>`_ and
|
||||
`#1819 <https://github.com/sanic-org/sanic/pull/1819>`_
|
||||
Upgrade ``str.format()`` to f-strings
|
||||
|
||||
*
|
||||
`#1798 <https://github.com/sanic-org/sanic/pull/1798>`_
|
||||
Allow multiple workers on MacOS with Python 3.8
|
||||
|
||||
*
|
||||
`#1820 <https://github.com/sanic-org/sanic/pull/1820>`_
|
||||
Do not set content-type and content-length headers in exceptions
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1748 <https://github.com/sanic-org/sanic/pull/1748>`_
|
||||
Remove loop argument in ``asyncio.Event`` in Python 3.8
|
||||
|
||||
*
|
||||
`#1764 <https://github.com/sanic-org/sanic/pull/1764>`_
|
||||
Allow route decorators to stack up again
|
||||
|
||||
*
|
||||
`#1789 <https://github.com/sanic-org/sanic/pull/1789>`_
|
||||
Fix tests using hosts yielding incorrect ``url_for``
|
||||
|
||||
*
|
||||
`#1808 <https://github.com/sanic-org/sanic/pull/1808>`_
|
||||
Fix Ctrl+C and tests on Windows
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
|
||||
*
|
||||
`#1800 <https://github.com/sanic-org/sanic/pull/1800>`_
|
||||
Begin deprecation in way of first-class streaming, removal of ``body_init``, ``body_push``, and ``body_finish``
|
||||
|
||||
*
|
||||
`#1801 <https://github.com/sanic-org/sanic/pull/1801>`_
|
||||
Complete deprecation from `#1666 <https://github.com/sanic-org/sanic/pull/1666>`_ of dictionary context on ``request`` objects.
|
||||
|
||||
*
|
||||
`#1807 <https://github.com/sanic-org/sanic/pull/1807>`_
|
||||
Remove server config args that can be read directly from app
|
||||
|
||||
*
|
||||
`#1818 <https://github.com/sanic-org/sanic/pull/1818>`_
|
||||
Complete deprecation of ``app.remove_route`` and ``request.raw_args``
|
||||
|
||||
Dependencies
|
||||
************
|
||||
|
||||
*
|
||||
`#1794 <https://github.com/sanic-org/sanic/pull/1794>`_
|
||||
Bump ``httpx`` to 0.11.1
|
||||
|
||||
*
|
||||
`#1806 <https://github.com/sanic-org/sanic/pull/1806>`_
|
||||
Import ``ASGIDispatch`` from top-level ``httpx`` (from third-party deprecation)
|
||||
|
||||
Developer infrastructure
|
||||
************************
|
||||
|
||||
*
|
||||
`#1833 <https://github.com/sanic-org/sanic/pull/1833>`_
|
||||
Resolve broken documentation builds
|
||||
|
||||
Improved Documentation
|
||||
**********************
|
||||
|
||||
*
|
||||
`#1755 <https://github.com/sanic-org/sanic/pull/1755>`_
|
||||
Usage of ``response.empty()``
|
||||
|
||||
*
|
||||
`#1778 <https://github.com/sanic-org/sanic/pull/1778>`_
|
||||
Update README
|
||||
|
||||
*
|
||||
`#1783 <https://github.com/sanic-org/sanic/pull/1783>`_
|
||||
Fix typo
|
||||
|
||||
*
|
||||
`#1784 <https://github.com/sanic-org/sanic/pull/1784>`_
|
||||
Corrected changelog for docs move of MD to RST (`#1691 <https://github.com/sanic-org/sanic/pull/1691>`_)
|
||||
|
||||
*
|
||||
`#1803 <https://github.com/sanic-org/sanic/pull/1803>`_
|
||||
Update config docs to match DEFAULT_CONFIG
|
||||
|
||||
*
|
||||
`#1814 <https://github.com/sanic-org/sanic/pull/1814>`_
|
||||
Update getting_started.rst
|
||||
|
||||
*
|
||||
`#1821 <https://github.com/sanic-org/sanic/pull/1821>`_
|
||||
Update to deployment
|
||||
|
||||
*
|
||||
`#1822 <https://github.com/sanic-org/sanic/pull/1822>`_
|
||||
Update docs with changes done in 20.3
|
||||
|
||||
*
|
||||
`#1834 <https://github.com/sanic-org/sanic/pull/1834>`_
|
||||
Order of listeners
|
||||
|
||||
|
||||
Version 19.12.0
|
||||
===============
|
||||
---------------
|
||||
|
||||
Bugfixes
|
||||
********
|
||||
@@ -14,27 +684,27 @@ Bugfixes
|
||||
|
||||
- If you register a middleware via :code:`@blueprint.middleware` then it will apply only to the routes defined by the blueprint.
|
||||
- If you register a middleware via :code:`@blueprint_group.middleware` then it will apply to all blueprint based routes that are part of the group.
|
||||
- If you define a middleware via :code:`@app.middleware` then it will be applied on all available routes (`#37 <https://github.com/huge-success/sanic/issues/37>`__)
|
||||
- If you define a middleware via :code:`@app.middleware` then it will be applied on all available routes (`#37 <https://github.com/sanic-org/sanic/issues/37>`__)
|
||||
- Fix `url_for` behavior with missing SERVER_NAME
|
||||
|
||||
If the `SERVER_NAME` was missing in the `app.config` entity, the `url_for` on the `request` and `app` were failing
|
||||
due to an `AttributeError`. This fix makes the availability of `SERVER_NAME` on our `app.config` an optional behavior. (`#1707 <https://github.com/huge-success/sanic/issues/1707>`__)
|
||||
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
|
||||
**********************
|
||||
|
||||
- Move docs from RST to MD
|
||||
- Move docs from MD to RST
|
||||
|
||||
Moved all docs from markdown to restructured text like the rest of the docs to unify the scheme and make it easier in
|
||||
the future to update documentation. (`#1691 <https://github.com/huge-success/sanic/issues/1691>`__)
|
||||
the future to update documentation. (`#1691 <https://github.com/sanic-org/sanic/issues/1691>`__)
|
||||
- Fix documentation for `get` and `getlist` of the `request.args`
|
||||
|
||||
Add additional example for showing the usage of `getlist` and fix the documentation string for `request.args` behavior (`#1704 <https://github.com/huge-success/sanic/issues/1704>`__)
|
||||
Add additional example for showing the usage of `getlist` and fix the documentation string for `request.args` behavior (`#1704 <https://github.com/sanic-org/sanic/issues/1704>`__)
|
||||
|
||||
|
||||
Version 19.6.3
|
||||
==============
|
||||
--------------
|
||||
|
||||
Features
|
||||
********
|
||||
@@ -42,7 +712,7 @@ Features
|
||||
- Enable Towncrier Support
|
||||
|
||||
As part of this feature, `towncrier` is being introduced as a mechanism to partially automate the process
|
||||
of generating and managing change logs as part of each of pull requests. (`#1631 <https://github.com/huge-success/sanic/issues/1631>`__)
|
||||
of generating and managing change logs as part of each of pull requests. (`#1631 <https://github.com/sanic-org/sanic/issues/1631>`__)
|
||||
|
||||
|
||||
Improved Documentation
|
||||
@@ -53,26 +723,26 @@ Improved Documentation
|
||||
- Enable having a single common `CHANGELOG` file for both GitHub page and documentation
|
||||
- Fix Sphinix deprecation warnings
|
||||
- Fix documentation warnings due to invalid `rst` indentation
|
||||
- Enable common contribution guidelines file across GitHub and documentation via `CONTRIBUTING.rst` (`#1631 <https://github.com/huge-success/sanic/issues/1631>`__)
|
||||
- Enable common contribution guidelines file across GitHub and documentation via `CONTRIBUTING.rst` (`#1631 <https://github.com/sanic-org/sanic/issues/1631>`__)
|
||||
|
||||
|
||||
Version 19.6.2
|
||||
==============
|
||||
--------------
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1562 <https://github.com/huge-success/sanic/pull/1562>`_
|
||||
Remove ``aiohttp`` dependencey and create new ``SanicTestClient`` based upon
|
||||
`#1562 <https://github.com/sanic-org/sanic/pull/1562>`_
|
||||
Remove ``aiohttp`` dependency and create new ``SanicTestClient`` based upon
|
||||
`requests-async <https://github.com/encode/requests-async>`_
|
||||
|
||||
*
|
||||
`#1475 <https://github.com/huge-success/sanic/pull/1475>`_
|
||||
`#1475 <https://github.com/sanic-org/sanic/pull/1475>`_
|
||||
Added ASGI support (Beta)
|
||||
|
||||
*
|
||||
`#1436 <https://github.com/huge-success/sanic/pull/1436>`_
|
||||
`#1436 <https://github.com/sanic-org/sanic/pull/1436>`_
|
||||
Add Configure support from object string
|
||||
|
||||
|
||||
@@ -80,34 +750,34 @@ Bugfixes
|
||||
********
|
||||
|
||||
*
|
||||
`#1587 <https://github.com/huge-success/sanic/pull/1587>`_
|
||||
`#1587 <https://github.com/sanic-org/sanic/pull/1587>`_
|
||||
Add missing handle for Expect header.
|
||||
|
||||
*
|
||||
`#1560 <https://github.com/huge-success/sanic/pull/1560>`_
|
||||
`#1560 <https://github.com/sanic-org/sanic/pull/1560>`_
|
||||
Allow to disable Transfer-Encoding: chunked.
|
||||
|
||||
*
|
||||
`#1558 <https://github.com/huge-success/sanic/pull/1558>`_
|
||||
`#1558 <https://github.com/sanic-org/sanic/pull/1558>`_
|
||||
Fix graceful shutdown.
|
||||
|
||||
*
|
||||
`#1594 <https://github.com/huge-success/sanic/pull/1594>`_
|
||||
`#1594 <https://github.com/sanic-org/sanic/pull/1594>`_
|
||||
Strict Slashes behavior fix
|
||||
|
||||
Deprecations and Removals
|
||||
*************************
|
||||
|
||||
*
|
||||
`#1544 <https://github.com/huge-success/sanic/pull/1544>`_
|
||||
`#1544 <https://github.com/sanic-org/sanic/pull/1544>`_
|
||||
Drop dependency on distutil
|
||||
|
||||
*
|
||||
`#1562 <https://github.com/huge-success/sanic/pull/1562>`_
|
||||
`#1562 <https://github.com/sanic-org/sanic/pull/1562>`_
|
||||
Drop support for Python 3.5
|
||||
|
||||
*
|
||||
`#1568 <https://github.com/huge-success/sanic/pull/1568>`_
|
||||
`#1568 <https://github.com/sanic-org/sanic/pull/1568>`_
|
||||
Deprecate route removal.
|
||||
|
||||
.. warning::
|
||||
@@ -118,45 +788,45 @@ Deprecations and Removals
|
||||
|
||||
|
||||
Version 19.3
|
||||
============
|
||||
------------
|
||||
|
||||
Features
|
||||
********
|
||||
|
||||
*
|
||||
`#1497 <https://github.com/huge-success/sanic/pull/1497>`_
|
||||
`#1497 <https://github.com/sanic-org/sanic/pull/1497>`_
|
||||
Add support for zero-length and RFC 5987 encoded filename for
|
||||
multipart/form-data requests.
|
||||
|
||||
*
|
||||
`#1484 <https://github.com/huge-success/sanic/pull/1484>`_
|
||||
`#1484 <https://github.com/sanic-org/sanic/pull/1484>`_
|
||||
The type of ``expires`` attribute of ``sanic.cookies.Cookie`` is now
|
||||
enforced to be of type ``datetime``.
|
||||
|
||||
*
|
||||
`#1482 <https://github.com/huge-success/sanic/pull/1482>`_
|
||||
`#1482 <https://github.com/sanic-org/sanic/pull/1482>`_
|
||||
Add support for the ``stream`` parameter of ``sanic.Sanic.add_route()``
|
||||
available to ``sanic.Blueprint.add_route()``.
|
||||
|
||||
*
|
||||
`#1481 <https://github.com/huge-success/sanic/pull/1481>`_
|
||||
`#1481 <https://github.com/sanic-org/sanic/pull/1481>`_
|
||||
Accept negative values for route parameters with type ``int`` or ``number``.
|
||||
|
||||
*
|
||||
`#1476 <https://github.com/huge-success/sanic/pull/1476>`_
|
||||
`#1476 <https://github.com/sanic-org/sanic/pull/1476>`_
|
||||
Deprecated the use of ``sanic.request.Request.raw_args`` - it has a
|
||||
fundamental flaw in which is drops repeated query string parameters.
|
||||
Added ``sanic.request.Request.query_args`` as a replacement for the
|
||||
original use-case.
|
||||
|
||||
*
|
||||
`#1472 <https://github.com/huge-success/sanic/pull/1472>`_
|
||||
`#1472 <https://github.com/sanic-org/sanic/pull/1472>`_
|
||||
Remove an unwanted ``None`` check in Request class ``repr`` implementation.
|
||||
This changes the default ``repr`` of a Request from ``<Request>`` to
|
||||
``<Request: None />``
|
||||
|
||||
*
|
||||
`#1470 <https://github.com/huge-success/sanic/pull/1470>`_
|
||||
`#1470 <https://github.com/sanic-org/sanic/pull/1470>`_
|
||||
Added 2 new parameters to ``sanic.app.Sanic.create_server``\ :
|
||||
|
||||
|
||||
@@ -167,21 +837,21 @@ Features
|
||||
This is a breaking change.
|
||||
|
||||
*
|
||||
`#1499 <https://github.com/huge-success/sanic/pull/1499>`_
|
||||
`#1499 <https://github.com/sanic-org/sanic/pull/1499>`_
|
||||
Added a set of test cases that test and benchmark route resolution.
|
||||
|
||||
*
|
||||
`#1457 <https://github.com/huge-success/sanic/pull/1457>`_
|
||||
`#1457 <https://github.com/sanic-org/sanic/pull/1457>`_
|
||||
The type of the ``"max-age"`` value in a ``sanic.cookies.Cookie`` is now
|
||||
enforced to be an integer. Non-integer values are replaced with ``0``.
|
||||
|
||||
*
|
||||
`#1445 <https://github.com/huge-success/sanic/pull/1445>`_
|
||||
`#1445 <https://github.com/sanic-org/sanic/pull/1445>`_
|
||||
Added the ``endpoint`` attribute to an incoming ``request``\ , containing the
|
||||
name of the handler function.
|
||||
|
||||
*
|
||||
`#1423 <https://github.com/huge-success/sanic/pull/1423>`_
|
||||
`#1423 <https://github.com/sanic-org/sanic/pull/1423>`_
|
||||
Improved request streaming. ``request.stream`` is now a bounded-size buffer
|
||||
instead of an unbounded queue. Callers must now call
|
||||
``await request.stream.read()`` instead of ``await request.stream.get()``
|
||||
@@ -194,33 +864,33 @@ Bugfixes
|
||||
|
||||
|
||||
*
|
||||
`#1502 <https://github.com/huge-success/sanic/pull/1502>`_
|
||||
`#1502 <https://github.com/sanic-org/sanic/pull/1502>`_
|
||||
Sanic was prefetching ``time.time()`` and updating it once per second to
|
||||
avoid excessive ``time.time()`` calls. The implementation was observed to
|
||||
cause memory leaks in some cases. The benefit of the prefetch appeared
|
||||
to negligible, so this has been removed. Fixes
|
||||
`#1500 <https://github.com/huge-success/sanic/pull/1500>`_
|
||||
`#1500 <https://github.com/sanic-org/sanic/pull/1500>`_
|
||||
|
||||
*
|
||||
`#1501 <https://github.com/huge-success/sanic/pull/1501>`_
|
||||
`#1501 <https://github.com/sanic-org/sanic/pull/1501>`_
|
||||
Fix a bug in the auto-reloader when the process was launched as a module
|
||||
i.e. ``python -m init0.mod1`` where the sanic server is started
|
||||
in ``init0/mod1.py`` with ``debug`` enabled and imports another module in
|
||||
``init0``.
|
||||
|
||||
*
|
||||
`#1376 <https://github.com/huge-success/sanic/pull/1376>`_
|
||||
`#1376 <https://github.com/sanic-org/sanic/pull/1376>`_
|
||||
Allow sanic test client to bind to a random port by specifying
|
||||
``port=None`` when constructing a ``SanicTestClient``
|
||||
|
||||
*
|
||||
`#1399 <https://github.com/huge-success/sanic/pull/1399>`_
|
||||
`#1399 <https://github.com/sanic-org/sanic/pull/1399>`_
|
||||
Added the ability to specify middleware on a blueprint group, so that all
|
||||
routes produced from the blueprints in the group have the middleware
|
||||
applied.
|
||||
|
||||
*
|
||||
`#1442 <https://github.com/huge-success/sanic/pull/1442>`_
|
||||
`#1442 <https://github.com/sanic-org/sanic/pull/1442>`_
|
||||
Allow the the use the ``SANIC_ACCESS_LOG`` environment variable to
|
||||
enable/disable the access log when not explicitly passed to ``app.run()``.
|
||||
This allows the access log to be disabled for example when running via
|
||||
@@ -229,34 +899,34 @@ Bugfixes
|
||||
Developer infrastructure
|
||||
************************
|
||||
|
||||
* `#1529 <https://github.com/huge-success/sanic/pull/1529>`_ Update project PyPI credentials
|
||||
* `#1515 <https://github.com/huge-success/sanic/pull/1515>`_ fix linter issue causing travis build failures (fix #1514)
|
||||
* `#1490 <https://github.com/huge-success/sanic/pull/1490>`_ Fix python version in doc build
|
||||
* `#1478 <https://github.com/huge-success/sanic/pull/1478>`_ Upgrade setuptools version and use native docutils in doc build
|
||||
* `#1464 <https://github.com/huge-success/sanic/pull/1464>`_ Upgrade pytest, and fix caplog unit tests
|
||||
* `#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)
|
||||
* `#1490 <https://github.com/sanic-org/sanic/pull/1490>`_ Fix python version in doc build
|
||||
* `#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
|
||||
**********************
|
||||
|
||||
* `#1516 <https://github.com/huge-success/sanic/pull/1516>`_ Fix typo at the exception documentation
|
||||
* `#1510 <https://github.com/huge-success/sanic/pull/1510>`_ fix typo in Asyncio example
|
||||
* `#1486 <https://github.com/huge-success/sanic/pull/1486>`_ Documentation typo
|
||||
* `#1477 <https://github.com/huge-success/sanic/pull/1477>`_ Fix grammar in README.md
|
||||
* `#1489 <https://github.com/huge-success/sanic/pull/1489>`_ Added "databases" to the extensions list
|
||||
* `#1483 <https://github.com/huge-success/sanic/pull/1483>`_ Add sanic-zipkin to extensions list
|
||||
* `#1487 <https://github.com/huge-success/sanic/pull/1487>`_ Removed link to deleted repo, Sanic-OAuth, from the extensions list
|
||||
* `#1460 <https://github.com/huge-success/sanic/pull/1460>`_ 18.12 changelog
|
||||
* `#1449 <https://github.com/huge-success/sanic/pull/1449>`_ Add example of amending request object
|
||||
* `#1446 <https://github.com/huge-success/sanic/pull/1446>`_ Update README
|
||||
* `#1444 <https://github.com/huge-success/sanic/pull/1444>`_ Update README
|
||||
* `#1443 <https://github.com/huge-success/sanic/pull/1443>`_ Update README, including new logo
|
||||
* `#1440 <https://github.com/huge-success/sanic/pull/1440>`_ fix minor type and pip install instruction mismatch
|
||||
* `#1424 <https://github.com/huge-success/sanic/pull/1424>`_ Documentation Enhancements
|
||||
* `#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
|
||||
* `#1486 <https://github.com/sanic-org/sanic/pull/1486>`_ Documentation typo
|
||||
* `#1477 <https://github.com/sanic-org/sanic/pull/1477>`_ Fix grammar in README.md
|
||||
* `#1489 <https://github.com/sanic-org/sanic/pull/1489>`_ Added "databases" to the extensions list
|
||||
* `#1483 <https://github.com/sanic-org/sanic/pull/1483>`_ Add sanic-zipkin to extensions list
|
||||
* `#1487 <https://github.com/sanic-org/sanic/pull/1487>`_ Removed link to deleted repo, Sanic-OAuth, from the extensions list
|
||||
* `#1460 <https://github.com/sanic-org/sanic/pull/1460>`_ 18.12 changelog
|
||||
* `#1449 <https://github.com/sanic-org/sanic/pull/1449>`_ Add example of amending request object
|
||||
* `#1446 <https://github.com/sanic-org/sanic/pull/1446>`_ Update README
|
||||
* `#1444 <https://github.com/sanic-org/sanic/pull/1444>`_ Update README
|
||||
* `#1443 <https://github.com/sanic-org/sanic/pull/1443>`_ Update README, including new logo
|
||||
* `#1440 <https://github.com/sanic-org/sanic/pull/1440>`_ fix minor type and pip install instruction mismatch
|
||||
* `#1424 <https://github.com/sanic-org/sanic/pull/1424>`_ Documentation Enhancements
|
||||
|
||||
Note: 19.3.0 was skipped for packagement purposes and not released on PyPI
|
||||
|
||||
Version 18.12
|
||||
=============
|
||||
-------------
|
||||
|
||||
18.12.0
|
||||
*******
|
||||
@@ -301,14 +971,14 @@ Version 18.12
|
||||
* Fix document for logging
|
||||
|
||||
Version 0.8
|
||||
===========
|
||||
-----------
|
||||
|
||||
0.8.3
|
||||
*****
|
||||
|
||||
* Changes:
|
||||
|
||||
* Ownership changed to org 'huge-success'
|
||||
* Ownership changed to org 'sanic-org'
|
||||
|
||||
0.8.0
|
||||
*****
|
||||
@@ -388,7 +1058,7 @@ Version 0.8
|
||||
Note: Changelog was unmaintained between 0.1 and 0.7
|
||||
|
||||
Version 0.1
|
||||
===========
|
||||
-----------
|
||||
|
||||
|
||||
0.1.7
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
|
||||
Contributing
|
||||
============
|
||||
|
||||
Thank you for your interest! Sanic is always looking for contributors. If you
|
||||
don't feel comfortable contributing code, adding docstrings to the source files
|
||||
is very appreciated.
|
||||
don't feel comfortable contributing code, adding docstrings to the source files,
|
||||
or helping with the `Sanic User Guide <https://github.com/sanic-org/sanic-guide>`_
|
||||
by providing documentation or implementation examples would be appreciated!
|
||||
|
||||
We are committed to providing a friendly, safe and welcoming environment for all,
|
||||
regardless of gender, sexual orientation, disability, ethnicity, religion,
|
||||
or similar personal characteristic.
|
||||
Our `code of conduct <./CONDUCT.md>`_ sets the standards for behavior.
|
||||
Our `code of conduct <https://github.com/sanic-org/sanic/blob/master/CONDUCT.md>`_ sets the standards for behavior.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
To develop on sanic (and mainly to just run the tests) it is highly recommend to
|
||||
To develop on Sanic (and mainly to just run the tests) it is highly recommend to
|
||||
install from sources.
|
||||
|
||||
So assume you have already cloned the repo and are in the working directory with
|
||||
@@ -89,6 +86,17 @@ Permform ``flake8``\ , ``black`` and ``isort`` checks.
|
||||
|
||||
tox -e lint
|
||||
|
||||
Run type annotation checks
|
||||
---------------
|
||||
|
||||
``tox`` environment -> ``[testenv:type-checking]``
|
||||
|
||||
Permform ``mypy`` checks.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
tox -e type-checking
|
||||
|
||||
Run other checks
|
||||
----------------
|
||||
|
||||
@@ -161,6 +169,12 @@ flake8
|
||||
|
||||
``isort``\ , ``black`` and ``flake8`` checks are performed during ``tox`` lint checks.
|
||||
|
||||
The **easiest** way to make your code conform is to run the following before committing.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
make pretty
|
||||
|
||||
Refer `tox <https://tox.readthedocs.io/en/latest/index.html>`_ documentation for more details.
|
||||
|
||||
Pull requests
|
||||
@@ -168,12 +182,13 @@ Pull requests
|
||||
|
||||
So the pull request approval rules are pretty simple:
|
||||
|
||||
#. All pull requests must have a changelog details associated with it.
|
||||
#. All pull requests must pass unit tests.
|
||||
#. All pull requests must be reviewed and approved by at least one current collaborator on the project.
|
||||
#. All pull requests must be reviewed and approved by at least one current member of the Core Developer team.
|
||||
#. All pull requests must pass flake8 checks.
|
||||
#. All pull requests must match ``isort`` and ``black`` requirements.
|
||||
#. All pull requests must be **PROPERLY** type annotated, unless exemption is given.
|
||||
#. All pull requests must be consistent with the existing code.
|
||||
#. If you decide to remove/change anything from any common interface a deprecation message should accompany it.
|
||||
#. If you decide to remove/change anything from any common interface a deprecation message should accompany it in accordance with our `deprecation policy <https://sanicframework.org/en/guide/project/policies.html#deprecation>`_.
|
||||
#. If you implement a new feature you should have at least one unit test to accompany it.
|
||||
#. An example must be one of the following:
|
||||
|
||||
@@ -182,56 +197,14 @@ So the pull request approval rules are pretty simple:
|
||||
* Example of how to use Sanic and asynchronous library
|
||||
|
||||
|
||||
Changelog
|
||||
---------
|
||||
|
||||
It is mandatory to add documentation for Change log as part of your Pull request when you fix/contribute something
|
||||
to the ``sanic`` community. This will enable us in generating better and well defined change logs during the
|
||||
release which can aid community users in a great way.
|
||||
|
||||
.. note::
|
||||
|
||||
Single line explaining the details of the PR in brief
|
||||
|
||||
Detailed description of what the PR is about and what changes or enhancements are being done.
|
||||
No need to include examples or any other details here. But it is important that you provide
|
||||
enough context here to let user understand what this change is all about and why it is being
|
||||
introduced into the ``sanic`` codebase.
|
||||
|
||||
Make sure you leave an line space after the first line to make sure the document rendering is clean
|
||||
|
||||
|
||||
.. list-table::
|
||||
:header-rows: 1
|
||||
|
||||
* - Contribution Type
|
||||
- Changelog file name format
|
||||
- Changelog file location
|
||||
* - Features
|
||||
- <git_issue>.feature.rst
|
||||
- ``changelogs``
|
||||
* - Bugfixes
|
||||
- <git_issue>.bugfix.rst
|
||||
- ``changelogs``
|
||||
* - Improved Documentation
|
||||
- <git_issue>.doc.rst
|
||||
- ``changelogs``
|
||||
* - Deprecations and Removals
|
||||
- <git_issue>.removal.rst
|
||||
- ``changelogs``
|
||||
* - Miscellaneous internal changes
|
||||
- <git_issue>.misc.rst
|
||||
- ``changelogs``
|
||||
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
|
||||
Sanic's documentation is built
|
||||
using `sphinx <http://www.sphinx-doc.org/en/1.5.1/>`_. Guides are written in
|
||||
Markdown and can be found in the ``docs`` folder, while the module reference is
|
||||
Sanic's API documentation is built using `sphinx <http://www.sphinx-doc.org/en/1.5.1/>`_ with module references
|
||||
automatically generated using ``sphinx-apidoc``.
|
||||
|
||||
The User Guide is in the `sanic-guide <https://github.com/sanic-org/sanic-guide>`_ repository.
|
||||
|
||||
To generate the documentation from scratch:
|
||||
|
||||
.. code-block:: bash
|
||||
@@ -245,6 +218,14 @@ To generate the documentation from scratch:
|
||||
|
||||
The HTML documentation will be created in the ``docs/_build`` folder.
|
||||
|
||||
You can run the following to have a live development server with the API documents
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
make docs-serve
|
||||
|
||||
Refer to the User Guide repo for documentation on how to contribute there.
|
||||
|
||||
.. warning::
|
||||
One of the main goals of Sanic is speed. Code that lowers the performance of
|
||||
Sanic without significant gains in usability, security, or features may not be
|
||||
|
||||
11
Makefile
11
Makefile
@@ -63,16 +63,17 @@ ifdef include_tests
|
||||
isort -rc sanic tests
|
||||
else
|
||||
$(info Sorting Imports)
|
||||
isort -rc sanic tests
|
||||
isort -rc sanic tests --profile=black
|
||||
endif
|
||||
endif
|
||||
|
||||
black:
|
||||
black --config ./.black.toml sanic tests
|
||||
|
||||
fix-import: black
|
||||
isort -rc sanic tests
|
||||
isort:
|
||||
isort sanic tests --profile=black
|
||||
|
||||
pretty: black isort
|
||||
|
||||
docs-clean:
|
||||
cd docs && make clean
|
||||
@@ -83,6 +84,10 @@ docs: docs-clean
|
||||
docs-test: docs-clean
|
||||
cd docs && make dummy
|
||||
|
||||
docs-serve:
|
||||
# python -m http.server --directory=./docs/_build/html 9999
|
||||
sphinx-autobuild docs docs/_build/html --port 9999 --watch ./sanic
|
||||
|
||||
changelog:
|
||||
python scripts/changelog.py
|
||||
|
||||
|
||||
69
README.rst
69
README.rst
@@ -1,4 +1,4 @@
|
||||
.. image:: https://raw.githubusercontent.com/huge-success/sanic-assets/master/png/sanic-framework-logo-400x97.png
|
||||
.. image:: https://raw.githubusercontent.com/sanic-org/sanic-assets/master/png/sanic-framework-logo-400x97.png
|
||||
:alt: Sanic | Build fast. Run fast.
|
||||
|
||||
Sanic | Build fast. Run fast.
|
||||
@@ -7,29 +7,32 @@ Sanic | Build fast. Run fast.
|
||||
.. start-badges
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 85
|
||||
:stub-columns: 1
|
||||
|
||||
* - Build
|
||||
- | |Build Status| |AppVeyor Build Status| |Codecov|
|
||||
* - Docs
|
||||
- |Documentation|
|
||||
- | |UserGuide| |Documentation|
|
||||
* - Package
|
||||
- | |PyPI| |PyPI version| |Wheel| |Supported implementations| |Code style black|
|
||||
* - Support
|
||||
- | |Forums| |Join the chat at https://gitter.im/sanic-python/Lobby| |Awesome|
|
||||
- | |Forums| |Discord| |Awesome|
|
||||
* - Stats
|
||||
- | |Downloads| |Conda downloads|
|
||||
- | |Downloads| |WkDownloads| |Conda downloads|
|
||||
|
||||
.. |UserGuide| image:: https://img.shields.io/badge/user%20guide-sanic-ff0068
|
||||
:target: https://sanicframework.org/
|
||||
.. |Forums| image:: https://img.shields.io/badge/forums-community-ff0068.svg
|
||||
:target: https://community.sanicframework.org/
|
||||
.. |Join the chat at https://gitter.im/sanic-python/Lobby| image:: https://badges.gitter.im/sanic-python/Lobby.svg
|
||||
:target: https://gitter.im/sanic-python/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
|
||||
.. |Codecov| image:: https://codecov.io/gh/huge-success/sanic/branch/master/graph/badge.svg
|
||||
:target: https://codecov.io/gh/huge-success/sanic
|
||||
.. |Build Status| image:: https://travis-ci.org/huge-success/sanic.svg?branch=master
|
||||
:target: https://travis-ci.org/huge-success/sanic
|
||||
.. |Discord| image:: https://img.shields.io/discord/812221182594121728?logo=discord
|
||||
:target: https://discord.gg/FARQzAEMAA
|
||||
.. |Codecov| image:: https://codecov.io/gh/sanic-org/sanic/branch/master/graph/badge.svg
|
||||
:target: https://codecov.io/gh/sanic-org/sanic
|
||||
.. |Build Status| image:: https://travis-ci.com/sanic-org/sanic.svg?branch=master
|
||||
:target: https://travis-ci.com/sanic-org/sanic
|
||||
.. |AppVeyor Build Status| image:: https://ci.appveyor.com/api/projects/status/d8pt3ids0ynexi8c/branch/master?svg=true
|
||||
:target: https://ci.appveyor.com/project/huge-success/sanic
|
||||
:target: https://ci.appveyor.com/project/sanic-org/sanic
|
||||
.. |Documentation| image:: https://readthedocs.org/projects/sanic/badge/?version=latest
|
||||
:target: http://sanic.readthedocs.io/en/latest/?badge=latest
|
||||
.. |PyPI| image:: https://img.shields.io/pypi/v/sanic.svg
|
||||
@@ -50,20 +53,40 @@ Sanic | Build fast. Run fast.
|
||||
.. |Downloads| image:: https://pepy.tech/badge/sanic/month
|
||||
:alt: Downloads
|
||||
:target: https://pepy.tech/project/sanic
|
||||
.. |WkDownloads| image:: https://pepy.tech/badge/sanic/week
|
||||
:alt: Downloads
|
||||
:target: https://pepy.tech/project/sanic
|
||||
.. |Conda downloads| image:: https://img.shields.io/conda/dn/conda-forge/sanic.svg
|
||||
:alt: Downloads
|
||||
:target: https://anaconda.org/conda-forge/sanic
|
||||
|
||||
.. end-badges
|
||||
|
||||
Sanic is a **Python 3.6+** 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 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.
|
||||
|
||||
`Source code on GitHub <https://github.com/huge-success/sanic/>`_ | `Help and discussion board <https://community.sanicframework.org/>`_.
|
||||
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>`_.
|
||||
|
||||
`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>`_
|
||||
|
||||
The project is maintained by the community, for the community. **Contributions are welcome!**
|
||||
|
||||
The goal of the project is to provide a simple way to get up and running a highly performant HTTP server that is easy to build, to expand, and ultimately to scale.
|
||||
|
||||
Sponsor
|
||||
-------
|
||||
|
||||
|Try CodeStream|
|
||||
|
||||
.. |Try CodeStream| image:: https://alt-images.codestream.com/codestream_logo_sanicorg.png
|
||||
:target: https://codestream.com/?utm_source=github&utm_campaign=sanicorg&utm_medium=banner
|
||||
:alt: Try CodeStream
|
||||
|
||||
Manage pull requests and conduct code reviews in your IDE with full source-tree context. Comment on any line, not just the diffs. Use jump-to-definition, your favorite keybindings, and code intelligence with more of your workflow.
|
||||
|
||||
`Learn More <https://codestream.com/?utm_source=github&utm_campaign=sanicorg&utm_medium=banner>`_
|
||||
|
||||
Thank you to our sponsor. Check out `open collective <https://opencollective.com/sanic-org>`_ to learn more about helping to fund Sanic.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
@@ -83,6 +106,9 @@ Installation
|
||||
If you are running on a clean install of Fedora 28 or above, please make sure you have the ``redhat-rpm-config`` package installed in case if you want to
|
||||
use ``sanic`` with ``ujson`` dependency.
|
||||
|
||||
.. note::
|
||||
|
||||
Windows support is currently "experimental" and on a best-effort basis. Multiple workers are also not currently supported on Windows (see `Issue #1517 <https://github.com/sanic-org/sanic/issues/1517>`_), but setting ``workers=1`` should launch the server successfully.
|
||||
|
||||
Hello World Example
|
||||
-------------------
|
||||
@@ -92,20 +118,20 @@ Hello World Example
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic()
|
||||
app = Sanic("My Hello, world app")
|
||||
|
||||
@app.route('/')
|
||||
async def test(request):
|
||||
return json({'hello': 'world'})
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=8000)
|
||||
app.run()
|
||||
|
||||
Sanic can now be easily run using ``python3 hello.py``.
|
||||
Sanic can now be easily run using ``sanic hello.app``.
|
||||
|
||||
.. code::
|
||||
|
||||
[2018-12-30 11:37:41 +0200] [13564] [INFO] Goin' Fast @ http://0.0.0.0:8000
|
||||
[2018-12-30 11:37:41 +0200] [13564] [INFO] Goin' Fast @ http://127.0.0.1:8000
|
||||
[2018-12-30 11:37:41 +0200] [13564] [INFO] Starting worker [13564]
|
||||
|
||||
And, we can verify it is working: ``curl localhost:8000 -i``
|
||||
@@ -122,24 +148,25 @@ And, we can verify it is working: ``curl localhost:8000 -i``
|
||||
|
||||
**Now, let's go build something fast!**
|
||||
|
||||
Minimum Python version is 3.7. If you need Python 3.6 support, please use v20.12LTS.
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
|
||||
`Documentation on Readthedocs <http://sanic.readthedocs.io/>`_.
|
||||
`User Guide <https://sanicframework.org>`__ and `API Documentation <http://sanic.readthedocs.io/>`__.
|
||||
|
||||
Changelog
|
||||
---------
|
||||
|
||||
`Release Changelogs <https://github.com/huge-success/sanic/blob/master/CHANGELOG.rst>`_.
|
||||
`Release Changelogs <https://github.com/sanic-org/sanic/blob/master/CHANGELOG.rst>`__.
|
||||
|
||||
|
||||
Questions and Discussion
|
||||
------------------------
|
||||
|
||||
`Ask a question or join the conversation <https://community.sanicframework.org/>`_.
|
||||
`Ask a question or join the conversation <https://community.sanicframework.org/>`__.
|
||||
|
||||
Contribution
|
||||
------------
|
||||
|
||||
We are always happy to have new contributions. We have `marked issues good for anyone looking to get started <https://github.com/huge-success/sanic/issues?q=is%3Aopen+is%3Aissue+label%3Abeginner>`_, and welcome `questions on the forums <https://community.sanicframework.org/>`_. Please take a look at our `Contribution guidelines <https://sanic.readthedocs.io/en/latest/sanic/contributing.html>`_.
|
||||
We are always happy to have new contributions. We have `marked issues good for anyone looking to get started <https://github.com/sanic-org/sanic/issues?q=is%3Aopen+is%3Aissue+label%3Abeginner>`_, and welcome `questions on the forums <https://community.sanicframework.org/>`_. Please take a look at our `Contribution guidelines <https://github.com/sanic-org/sanic/blob/master/CONTRIBUTING.rst>`_.
|
||||
|
||||
17
SECURITY.md
17
SECURITY.md
@@ -5,10 +5,16 @@
|
||||
Sanic releases long term support release once a year in December. LTS releases receive bug and security updates for **24 months**. Interim releases throughout the year occur every three months, and are supported until the subsequent interim release.
|
||||
|
||||
| Version | LTS | Supported |
|
||||
| ------- | ------------------ | ------------------ |
|
||||
| 19.6.0 | | :white_check_mark: |
|
||||
| 19.3.1 | | :heavy_check_mark: |
|
||||
| 18.12.0 | :heavy_check_mark: | :heavy_check_mark: |
|
||||
| ------- | ------------- | ------------------ |
|
||||
| 20.12 | until 2022-12 | :heavy_check_mark: |
|
||||
| 20.9 | | :x: |
|
||||
| 20.6 | | :x: |
|
||||
| 20.3 | | :x: |
|
||||
| 19.12 | until 2021-12 | :white_check_mark: |
|
||||
| 19.9 | | :x: |
|
||||
| 19.6 | | :x: |
|
||||
| 19.3 | | :x: |
|
||||
| 18.12 | | :x: |
|
||||
| 0.8.3 | | :x: |
|
||||
| 0.7.0 | | :x: |
|
||||
| 0.6.0 | | :x: |
|
||||
@@ -18,6 +24,9 @@ Sanic releases long term support release once a year in December. LTS releases r
|
||||
| 0.2.0 | | :x: |
|
||||
| 0.1.9 | | :x: |
|
||||
|
||||
:white_check_mark: = security/bug fixes
|
||||
:heavy_check_mark: = full support
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you discover a security vulnerability, we ask that you **do not** create an issue on GitHub. Instead, please [send a message to the core-devs](https://community.sanicframework.org/g/core-devs) on the community forums. Once logged in, you can send a message to the core-devs by clicking the message button.
|
||||
|
||||
1
changelogs/1892.removal.rst
Normal file
1
changelogs/1892.removal.rst
Normal file
@@ -0,0 +1 @@
|
||||
Remove [version] section.
|
||||
3
changelogs/1904.feature.rst
Normal file
3
changelogs/1904.feature.rst
Normal file
@@ -0,0 +1,3 @@
|
||||
Adds WEBSOCKET_PING_TIMEOUT and WEBSOCKET_PING_INTERVAL configuration values
|
||||
|
||||
Allows setting the ping_interval and ping_timeout arguments when initializing `WebSocketCommonProtocol`.
|
||||
1
changelogs/1970.misc.rst
Normal file
1
changelogs/1970.misc.rst
Normal file
@@ -0,0 +1 @@
|
||||
Adds py.typed file to expose type information to other packages.
|
||||
14
codecov.yml
Normal file
14
codecov.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
codecov:
|
||||
require_ci_to_pass: no
|
||||
coverage:
|
||||
precision: 3
|
||||
round: nearest
|
||||
status:
|
||||
project:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 0.5%
|
||||
patch:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 0.75%
|
||||
4
docs/_static/custom.css
vendored
Normal file
4
docs/_static/custom.css
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
.wy-side-nav-search,
|
||||
.wy-nav-top {
|
||||
background: #444444;
|
||||
}
|
||||
BIN
docs/_static/sanic-framework-logo-white-400x97.png
vendored
Normal file
BIN
docs/_static/sanic-framework-logo-white-400x97.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
86
docs/conf.py
86
docs/conf.py
@@ -12,8 +12,10 @@ import sys
|
||||
|
||||
# Add support for auto-doc
|
||||
import recommonmark
|
||||
|
||||
from recommonmark.transform import AutoStructify
|
||||
|
||||
|
||||
# Ensure that sanic is present in the path, to allow sphinx-apidoc to
|
||||
# autogenerate documentation from docstrings
|
||||
root_directory = os.path.dirname(os.getcwd())
|
||||
@@ -21,23 +23,25 @@ sys.path.insert(0, root_directory)
|
||||
|
||||
import sanic
|
||||
|
||||
|
||||
# -- General configuration ------------------------------------------------
|
||||
|
||||
extensions = ['sphinx.ext.autodoc', "recommonmark"]
|
||||
extensions = ["sphinx.ext.autodoc", "recommonmark"]
|
||||
|
||||
templates_path = ['_templates']
|
||||
templates_path = ["_templates"]
|
||||
|
||||
# Enable support for both Restructured Text and Markdown
|
||||
source_suffix = ['.rst', '.md']
|
||||
source_suffix = [".rst", ".md"]
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
master_doc = "index"
|
||||
|
||||
# General information about the project.
|
||||
project = 'Sanic'
|
||||
copyright = '2018, Sanic contributors'
|
||||
author = 'Sanic contributors'
|
||||
project = "Sanic"
|
||||
copyright = "2021, Sanic Community Organization"
|
||||
author = "Sanic Community Organization"
|
||||
|
||||
html_logo = "./_static/sanic-framework-logo-white-400x97.png"
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
@@ -52,7 +56,7 @@ release = sanic.__version__
|
||||
#
|
||||
# This is also used if you do content translation via gettext catalogs.
|
||||
# Usually you set "language" from the command line for these cases.
|
||||
language = 'en'
|
||||
language = "en"
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
@@ -60,10 +64,10 @@ language = 'en'
|
||||
#
|
||||
# modules.rst is generated by sphinx-apidoc but is unused. This suppresses
|
||||
# a warning about it.
|
||||
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'modules.rst']
|
||||
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "modules.rst"]
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
pygments_style = "sphinx"
|
||||
|
||||
# If true, `todo` and `todoList` produce output, else they produce nothing.
|
||||
todo_include_todos = False
|
||||
@@ -72,17 +76,17 @@ todo_include_todos = False
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'sphinx_rtd_theme'
|
||||
html_theme = "sphinx_rtd_theme"
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['_static']
|
||||
|
||||
html_static_path = ["_static"]
|
||||
html_css_files = ["custom.css"]
|
||||
# -- Options for HTMLHelp output ------------------------------------------
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = 'Sanicdoc'
|
||||
htmlhelp_basename = "Sanicdoc"
|
||||
|
||||
# -- Options for LaTeX output ---------------------------------------------
|
||||
|
||||
@@ -90,15 +94,12 @@ latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#
|
||||
# 'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#
|
||||
# 'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#
|
||||
# 'preamble': '',
|
||||
|
||||
# Latex figure (float) alignment
|
||||
#
|
||||
# 'figure_align': 'htbp',
|
||||
@@ -107,14 +108,21 @@ latex_elements = {
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title,
|
||||
# author, documentclass [howto, manual, or own class]).
|
||||
latex_documents = [(master_doc, 'Sanic.tex', 'Sanic Documentation',
|
||||
'Sanic contributors', 'manual'), ]
|
||||
latex_documents = [
|
||||
(
|
||||
master_doc,
|
||||
"Sanic.tex",
|
||||
"Sanic Documentation",
|
||||
"Sanic contributors",
|
||||
"manual",
|
||||
),
|
||||
]
|
||||
|
||||
# -- Options for manual page output ---------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [(master_doc, 'sanic', 'Sanic Documentation', [author], 1)]
|
||||
man_pages = [(master_doc, "sanic", "Sanic Documentation", [author], 1)]
|
||||
|
||||
# -- Options for Texinfo output -------------------------------------------
|
||||
|
||||
@@ -122,8 +130,15 @@ man_pages = [(master_doc, 'sanic', 'Sanic Documentation', [author], 1)]
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
(master_doc, 'Sanic', 'Sanic Documentation', author, 'Sanic',
|
||||
'One line description of project.', 'Miscellaneous'),
|
||||
(
|
||||
master_doc,
|
||||
"Sanic",
|
||||
"Sanic Documentation",
|
||||
author,
|
||||
"Sanic",
|
||||
"One line description of project.",
|
||||
"Miscellaneous",
|
||||
),
|
||||
]
|
||||
|
||||
# -- Options for Epub output ----------------------------------------------
|
||||
@@ -135,17 +150,32 @@ epub_publisher = author
|
||||
epub_copyright = copyright
|
||||
|
||||
# A list of files that should not be packed into the epub file.
|
||||
epub_exclude_files = ['search.html']
|
||||
epub_exclude_files = ["search.html"]
|
||||
|
||||
# -- Custom Settings -------------------------------------------------------
|
||||
|
||||
suppress_warnings = ['image.nonlocal_uri']
|
||||
suppress_warnings = ["image.nonlocal_uri"]
|
||||
|
||||
|
||||
autodoc_typehints = "description"
|
||||
autodoc_default_options = {
|
||||
"member-order": "groupwise",
|
||||
}
|
||||
|
||||
|
||||
# app setup hook
|
||||
def setup(app):
|
||||
app.add_config_value('recommonmark_config', {
|
||||
'enable_eval_rst': True,
|
||||
'enable_auto_doc_ref': False,
|
||||
}, True)
|
||||
app.add_config_value(
|
||||
"recommonmark_config",
|
||||
{
|
||||
"enable_eval_rst": True,
|
||||
"enable_auto_doc_ref": False,
|
||||
},
|
||||
True,
|
||||
)
|
||||
app.add_transform(AutoStructify)
|
||||
|
||||
|
||||
html_theme_options = {
|
||||
"style_external_links": False,
|
||||
}
|
||||
|
||||
@@ -1,39 +1,23 @@
|
||||
.. include:: sanic/index.rst
|
||||
.. include:: ../README.rst
|
||||
|
||||
Guides
|
||||
======
|
||||
User Guide
|
||||
==========
|
||||
|
||||
To learn about using Sanic, checkout the `User Guide <https://sanicframework.org/guide/>`__.
|
||||
|
||||
API
|
||||
===
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
sanic/getting_started
|
||||
sanic/config
|
||||
sanic/logging
|
||||
sanic/request_data
|
||||
sanic/response
|
||||
sanic/cookies
|
||||
sanic/routing
|
||||
sanic/blueprints
|
||||
sanic/static_files
|
||||
sanic/versioning
|
||||
sanic/exceptions
|
||||
sanic/middleware
|
||||
sanic/websocket
|
||||
sanic/decorators
|
||||
sanic/streaming
|
||||
sanic/class_based_views
|
||||
sanic/custom_protocol
|
||||
sanic/sockets
|
||||
sanic/ssl
|
||||
sanic/debug_mode
|
||||
sanic/testing
|
||||
sanic/deploying
|
||||
sanic/extensions
|
||||
sanic/examples
|
||||
👥 User Guide <https://sanicframework.org/guide/>
|
||||
sanic/api_reference
|
||||
💻 Source code <https://github.com/sanic-org/sanic/>
|
||||
sanic/changelog
|
||||
sanic/contributing
|
||||
sanic/api_reference
|
||||
sanic/asyncio_python37
|
||||
❓ Support <https://community.sanicframework.org/>
|
||||
💬 Chat <https://discord.gg/FARQzAEMAA>
|
||||
|
||||
|
||||
Module Documentation
|
||||
@@ -43,4 +27,3 @@ Module Documentation
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
||||
@@ -1,159 +1,132 @@
|
||||
API Reference
|
||||
=============
|
||||
📑 API Reference
|
||||
================
|
||||
|
||||
Submodules
|
||||
----------
|
||||
|
||||
sanic.app module
|
||||
----------------
|
||||
sanic.app
|
||||
---------
|
||||
|
||||
.. automodule:: sanic.app
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
|
||||
sanic.blueprints module
|
||||
-----------------------
|
||||
sanic.blueprints
|
||||
----------------
|
||||
|
||||
.. automodule:: sanic.blueprints
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
|
||||
sanic.blueprint_group module
|
||||
----------------------------
|
||||
sanic.blueprint_group
|
||||
---------------------
|
||||
|
||||
.. automodule:: sanic.blueprint_group
|
||||
:members:
|
||||
:undoc-members:
|
||||
:special-members:
|
||||
|
||||
|
||||
sanic.compat
|
||||
------------
|
||||
|
||||
.. automodule:: sanic.compat
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
|
||||
sanic.config module
|
||||
-------------------
|
||||
sanic.config
|
||||
------------
|
||||
|
||||
.. automodule:: sanic.config
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.constants module
|
||||
----------------------
|
||||
|
||||
.. automodule:: sanic.constants
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.cookies module
|
||||
--------------------
|
||||
sanic.cookies
|
||||
-------------
|
||||
|
||||
.. automodule:: sanic.cookies
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.exceptions module
|
||||
-----------------------
|
||||
sanic.errorpages
|
||||
----------------
|
||||
|
||||
.. automodule:: sanic.errorpages
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.exceptions
|
||||
----------------
|
||||
|
||||
.. automodule:: sanic.exceptions
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.handlers module
|
||||
---------------------
|
||||
sanic.handlers
|
||||
--------------
|
||||
|
||||
.. automodule:: sanic.handlers
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.log module
|
||||
----------------
|
||||
sanic.http
|
||||
----------
|
||||
|
||||
.. automodule:: sanic.http
|
||||
:members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.log
|
||||
---------
|
||||
|
||||
.. automodule:: sanic.log
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.request module
|
||||
--------------------
|
||||
sanic.request
|
||||
-------------
|
||||
|
||||
.. automodule:: sanic.request
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.response module
|
||||
---------------------
|
||||
sanic.response
|
||||
--------------
|
||||
|
||||
.. automodule:: sanic.response
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.router module
|
||||
-------------------
|
||||
sanic.router
|
||||
------------
|
||||
|
||||
.. automodule:: sanic.router
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.server module
|
||||
-------------------
|
||||
sanic.server
|
||||
------------
|
||||
|
||||
.. automodule:: sanic.server
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.static module
|
||||
-------------------
|
||||
|
||||
.. automodule:: sanic.static
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.testing module
|
||||
--------------------
|
||||
|
||||
.. automodule:: sanic.testing
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.views module
|
||||
------------------
|
||||
sanic.views
|
||||
-----------
|
||||
|
||||
.. automodule:: sanic.views
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.websocket module
|
||||
----------------------
|
||||
sanic.websocket
|
||||
---------------
|
||||
|
||||
.. automodule:: sanic.websocket
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
sanic.worker module
|
||||
-------------------
|
||||
sanic.worker
|
||||
------------
|
||||
|
||||
.. automodule:: sanic.worker
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
|
||||
Module contents
|
||||
---------------
|
||||
|
||||
.. automodule:: sanic
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
Python 3.7 AsyncIO examples
|
||||
###########################
|
||||
|
||||
With Python 3.7 AsyncIO got major update for the following types:
|
||||
|
||||
- asyncio.AbstractEventLoop
|
||||
- asyncio.AbstractServer
|
||||
|
||||
|
||||
This example shows how to use sanic with Python 3.7, to be precise: how to retrieve an asyncio server instance:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import os
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
|
||||
server_socket = '/tmp/sanic.sock'
|
||||
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
|
||||
try:
|
||||
os.remove(server_socket)
|
||||
finally:
|
||||
sock.bind(server_socket)
|
||||
|
||||
if __name__ == "__main__":
|
||||
loop = asyncio.get_event_loop()
|
||||
srv_coro = app.create_server(
|
||||
sock=sock,
|
||||
return_asyncio_server=True,
|
||||
asyncio_server_kwargs=dict(
|
||||
start_serving=False
|
||||
)
|
||||
)
|
||||
srv = loop.run_until_complete(srv_coro)
|
||||
try:
|
||||
assert srv.is_serving() is False
|
||||
loop.run_until_complete(srv.start_serving())
|
||||
assert srv.is_serving() is True
|
||||
loop.run_until_complete(srv.serve_forever())
|
||||
except KeyboardInterrupt:
|
||||
srv.close()
|
||||
loop.close()
|
||||
|
||||
|
||||
Please note that uvloop does not support these features yet.
|
||||
@@ -1,301 +0,0 @@
|
||||
Blueprints
|
||||
==========
|
||||
|
||||
Blueprints are objects that can be used for sub-routing within an application.
|
||||
Instead of adding routes to the application instance, blueprints define similar
|
||||
methods for adding routes, which are then registered with the application in a
|
||||
flexible and pluggable manner.
|
||||
|
||||
Blueprints are especially useful for larger applications, where your
|
||||
application logic can be broken down into several groups or areas of
|
||||
responsibility.
|
||||
|
||||
My First Blueprint
|
||||
------------------
|
||||
|
||||
The following shows a very simple blueprint that registers a handler-function at
|
||||
the root `/` of your application.
|
||||
|
||||
Suppose you save this file as `my_blueprint.py`, which can be imported into your
|
||||
main application later.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
from sanic import Blueprint
|
||||
|
||||
bp = Blueprint('my_blueprint')
|
||||
|
||||
@bp.route('/')
|
||||
async def bp_root(request):
|
||||
return json({'my': 'blueprint'})
|
||||
|
||||
Registering blueprints
|
||||
----------------------
|
||||
|
||||
Blueprints must be registered with the application.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from my_blueprint import bp
|
||||
|
||||
app = Sanic(__name__)
|
||||
app.blueprint(bp)
|
||||
|
||||
app.run(host='0.0.0.0', port=8000, debug=True)
|
||||
|
||||
This will add the blueprint to the application and register any routes defined
|
||||
by that blueprint. In this example, the registered routes in the `app.router`
|
||||
will look like:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
[Route(handler=<function bp_root at 0x7f908382f9d8>, methods=frozenset({'GET'}), pattern=re.compile('^/$'), parameters=[], name='my_blueprint.bp_root', uri='/')]
|
||||
|
||||
Blueprint groups and nesting
|
||||
----------------------------
|
||||
|
||||
Blueprints may also be registered as part of a list or tuple, where the registrar will recursively cycle through any sub-sequences of blueprints and register them accordingly. The `Blueprint.group` method is provided to simplify this process, allowing a 'mock' backend directory structure mimicking what's seen from the front end. Consider this (quite contrived) example:
|
||||
|
||||
| api/
|
||||
| ├──content/
|
||||
| │ ├──authors.py
|
||||
| │ ├──static.py
|
||||
| │ └──__init__.py
|
||||
| ├──info.py
|
||||
| └──__init__.py
|
||||
| app.py
|
||||
|
||||
Initialization of this app's blueprint hierarchy could go as follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# api/content/authors.py
|
||||
from sanic import Blueprint
|
||||
|
||||
authors = Blueprint('content_authors', url_prefix='/authors')
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# api/content/static.py
|
||||
from sanic import Blueprint
|
||||
|
||||
static = Blueprint('content_static', url_prefix='/static')
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# api/content/__init__.py
|
||||
from sanic import Blueprint
|
||||
|
||||
from .static import static
|
||||
from .authors import authors
|
||||
|
||||
content = Blueprint.group(static, authors, url_prefix='/content')
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# api/info.py
|
||||
from sanic import Blueprint
|
||||
|
||||
info = Blueprint('info', url_prefix='/info')
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# api/__init__.py
|
||||
from sanic import Blueprint
|
||||
|
||||
from .content import content
|
||||
from .info import info
|
||||
|
||||
api = Blueprint.group(content, info, url_prefix='/api')
|
||||
|
||||
And registering these blueprints in `app.py` can now be done like so:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# app.py
|
||||
from sanic import Sanic
|
||||
|
||||
from .api import api
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
app.blueprint(api)
|
||||
|
||||
Using Blueprints
|
||||
----------------
|
||||
|
||||
Blueprints have almost the same functionality as an application instance.
|
||||
|
||||
WebSocket routes
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
WebSocket handlers can be registered on a blueprint using the `@bp.websocket`
|
||||
decorator or `bp.add_websocket_route` method.
|
||||
|
||||
Blueprint Middleware
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Using blueprints allows you to also register middleware globally.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@bp.middleware
|
||||
async def print_on_request(request):
|
||||
print("I am a spy")
|
||||
|
||||
@bp.middleware('request')
|
||||
async def halt_request(request):
|
||||
return text('I halted the request')
|
||||
|
||||
@bp.middleware('response')
|
||||
async def halt_response(request, response):
|
||||
return text('I halted the response')
|
||||
|
||||
|
||||
Blueprint Group Middleware
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Using this middleware will ensure that you can apply a common middleware to all the blueprints that form the
|
||||
current blueprint group under consideration.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bp1 = Blueprint('bp1', url_prefix='/bp1')
|
||||
bp2 = Blueprint('bp2', url_prefix='/bp2')
|
||||
|
||||
@bp1.middleware('request')
|
||||
async def bp1_only_middleware(request):
|
||||
print('applied on Blueprint : bp1 Only')
|
||||
|
||||
@bp1.route('/')
|
||||
async def bp1_route(request):
|
||||
return text('bp1')
|
||||
|
||||
@bp2.route('/<param>')
|
||||
async def bp2_route(request, param):
|
||||
return text(param)
|
||||
|
||||
group = Blueprint.group(bp1, bp2)
|
||||
|
||||
@group.middleware('request')
|
||||
async def group_middleware(request):
|
||||
print('common middleware applied for both bp1 and bp2')
|
||||
|
||||
# Register Blueprint group under the app
|
||||
app.blueprint(group)
|
||||
|
||||
Exceptions
|
||||
~~~~~~~~~~
|
||||
|
||||
Exceptions can be applied exclusively to blueprints globally.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@bp.exception(NotFound)
|
||||
def ignore_404s(request, exception):
|
||||
return text("Yep, I totally found the page: {}".format(request.url))
|
||||
|
||||
Static files
|
||||
~~~~~~~~~~~~
|
||||
|
||||
Static files can be served globally, under the blueprint prefix.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# suppose bp.name == 'bp'
|
||||
|
||||
bp.static('/web/path', '/folder/to/serve')
|
||||
# also you can pass name parameter to it for url_for
|
||||
bp.static('/web/path', '/folder/to/server', name='uploads')
|
||||
app.url_for('static', name='bp.uploads', filename='file.txt') == '/bp/web/path/file.txt'
|
||||
|
||||
Start and stop
|
||||
--------------
|
||||
|
||||
Blueprints can run functions during the start and stop process of the server.
|
||||
If running in multiprocessor mode (more than 1 worker), these are triggered
|
||||
after the workers fork.
|
||||
|
||||
Available events are:
|
||||
|
||||
- `before_server_start`: Executed before the server begins to accept connections
|
||||
- `after_server_start`: Executed after the server begins to accept connections
|
||||
- `before_server_stop`: Executed before the server stops accepting connections
|
||||
- `after_server_stop`: Executed after the server is stopped and all requests are complete
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bp = Blueprint('my_blueprint')
|
||||
|
||||
@bp.listener('before_server_start')
|
||||
async def setup_connection(app, loop):
|
||||
global database
|
||||
database = mysql.connect(host='127.0.0.1'...)
|
||||
|
||||
@bp.listener('after_server_stop')
|
||||
async def close_connection(app, loop):
|
||||
await database.close()
|
||||
|
||||
Use-case: API versioning
|
||||
------------------------
|
||||
|
||||
Blueprints can be very useful for API versioning, where one blueprint may point
|
||||
at `/v1/<routes>`, and another pointing at `/v2/<routes>`.
|
||||
|
||||
When a blueprint is initialised, it can take an optional `version` argument,
|
||||
which will be prepended to all routes defined on the blueprint. This feature
|
||||
can be used to implement our API versioning scheme.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# blueprints.py
|
||||
from sanic.response import text
|
||||
from sanic import Blueprint
|
||||
|
||||
blueprint_v1 = Blueprint('v1', url_prefix='/api', version="v1")
|
||||
blueprint_v2 = Blueprint('v2', url_prefix='/api', version="v2")
|
||||
|
||||
@blueprint_v1.route('/')
|
||||
async def api_v1_root(request):
|
||||
return text('Welcome to version 1 of our documentation')
|
||||
|
||||
@blueprint_v2.route('/')
|
||||
async def api_v2_root(request):
|
||||
return text('Welcome to version 2 of our documentation')
|
||||
|
||||
When we register our blueprints on the app, the routes `/v1/api` and `/v2/api` will now
|
||||
point to the individual blueprints, which allows the creation of *sub-sites*
|
||||
for each API version.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# main.py
|
||||
from sanic import Sanic
|
||||
from blueprints import blueprint_v1, blueprint_v2
|
||||
|
||||
app = Sanic(__name__)
|
||||
app.blueprint(blueprint_v1)
|
||||
app.blueprint(blueprint_v2)
|
||||
|
||||
app.run(host='0.0.0.0', port=8000, debug=True)
|
||||
|
||||
URL Building with `url_for`
|
||||
---------------------------
|
||||
|
||||
If you wish to generate a URL for a route inside of a blueprint, remember that the endpoint name
|
||||
takes the format `<blueprint_name>.<handler_name>`. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@blueprint_v1.route('/')
|
||||
async def root(request):
|
||||
url = request.app.url_for('v1.post_handler', post_id=5) # --> '/v1/api/post/5'
|
||||
return redirect(url)
|
||||
|
||||
|
||||
@blueprint_v1.route('/post/<post_id>')
|
||||
async def post_handler(request, post_id):
|
||||
return text('Post {} in Blueprint V1'.format(post_id))
|
||||
@@ -1,4 +1,4 @@
|
||||
Changelog
|
||||
---------
|
||||
📜 Changelog
|
||||
============
|
||||
|
||||
.. include:: ../../CHANGELOG.rst
|
||||
@@ -1,169 +0,0 @@
|
||||
Class-Based Views
|
||||
=================
|
||||
|
||||
Class-based views are simply classes which implement response behaviour to
|
||||
requests. They provide a way to compartmentalise handling of different HTTP
|
||||
request types at the same endpoint. Rather than defining and decorating three
|
||||
different handler functions, one for each of an endpoint's supported request
|
||||
type, the endpoint can be assigned a class-based view.
|
||||
|
||||
Defining views
|
||||
--------------
|
||||
|
||||
A class-based view should subclass `HTTPMethodView`. You can then implement
|
||||
class methods for every HTTP request type you want to support. If a request is
|
||||
received that has no defined method, a `405: Method not allowed` response will
|
||||
be generated.
|
||||
|
||||
To register a class-based view on an endpoint, the `app.add_route` method is
|
||||
used. The first argument should be the defined class with the method `as_view`
|
||||
invoked, and the second should be the URL endpoint.
|
||||
|
||||
The available methods are `get`, `post`, `put`, `patch`, and `delete`. A class
|
||||
using all these methods would look like the following.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.views import HTTPMethodView
|
||||
from sanic.response import text
|
||||
|
||||
app = Sanic('some_name')
|
||||
|
||||
class SimpleView(HTTPMethodView):
|
||||
|
||||
def get(self, request):
|
||||
return text('I am get method')
|
||||
|
||||
def post(self, request):
|
||||
return text('I am post method')
|
||||
|
||||
def put(self, request):
|
||||
return text('I am put method')
|
||||
|
||||
def patch(self, request):
|
||||
return text('I am patch method')
|
||||
|
||||
def delete(self, request):
|
||||
return text('I am delete method')
|
||||
|
||||
app.add_route(SimpleView.as_view(), '/')
|
||||
|
||||
You can also use `async` syntax.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.views import HTTPMethodView
|
||||
from sanic.response import text
|
||||
|
||||
app = Sanic('some_name')
|
||||
|
||||
class SimpleAsyncView(HTTPMethodView):
|
||||
|
||||
async def get(self, request):
|
||||
return text('I am async get method')
|
||||
|
||||
app.add_route(SimpleAsyncView.as_view(), '/')
|
||||
|
||||
URL parameters
|
||||
--------------
|
||||
|
||||
If you need any URL parameters, as discussed in the routing guide, include them
|
||||
in the method definition.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class NameView(HTTPMethodView):
|
||||
|
||||
def get(self, request, name):
|
||||
return text('Hello {}'.format(name))
|
||||
|
||||
app.add_route(NameView.as_view(), '/<name>')
|
||||
|
||||
Decorators
|
||||
----------
|
||||
|
||||
If you want to add any decorators to the class, you can set the `decorators`
|
||||
class variable. These will be applied to the class when `as_view` is called.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class ViewWithDecorator(HTTPMethodView):
|
||||
decorators = [some_decorator_here]
|
||||
|
||||
def get(self, request, name):
|
||||
return text('Hello I have a decorator')
|
||||
|
||||
def post(self, request, name):
|
||||
return text("Hello I also have a decorator")
|
||||
|
||||
app.add_route(ViewWithDecorator.as_view(), '/url')
|
||||
|
||||
But if you just want to decorate some functions and not all functions, you can do as follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class ViewWithSomeDecorator(HTTPMethodView):
|
||||
|
||||
@staticmethod
|
||||
@some_decorator_here
|
||||
def get(request, name):
|
||||
return text("Hello I have a decorator")
|
||||
|
||||
def post(self, request, name):
|
||||
return text("Hello I don't have any decorators")
|
||||
|
||||
URL Building
|
||||
------------
|
||||
|
||||
If you wish to build a URL for an HTTPMethodView, remember that the class name will be the endpoint
|
||||
that you will pass into `url_for`. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.route('/')
|
||||
def index(request):
|
||||
url = app.url_for('SpecialClassView')
|
||||
return redirect(url)
|
||||
|
||||
|
||||
class SpecialClassView(HTTPMethodView):
|
||||
def get(self, request):
|
||||
return text('Hello from the Special Class View!')
|
||||
|
||||
|
||||
app.add_route(SpecialClassView.as_view(), '/special_class_view')
|
||||
|
||||
Using CompositionView
|
||||
---------------------
|
||||
|
||||
As an alternative to the `HTTPMethodView`, you can use `CompositionView` to
|
||||
move handler functions outside of the view class.
|
||||
|
||||
Handler functions for each supported HTTP method are defined elsewhere in the
|
||||
source, and then added to the view using the `CompositionView.add` method. The
|
||||
first parameter is a list of HTTP methods to handle (e.g. `['GET', 'POST']`),
|
||||
and the second is the handler function. The following example shows
|
||||
`CompositionView` usage with both an external handler function and an inline
|
||||
lambda:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.views import CompositionView
|
||||
from sanic.response import text
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
def get_handler(request):
|
||||
return text('I am a get method')
|
||||
|
||||
view = CompositionView()
|
||||
view.add(['GET'], get_handler)
|
||||
view.add(['POST', 'PUT'], lambda request: text('I am a post/put method'))
|
||||
|
||||
# Use the new view to handle requests to the base URL
|
||||
app.add_route(view, '/')
|
||||
|
||||
Note: currently you cannot build a URL for a CompositionView using `url_for`.
|
||||
@@ -1,242 +0,0 @@
|
||||
Configuration
|
||||
=============
|
||||
|
||||
Any reasonably complex application will need configuration that is not baked into the actual code. Settings might be different for different environments or installations.
|
||||
|
||||
Basics
|
||||
------
|
||||
|
||||
Sanic holds the configuration in the `config` attribute of the application object. The configuration object is merely an object that can be modified either using dot-notation or like a dictionary:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic('myapp')
|
||||
app.config.DB_NAME = 'appdb'
|
||||
app.config.DB_USER = 'appuser'
|
||||
|
||||
Since the config object actually is a dictionary, you can use its `update` method in order to set several values at once:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
db_settings = {
|
||||
'DB_HOST': 'localhost',
|
||||
'DB_NAME': 'appdb',
|
||||
'DB_USER': 'appuser'
|
||||
}
|
||||
app.config.update(db_settings)
|
||||
|
||||
In general the convention is to only have UPPERCASE configuration parameters. The methods described below for loading configuration only look for such uppercase parameters.
|
||||
|
||||
Loading Configuration
|
||||
---------------------
|
||||
|
||||
There are several ways how to load configuration.
|
||||
|
||||
From Environment Variables
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Any variables defined with the `SANIC_` prefix will be applied to the sanic config. For example, setting `SANIC_REQUEST_TIMEOUT` will be loaded by the application automatically and fed into the `REQUEST_TIMEOUT` config variable. You can pass a different prefix to Sanic:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic(load_env='MYAPP_')
|
||||
|
||||
Then the above variable would be `MYAPP_REQUEST_TIMEOUT`. If you want to disable loading from environment variables you can set it to `False` instead:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic(load_env=False)
|
||||
|
||||
From an Object
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
If there are a lot of configuration values and they have sensible defaults it might be helpful to put them into a module:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import myapp.default_settings
|
||||
|
||||
app = Sanic('myapp')
|
||||
app.config.from_object(myapp.default_settings)
|
||||
|
||||
or also by path to config:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic('myapp')
|
||||
app.config.from_object('config.path.config.Class')
|
||||
|
||||
You could use a class or any other object as well.
|
||||
|
||||
From a File
|
||||
~~~~~~~~~~~
|
||||
|
||||
Usually you will want to load configuration from a file that is not part of the distributed application. You can load configuration from a file using `from_pyfile(/path/to/config_file)`. However, that requires the program to know the path to the config file. So instead you can specify the location of the config file in an environment variable and tell Sanic to use that to find the config file:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic('myapp')
|
||||
app.config.from_envvar('MYAPP_SETTINGS')
|
||||
|
||||
Then you can run your application with the `MYAPP_SETTINGS` environment variable set:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
#$ MYAPP_SETTINGS=/path/to/config_file python3 myapp.py
|
||||
#INFO: Goin' Fast @ http://0.0.0.0:8000
|
||||
|
||||
|
||||
The config files are regular Python files which are executed in order to load them. This allows you to use arbitrary logic for constructing the right configuration. Only uppercase variables are added to the configuration. Most commonly the configuration consists of simple key value pairs:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# config_file
|
||||
DB_HOST = 'localhost'
|
||||
DB_NAME = 'appdb'
|
||||
DB_USER = 'appuser'
|
||||
|
||||
Builtin Configuration Values
|
||||
----------------------------
|
||||
|
||||
Out of the box there are just a few predefined values which can be overwritten when creating the application.
|
||||
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| Variable | Default | Description |
|
||||
+===========================+===================+=============================================================================+
|
||||
| REQUEST_MAX_SIZE | 100000000 | How big a request may be (bytes) |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| REQUEST_BUFFER_QUEUE_SIZE | 100 | Request streaming buffer queue size |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| REQUEST_TIMEOUT | 60 | How long a request can take to arrive (sec) |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| RESPONSE_TIMEOUT | 60 | How long a response can take to process (sec) |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| KEEP_ALIVE | True | Disables keep-alive when False |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| KEEP_ALIVE_TIMEOUT | 5 | How long to hold a TCP connection open (sec) |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| GRACEFUL_SHUTDOWN_TIMEOUT | 15.0 | How long to wait to force close non-idle connection (sec) |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| ACCESS_LOG | True | Disable or enable access log |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| PROXIES_COUNT | -1 | The number of proxy servers in front of the app (e.g. nginx; see below) |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| FORWARDED_FOR_HEADER | "X-Forwarded-For" | The name of "X-Forwarded-For" HTTP header that contains client and proxy ip |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
| REAL_IP_HEADER | "X-Real-IP" | The name of "X-Real-IP" HTTP header that contains real client ip |
|
||||
+---------------------------+-------------------+-----------------------------------------------------------------------------+
|
||||
|
||||
The different Timeout variables:
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
`REQUEST_TIMEOUT`
|
||||
#################
|
||||
|
||||
A request timeout measures the duration of time between the instant when a new open TCP connection is passed to the
|
||||
Sanic backend server, and the instant when the whole HTTP request is received. If the time taken exceeds the
|
||||
`REQUEST_TIMEOUT` value (in seconds), this is considered a Client Error so Sanic generates an `HTTP 408` response
|
||||
and sends that to the client. Set this parameter's value higher if your clients routinely pass very large request payloads
|
||||
or upload requests very slowly.
|
||||
|
||||
`RESPONSE_TIMEOUT`
|
||||
##################
|
||||
|
||||
A response timeout measures the duration of time between the instant the Sanic server passes the HTTP request to the
|
||||
Sanic App, and the instant a HTTP response is sent to the client. If the time taken exceeds the `RESPONSE_TIMEOUT`
|
||||
value (in seconds), this is considered a Server Error so Sanic generates an `HTTP 503` response and sends that to the
|
||||
client. Set this parameter's value higher if your application is likely to have long-running process that delay the
|
||||
generation of a response.
|
||||
|
||||
`KEEP_ALIVE_TIMEOUT`
|
||||
####################
|
||||
|
||||
What is Keep Alive? And what does the Keep Alive Timeout value do?
|
||||
******************************************************************
|
||||
|
||||
`Keep-Alive` is a HTTP feature introduced in `HTTP 1.1`. When sending a HTTP request, the client (usually a web browser application)
|
||||
can set a `Keep-Alive` header to indicate the http server (Sanic) to not close the TCP connection after it has send the response.
|
||||
This allows the client to reuse the existing TCP connection to send subsequent HTTP requests, and ensures more efficient
|
||||
network traffic for both the client and the server.
|
||||
|
||||
The `KEEP_ALIVE` config variable is set to `True` in Sanic by default. If you don't need this feature in your application,
|
||||
set it to `False` to cause all client connections to close immediately after a response is sent, regardless of
|
||||
the `Keep-Alive` header on the request.
|
||||
|
||||
The amount of time the server holds the TCP connection open is decided by the server itself.
|
||||
In Sanic, that value is configured using the `KEEP_ALIVE_TIMEOUT` value. By default, it is set to 5 seconds.
|
||||
This is the same default setting as the Apache HTTP server and is a good balance between allowing enough time for
|
||||
the client to send a new request, and not holding open too many connections at once. Do not exceed 75 seconds unless
|
||||
you know your clients are using a browser which supports TCP connections held open for that long.
|
||||
|
||||
For reference:
|
||||
|
||||
* Apache httpd server default keepalive timeout = 5 seconds
|
||||
* Nginx server default keepalive timeout = 75 seconds
|
||||
* Nginx performance tuning guidelines uses keepalive = 15 seconds
|
||||
* IE (5-9) client hard keepalive limit = 60 seconds
|
||||
* Firefox client hard keepalive limit = 115 seconds
|
||||
* Opera 11 client hard keepalive limit = 120 seconds
|
||||
* Chrome 13+ client keepalive limit > 300+ seconds
|
||||
|
||||
|
||||
Proxy configuration
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
When you use a reverse proxy server (e.g. nginx), the value of `request.ip` will contain ip of a proxy,
|
||||
typically `127.0.0.1`. Sanic may be configured to use proxy headers for determining the true client IP,
|
||||
available as `request.remote_addr`. The full external URL is also constructed from header fields if available.
|
||||
|
||||
Without proper precautions, a malicious client may use proxy headers to spoof its own IP. To avoid such issues, Sanic does not use any proxy headers unless explicitly enabled.
|
||||
|
||||
Services behind reverse proxies must configure `FORWARDED_SECRET`, `REAL_IP_HEADER` and/or `PROXIES_COUNT`.
|
||||
|
||||
Forwarded header
|
||||
################
|
||||
|
||||
.. Forwarded: for="1.2.3.4"; proto="https"; host="yoursite.com"; secret="Pr0xy", for="10.0.0.1"; proto="http"; host="proxy.internal"; by="_1234proxy"
|
||||
|
||||
* Set `FORWARDED_SECRET` to an identifier used by the proxy of interest.
|
||||
|
||||
The secret is used to securely identify a specific proxy server. Given the above header, secret `Pr0xy` would use the
|
||||
information on the first line and secret `_1234proxy` would use the second line. The secret must exactly match the value
|
||||
of `secret` or `by`. A secret in `by` must begin with an underscore and use only characters specified in
|
||||
`RFC 7239 section 6.3 <https://tools.ietf.org/html/rfc7239#section-6.3>`_, while `secret` has no such restrictions.
|
||||
|
||||
Sanic ignores any elements without the secret key, and will not even parse the header if no secret is set.
|
||||
|
||||
All other proxy headers are ignored once a trusted forwarded element is found, as it already carries complete information about the client.
|
||||
|
||||
Traditional proxy headers
|
||||
#########################
|
||||
|
||||
.. X-Real-IP: 1.2.3.4
|
||||
X-Forwarded-For: 1.2.3.4, 10.0.0.1
|
||||
X-Forwarded-Proto: https
|
||||
X-Forwarded-Host: yoursite.com
|
||||
|
||||
|
||||
* Set `REAL_IP_HEADER` to `x-real-ip`, `true-client-ip`, `cf-connecting-ip` or other name of such header.
|
||||
* Set `PROXIES_COUNT` to the number of entries expected in `x-forwarded-for` (name configurable via `FORWARDED_FOR_HEADER`).
|
||||
|
||||
If client IP is found by one of these methods, Sanic uses the following headers for URL parts:
|
||||
|
||||
* `x-forwarded-proto`, `x-forwarded-host`, `x-forwarded-port`, `x-forwarded-path` and if necessary, `x-scheme`.
|
||||
|
||||
Proxy config if using ...
|
||||
#########################
|
||||
|
||||
* a proxy that supports `forwarded`: set `FORWARDED_SECRET` to the value that the proxy inserts in the header
|
||||
* Apache Traffic Server: `CONFIG proxy.config.http.insert_forwarded STRING for|proto|host|by=_secret`
|
||||
* NGHTTPX: `nghttpx --add-forwarded=for,proto,host,by --forwarded-for=ip --forwarded-by=_secret`
|
||||
* NGINX: after `the official instructions <https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/>`_, add anywhere in your config:
|
||||
|
||||
.. proxy_set_header Forwarded "$proxy_add_forwarded;by=\"_$server_name\";proto=$scheme;host=\"$http_host\";path=\"$request_uri\";secret=_secret";
|
||||
|
||||
* a custom header with client IP: set `REAL_IP_HEADER` to the name of that header
|
||||
* `x-forwarded-for`: set `PROXIES_COUNT` to `1` for a single proxy, or a greater number to allow Sanic to select the correct IP
|
||||
* no proxies: no configuration required!
|
||||
|
||||
Changes in Sanic 19.9
|
||||
#####################
|
||||
|
||||
Earlier Sanic versions had unsafe default settings. From 19.9 onwards proxy settings must be set manually, and support for negative PROXIES_COUNT has been removed.
|
||||
@@ -1 +1,4 @@
|
||||
♥️ Contributing
|
||||
===============
|
||||
|
||||
.. include:: ../../CONTRIBUTING.rst
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
Cookies
|
||||
=======
|
||||
|
||||
Cookies are pieces of data which persist inside a user's browser. Sanic can
|
||||
both read and write cookies, which are stored as key-value pairs.
|
||||
|
||||
.. warning::
|
||||
|
||||
Cookies can be freely altered by the client. Therefore you cannot just store
|
||||
data such as login information in cookies as-is, as they can be freely altered
|
||||
by the client. To ensure data you store in cookies is not forged or tampered
|
||||
with by the client, use something like `itsdangerous`_ to cryptographically
|
||||
sign the data.
|
||||
|
||||
|
||||
Reading cookies
|
||||
---------------
|
||||
|
||||
A user's cookies can be accessed via the ``Request`` object's ``cookies`` dictionary.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route("/cookie")
|
||||
async def test(request):
|
||||
test_cookie = request.cookies.get('test')
|
||||
return text("Test cookie set to: {}".format(test_cookie))
|
||||
|
||||
Writing cookies
|
||||
---------------
|
||||
|
||||
When returning a response, cookies can be set on the ``Response`` object.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route("/cookie")
|
||||
async def test(request):
|
||||
response = text("There's a cookie up in this response")
|
||||
response.cookies['test'] = 'It worked!'
|
||||
response.cookies['test']['domain'] = '.gotta-go-fast.com'
|
||||
response.cookies['test']['httponly'] = True
|
||||
return response
|
||||
|
||||
Deleting cookies
|
||||
----------------
|
||||
|
||||
Cookies can be removed semantically or explicitly.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route("/cookie")
|
||||
async def test(request):
|
||||
response = text("Time to eat some cookies muahaha")
|
||||
|
||||
# This cookie will be set to expire in 0 seconds
|
||||
del response.cookies['kill_me']
|
||||
|
||||
# This cookie will self destruct in 5 seconds
|
||||
response.cookies['short_life'] = 'Glad to be here'
|
||||
response.cookies['short_life']['max-age'] = 5
|
||||
del response.cookies['favorite_color']
|
||||
|
||||
# This cookie will remain unchanged
|
||||
response.cookies['favorite_color'] = 'blue'
|
||||
response.cookies['favorite_color'] = 'pink'
|
||||
del response.cookies['favorite_color']
|
||||
|
||||
return response
|
||||
|
||||
Response cookies can be set like dictionary values and have the following
|
||||
parameters available:
|
||||
|
||||
- ``expires`` (datetime): The time for the cookie to expire on the client's browser.
|
||||
- ``path`` (string): The subset of URLs to which this cookie applies. Defaults to /.
|
||||
- ``comment`` (string): A comment (metadata).
|
||||
- ``domain`` (string): Specifies the domain for which the cookie is valid. An
|
||||
explicitly specified domain must always start with a dot.
|
||||
- ``max-age`` (number): Number of seconds the cookie should live for.
|
||||
- ``secure`` (boolean): Specifies whether the cookie will only be sent via HTTPS.
|
||||
- ``httponly`` (boolean): Specifies whether the cookie cannot be read by Javascript.
|
||||
|
||||
.. _itsdangerous: https://pythonhosted.org/itsdangerous/
|
||||
@@ -1,76 +0,0 @@
|
||||
Custom Protocols
|
||||
================
|
||||
|
||||
.. note::
|
||||
|
||||
This is advanced usage, and most readers will not need such functionality.
|
||||
|
||||
You can change the behavior of Sanic's protocol by specifying a custom
|
||||
protocol, which should be a subclass
|
||||
of `asyncio.protocol <https://docs.python.org/3/library/asyncio-protocol.html#protocol-classes>`_.
|
||||
This protocol can then be passed as the keyword argument ``protocol`` to the ``sanic.run`` method.
|
||||
|
||||
The constructor of the custom protocol class receives the following keyword
|
||||
arguments from Sanic.
|
||||
|
||||
- ``loop``: an ``asyncio``-compatible event loop.
|
||||
- ``connections``: a ``set`` to store protocol objects. When Sanic receives
|
||||
``SIGINT`` or ``SIGTERM``, it executes ``protocol.close_if_idle`` for all protocol
|
||||
objects stored in this set.
|
||||
- ``signal``: a ``sanic.server.Signal`` object with the ``stopped`` attribute. When
|
||||
Sanic receives ``SIGINT`` or ``SIGTERM``, ``signal.stopped`` is assigned ``True``.
|
||||
- ``request_handler``: a coroutine that takes a ``sanic.request.Request`` object
|
||||
and a ``response`` callback as arguments.
|
||||
- ``error_handler``: a ``sanic.exceptions.Handler`` which is called when exceptions
|
||||
are raised.
|
||||
- ``request_timeout``: the number of seconds before a request times out.
|
||||
- ``request_max_size``: an integer specifying the maximum size of a request, in bytes.
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
An error occurs in the default protocol if a handler function does not return
|
||||
an ``HTTPResponse`` object.
|
||||
|
||||
By overriding the ``write_response`` protocol method, if a handler returns a
|
||||
string it will be converted to an ``HTTPResponse object``.
|
||||
|
||||
.. code:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.server import HttpProtocol
|
||||
from sanic.response import text
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
|
||||
class CustomHttpProtocol(HttpProtocol):
|
||||
|
||||
def __init__(self, *, loop, request_handler, error_handler,
|
||||
signal, connections, request_timeout, request_max_size):
|
||||
super().__init__(
|
||||
loop=loop, request_handler=request_handler,
|
||||
error_handler=error_handler, signal=signal,
|
||||
connections=connections, request_timeout=request_timeout,
|
||||
request_max_size=request_max_size)
|
||||
|
||||
def write_response(self, response):
|
||||
if isinstance(response, str):
|
||||
response = text(response)
|
||||
self.transport.write(
|
||||
response.output(self.request.version)
|
||||
)
|
||||
self.transport.close()
|
||||
|
||||
|
||||
@app.route('/')
|
||||
async def string(request):
|
||||
return 'string'
|
||||
|
||||
|
||||
@app.route('/1')
|
||||
async def response(request):
|
||||
return text('response')
|
||||
|
||||
app.run(host='0.0.0.0', port=8000, protocol=CustomHttpProtocol)
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
Debug Mode
|
||||
=============
|
||||
|
||||
When enabling Sanic's debug mode, Sanic will provide a more verbose logging output
|
||||
and by default will enable the Auto Reload feature.
|
||||
|
||||
.. warning::
|
||||
|
||||
Sanic's debug more will slow down the server's performance
|
||||
and is therefore advised to enable it only in development environments.
|
||||
|
||||
|
||||
Setting the debug mode
|
||||
----------------------
|
||||
|
||||
By setting the ``debug`` mode a more verbose output from Sanic will be output
|
||||
and the Automatic Reloader will be activated.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic()
|
||||
|
||||
@app.route('/')
|
||||
async def hello_world(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host="0.0.0.0", port=8000, debug=True)
|
||||
|
||||
|
||||
|
||||
Manually setting auto reload
|
||||
----------------------------
|
||||
|
||||
Sanic offers a way to enable or disable the Automatic Reloader manually,
|
||||
the ``auto_reload`` argument will activate or deactivate the Automatic Reloader.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic()
|
||||
|
||||
@app.route('/')
|
||||
async def hello_world(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host="0.0.0.0", port=8000, auto_reload=True)
|
||||
@@ -1,40 +0,0 @@
|
||||
Handler Decorators
|
||||
==================
|
||||
|
||||
Since Sanic handlers are simple Python functions, you can apply decorators to them in a similar manner to Flask. A typical use case is when you want some code to run before a handler's code is executed.
|
||||
|
||||
Authorization Decorator
|
||||
-----------------------
|
||||
|
||||
Let's say you want to check that a user is authorized to access a particular endpoint. You can create a decorator that wraps a handler function, checks a request if the client is authorized to access a resource, and sends the appropriate response.
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from functools import wraps
|
||||
from sanic.response import json
|
||||
|
||||
def authorized():
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
async def decorated_function(request, *args, **kwargs):
|
||||
# run some method that checks the request
|
||||
# for the client's authorization status
|
||||
is_authorized = check_request_for_authorization_status(request)
|
||||
|
||||
if is_authorized:
|
||||
# the user is authorized.
|
||||
# run the handler method and return the response
|
||||
response = await f(request, *args, **kwargs)
|
||||
return response
|
||||
else:
|
||||
# the user is not authorized.
|
||||
return json({'status': 'not_authorized'}, 403)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
@app.route("/")
|
||||
@authorized()
|
||||
async def test(request):
|
||||
return json({'status': 'authorized'})
|
||||
@@ -1,201 +0,0 @@
|
||||
Deploying
|
||||
=========
|
||||
|
||||
Deploying Sanic is very simple using one of three options: the inbuilt webserver,
|
||||
an `ASGI webserver <https://asgi.readthedocs.io/en/latest/implementations.html>`_, or `gunicorn`.
|
||||
It is also very common to place Sanic behind a reverse proxy, like `nginx`.
|
||||
|
||||
Running via Sanic webserver
|
||||
---------------------------
|
||||
|
||||
After defining an instance of `sanic.Sanic`, we can call the `run` method with the following
|
||||
keyword arguments:
|
||||
|
||||
- `host` *(default `"127.0.0.1"`)*: Address to host the server on.
|
||||
- `port` *(default `8000`)*: Port to host the server on.
|
||||
- `debug` *(default `False`)*: Enables debug output (slows server).
|
||||
- `ssl` *(default `None`)*: `SSLContext` for SSL encryption of worker(s).
|
||||
- `sock` *(default `None`)*: Socket for the server to accept connections from.
|
||||
- `workers` *(default `1`)*: Number of worker processes to spawn.
|
||||
- `loop` *(default `None`)*: An `asyncio`-compatible event loop. If none is specified, Sanic creates its own event loop.
|
||||
- `protocol` *(default `HttpProtocol`)*: Subclass of `asyncio.protocol <https://docs.python.org/3/library/asyncio-protocol.html#protocol-classes>`_.
|
||||
- `access_log` *(default `True`)*: Enables log on handling requests (significantly slows server).
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app.run(host='0.0.0.0', port=1337, access_log=False)
|
||||
|
||||
In the above example, we decided to turn off the access log in order to increase performance.
|
||||
|
||||
Workers
|
||||
~~~~~~~
|
||||
|
||||
By default, Sanic listens in the main process using only one CPU core. To crank
|
||||
up the juice, just specify the number of workers in the `run` arguments.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app.run(host='0.0.0.0', port=1337, workers=4)
|
||||
|
||||
Sanic will automatically spin up multiple processes and route traffic between
|
||||
them. We recommend as many workers as you have available cores.
|
||||
|
||||
Running via command
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
If you like using command line arguments, you can launch a Sanic webserver by
|
||||
executing the module. For example, if you initialized Sanic as `app` in a file
|
||||
named `server.py`, you could run the server like so:
|
||||
|
||||
.. python -m sanic server.app --host=0.0.0.0 --port=1337 --workers=4
|
||||
|
||||
With this way of running sanic, it is not necessary to invoke `app.run` in your
|
||||
Python file. If you do, make sure you wrap it so that it only executes when
|
||||
directly run by the interpreter.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=1337, workers=4)
|
||||
|
||||
Running via ASGI
|
||||
----------------
|
||||
|
||||
Sanic is also ASGI-compliant. This means you can use your preferred ASGI webserver
|
||||
to run Sanic. The three main implementations of ASGI are
|
||||
`Daphne <http://github.com/django/daphne>`_, `Uvicorn <https://www.uvicorn.org/>`_,
|
||||
and `Hypercorn <https://pgjones.gitlab.io/hypercorn/index.html>`_.
|
||||
|
||||
Follow their documentation for the proper way to run them, but it should look
|
||||
something like:
|
||||
|
||||
::
|
||||
|
||||
daphne myapp:app
|
||||
uvicorn myapp:app
|
||||
hypercorn myapp:app
|
||||
|
||||
A couple things to note when using ASGI:
|
||||
|
||||
1. When using the Sanic webserver, websockets will run using the `websockets <https://websockets.readthedocs.io/>`_ package.
|
||||
In ASGI mode, there is no need for this package since websockets are managed in the ASGI server.
|
||||
2. The ASGI `lifespan protocol <https://asgi.readthedocs.io/en/latest/specs/lifespan.html>`, supports
|
||||
only two server events: startup and shutdown. Sanic has four: before startup, after startup,
|
||||
before shutdown, and after shutdown. Therefore, in ASGI mode, the startup and shutdown events will
|
||||
run consecutively and not actually around the server process beginning and ending (since that
|
||||
is now controlled by the ASGI server). Therefore, it is best to use `after_server_start` and
|
||||
`before_server_stop`.
|
||||
3. ASGI mode is still in "beta" as of Sanic v19.6.
|
||||
|
||||
Running via Gunicorn
|
||||
--------------------
|
||||
|
||||
`Gunicorn <http://gunicorn.org/>`_ ‘Green Unicorn’ is a WSGI HTTP Server for UNIX.
|
||||
It’s a pre-fork worker model ported from Ruby’s Unicorn project.
|
||||
|
||||
In order to run Sanic application with Gunicorn, you need to use the special `sanic.worker.GunicornWorker`
|
||||
for Gunicorn `worker-class` argument:
|
||||
|
||||
::
|
||||
|
||||
gunicorn myapp:app --bind 0.0.0.0:1337 --worker-class sanic.worker.GunicornWorker
|
||||
|
||||
|
||||
If your application suffers from memory leaks, you can configure Gunicorn to gracefully restart a worker
|
||||
after it has processed a given number of requests. This can be a convenient way to help limit the effects
|
||||
of the memory leak.
|
||||
|
||||
See the `Gunicorn Docs <http://docs.gunicorn.org/en/latest/settings.html#max-requests>`_ for more information.
|
||||
|
||||
Other deployment considerations
|
||||
-------------------------------
|
||||
|
||||
Running behind a reverse proxy
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Sanic can be used with a reverse proxy (e.g. nginx). There's a simple example of nginx configuration:
|
||||
|
||||
|
||||
::
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.org;
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
If you want to get real client ip, you should configure `X-Real-IP` and `X-Forwarded-For` HTTP headers and set `app.config.PROXIES_COUNT` to `1`; see the configuration page for more information.
|
||||
|
||||
Disable debug logging for performance
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
To improve the performance add `debug=False` and `access_log=False` in the `run` arguments.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app.run(host='0.0.0.0', port=1337, workers=4, debug=False, access_log=False)
|
||||
|
||||
Running via Gunicorn you can set Environment variable `SANIC_ACCESS_LOG="False"`
|
||||
|
||||
::
|
||||
|
||||
env SANIC_ACCESS_LOG="False" gunicorn myapp:app --bind 0.0.0.0:1337 --worker-class sanic.worker.GunicornWorker --log-level warning
|
||||
|
||||
Or you can rewrite app config directly
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app.config.ACCESS_LOG = False
|
||||
|
||||
Asynchronous support and sharing the loop
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This is suitable if you *need* to share the Sanic process with other applications, in particular the `loop`.
|
||||
However, be advised that this method does not support using multiple processes, and is not the preferred way
|
||||
to run the app in general.
|
||||
|
||||
Here is an incomplete example (please see `run_async.py` in examples for something more practical):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
server = app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True)
|
||||
loop = asyncio.get_event_loop()
|
||||
task = asyncio.ensure_future(server)
|
||||
loop.run_forever()
|
||||
|
||||
Caveat: using this method, calling `app.create_server()` will trigger "before_server_start" server events, but not
|
||||
"after_server_start", "before_server_stop", or "after_server_stop" server events.
|
||||
|
||||
For more advanced use-cases, you can trigger these events using the AsyncioServer object, returned by awaiting
|
||||
the server task.
|
||||
|
||||
Here is an incomplete example (please see `run_async_advanced.py` in examples for something more complete):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
serv_coro = app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True)
|
||||
loop = asyncio.get_event_loop()
|
||||
serv_task = asyncio.ensure_future(serv_coro, loop=loop)
|
||||
server = loop.run_until_complete(serv_task)
|
||||
server.after_start()
|
||||
try:
|
||||
loop.run_forever()
|
||||
except KeyboardInterrupt as e:
|
||||
loop.stop()
|
||||
finally:
|
||||
server.before_stop()
|
||||
|
||||
# Wait for server to close
|
||||
close_task = server.close()
|
||||
loop.run_until_complete(close_task)
|
||||
|
||||
# Complete all tasks on the loop
|
||||
for connection in server.connections:
|
||||
connection.close_if_idle()
|
||||
server.after_stop()
|
||||
@@ -1,167 +0,0 @@
|
||||
Examples
|
||||
========
|
||||
|
||||
This section of the documentation is a simple collection of example code that can help you get a quick start
|
||||
on your application development. Most of these examples are categorized and provide you with a link to the
|
||||
working code example in the `Sanic Repository <https://github.com/huge-success/sanic/tree/master/examples>`_
|
||||
|
||||
|
||||
Basic Examples
|
||||
--------------
|
||||
|
||||
This section of the examples are a collection of code that provide a simple use case example of the sanic application.
|
||||
|
||||
Simple Apps
|
||||
~~~~~~~~~~~~
|
||||
|
||||
A simple sanic application with a single ``async`` method with ``text`` and ``json`` type response.
|
||||
|
||||
|
||||
.. literalinclude:: ../../examples/teapot.py
|
||||
|
||||
.. literalinclude:: ../../examples/simple_server.py
|
||||
|
||||
|
||||
Simple App with ``Sanic Views``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Showcasing the simple mechanism of using :class:`sanic.viewes.HTTPMethodView` as well as a way to extend the same
|
||||
into providing a custom ``async`` behavior for ``view``.
|
||||
|
||||
.. literalinclude:: ../../examples/simple_async_view.py
|
||||
|
||||
|
||||
URL Redirect
|
||||
~~~~~~~~~~~~
|
||||
|
||||
.. literalinclude:: ../../examples/redirect_example.py
|
||||
|
||||
|
||||
Named URL redirection
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
``Sanic`` provides an easy to use way of redirecting the requests via a helper method called ``url_for`` that takes a
|
||||
unique url name as argument and returns you the actual route assigned for it. This will help in simplifying the
|
||||
efforts required in redirecting the user between different section of the application.
|
||||
|
||||
.. literalinclude:: ../../examples/url_for_example.py
|
||||
|
||||
Blueprints
|
||||
~~~~~~~~~~
|
||||
``Sanic`` provides an amazing feature to group your APIs and routes under a logical collection that can easily be
|
||||
imported and plugged into any of your sanic application and it's called ``blueprints``
|
||||
|
||||
.. literalinclude:: ../../examples/blueprints.py
|
||||
|
||||
Logging Enhancements
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Even though ``Sanic`` comes with a battery of Logging support it allows the end users to customize the way logging
|
||||
is handled in the application runtime.
|
||||
|
||||
.. literalinclude:: ../../examples/override_logging.py
|
||||
|
||||
The following sample provides an example code that demonstrates the usage of :func:`sanic.app.Sanic.middleware` in order
|
||||
to provide a mechanism to assign a unique request ID for each of the incoming requests and log them via
|
||||
`aiotask-context <https://github.com/Skyscanner/aiotask-context>`_.
|
||||
|
||||
|
||||
.. literalinclude:: ../../examples/log_request_id.py
|
||||
|
||||
Sanic Streaming Support
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
``Sanic`` framework comes with in-built support for streaming large files and the following code explains the process
|
||||
to setup a ``Sanic`` application with streaming support.
|
||||
|
||||
.. literalinclude:: ../../examples/request_stream/server.py
|
||||
|
||||
Sample Client app to show the usage of streaming application by a client code.
|
||||
|
||||
.. literalinclude:: ../../examples/request_stream/client.py
|
||||
|
||||
Sanic Concurrency Support
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
``Sanic`` supports the ability to start an app with multiple worker support. However, it's important to be able to limit
|
||||
the concurrency per process/loop in order to ensure an efficient execution. The following section of the code provides a
|
||||
brief example of how to limit the concurrency with the help of :class:`asyncio.Semaphore`
|
||||
|
||||
.. literalinclude:: ../../examples/limit_concurrency.py
|
||||
|
||||
|
||||
Sanic Deployment via Docker
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Deploying a ``sanic`` app via ``docker`` and ``docker-compose`` is an easy task to achieve and the following example
|
||||
provides a deployment of the sample ``simple_server.py``
|
||||
|
||||
.. literalinclude:: ../../examples/Dockerfile
|
||||
|
||||
.. literalinclude:: ../../examples/docker-compose.yml
|
||||
|
||||
|
||||
Monitoring and Error Handling
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
``Sanic`` provides an extendable bare minimum implementation of a global exception handler via
|
||||
:class:`sanic.handlers.ErrorHandler`. This example shows how to extend it to enable some custom behaviors.
|
||||
|
||||
.. literalinclude:: ../../examples/exception_monitoring.py
|
||||
|
||||
Monitoring using external Service Providers
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
* `LogDNA <https://logdna.com/>`_
|
||||
|
||||
.. literalinclude:: ../../examples/logdna_example.py
|
||||
|
||||
* `RayGun <https://raygun.com/>`_
|
||||
|
||||
.. literalinclude:: ../../examples/raygun_example.py
|
||||
|
||||
* `Rollbar <https://rollbar.com>`_
|
||||
|
||||
.. literalinclude:: ../../examples/rollbar_example.py
|
||||
|
||||
* `Sentry <http://sentry.io>`_
|
||||
|
||||
.. literalinclude:: ../../examples/sentry_example.py
|
||||
|
||||
|
||||
Security
|
||||
~~~~~~~~
|
||||
|
||||
The following sample code shows a simple decorator based authentication and authorization mechanism that can be setup
|
||||
to secure your ``sanic`` api endpoints.
|
||||
|
||||
.. literalinclude:: ../../examples/authorized_sanic.py
|
||||
|
||||
Sanic Websocket
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
``Sanic`` provides an ability to easily add a route and map it to a ``websocket`` handlers.
|
||||
|
||||
.. literalinclude:: ../../examples/websocket.html
|
||||
.. literalinclude:: ../../examples/websocket.py
|
||||
|
||||
vhost Suppport
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
.. literalinclude:: ../../examples/vhosts.py
|
||||
|
||||
Unit Testing With Parallel Test Run Support
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The following example shows you how to get up and running with unit testing ``sanic`` application with parallel test
|
||||
execution support provided by the ``pytest-xdist`` plugin.
|
||||
|
||||
.. literalinclude:: ../../examples/pytest_xdist.py
|
||||
|
||||
|
||||
Amending Request Object
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``request`` object in ``Sanic`` is a kind of ``dict`` object, this means that ``request`` object can be manipulated as a regular ``dict`` object.
|
||||
|
||||
.. literalinclude:: ../../examples/amending_request_object.py
|
||||
|
||||
For more examples and useful samples please visit the `Huge-Sanic's GitHub Page <https://github.com/huge-success/sanic/tree/master/examples>`_
|
||||
@@ -1,92 +0,0 @@
|
||||
Exceptions
|
||||
==========
|
||||
|
||||
Exceptions can be thrown from within request handlers and will automatically be
|
||||
handled by Sanic. Exceptions take a message as their first argument, and can
|
||||
also take a status code to be passed back in the HTTP response.
|
||||
|
||||
Throwing an exception
|
||||
---------------------
|
||||
|
||||
To throw an exception, simply `raise` the relevant exception from the
|
||||
`sanic.exceptions` module.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.exceptions import ServerError
|
||||
|
||||
@app.route('/killme')
|
||||
async def i_am_ready_to_die(request):
|
||||
raise ServerError("Something bad happened", status_code=500)
|
||||
|
||||
You can also use the `abort` function with the appropriate status code:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.exceptions import abort
|
||||
from sanic.response import text
|
||||
|
||||
@app.route('/youshallnotpass')
|
||||
async def no_no(request):
|
||||
abort(401)
|
||||
# this won't happen
|
||||
text("OK")
|
||||
|
||||
Handling exceptions
|
||||
-------------------
|
||||
|
||||
To override Sanic's default handling of an exception, the `@app.exception`
|
||||
decorator is used. The decorator expects a list of exceptions to handle as
|
||||
arguments. You can pass `SanicException` to catch them all! The decorated
|
||||
exception handler function must take a `Request` and `Exception` object as
|
||||
arguments.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
from sanic.exceptions import NotFound
|
||||
|
||||
@app.exception(NotFound)
|
||||
async def ignore_404s(request, exception):
|
||||
return text("Yep, I totally found the page: {}".format(request.url))
|
||||
|
||||
You can also add an exception handler as such:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
|
||||
async def server_error_handler(request, exception):
|
||||
return text("Oops, server error", status=500)
|
||||
|
||||
app = Sanic()
|
||||
app.error_handler.add(Exception, server_error_handler)
|
||||
|
||||
In some cases, you might want to add some more error handling
|
||||
functionality to what is provided by default. In that case, you
|
||||
can subclass Sanic's default error handler as such:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.handlers import ErrorHandler
|
||||
|
||||
class CustomErrorHandler(ErrorHandler):
|
||||
def default(self, request, exception):
|
||||
''' handles errors that have no error handlers assigned '''
|
||||
# You custom error handling logic...
|
||||
return super().default(request, exception)
|
||||
|
||||
app = Sanic()
|
||||
app.error_handler = CustomErrorHandler()
|
||||
|
||||
Useful exceptions
|
||||
-----------------
|
||||
|
||||
Some of the most useful exceptions are presented below:
|
||||
|
||||
- `NotFound`: called when a suitable route for the request isn't found.
|
||||
- `ServerError`: called when something goes wrong inside the server. This
|
||||
usually occurs if there is an exception raised in user code.
|
||||
|
||||
See the `sanic.exceptions` module for the full list of exceptions to throw.
|
||||
@@ -1,4 +0,0 @@
|
||||
Extensions
|
||||
==========
|
||||
|
||||
Moved to the `awesome-sanic <https://github.com/mekicha/awesome-sanic>`_ list.
|
||||
@@ -1,62 +0,0 @@
|
||||
Getting Started
|
||||
===============
|
||||
|
||||
Make sure you have both `pip <https://pip.pypa.io/en/stable/installing/>`_ and at
|
||||
least version 3.6 of Python before starting. Sanic uses the new `async`/`await`
|
||||
syntax, so earlier versions of python won't work.
|
||||
|
||||
1. Install Sanic
|
||||
----------------
|
||||
|
||||
> If you are running on a clean install of Fedora 28 or above, please make sure you have the ``redhat-rpm-config`` package installed in case if you want to use ``sanic`` with ``ujson`` dependency.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip3 install sanic
|
||||
|
||||
To install sanic without `uvloop` or `ujson` using bash, you can provide either or both of these environmental variables
|
||||
using any truthy string like `'y', 'yes', 't', 'true', 'on', '1'` and setting the `SANIC_NO_X` (`X` = `UVLOOP`/`UJSON`)
|
||||
to true will stop that features installation.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
SANIC_NO_UVLOOP=true SANIC_NO_UJSON=true pip3 install sanic
|
||||
|
||||
You can also install Sanic from `conda-forge <https://anaconda.org/conda-forge/sanic>`_
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
conda config --add channels conda-forge
|
||||
conda install sanic
|
||||
|
||||
2. Create a file called `main.py`
|
||||
---------------------------------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic()
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
3. Run the server
|
||||
-----------------
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
python3 main.py
|
||||
|
||||
4. Check your browser
|
||||
---------------------
|
||||
|
||||
Open the address `http://0.0.0.0:8000 <http://0.0.0.0:8000>`_ in your web browser. You should see
|
||||
the message *Hello world!*.
|
||||
|
||||
You now have a working Sanic server!
|
||||
@@ -1,30 +0,0 @@
|
||||
Sanic
|
||||
=================================
|
||||
|
||||
Sanic is a Python 3.6+ 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.
|
||||
|
||||
The goal of the project is to provide a simple way to get up and running a highly performant HTTP server that is easy to build, to expand, and ultimately to scale.
|
||||
|
||||
Sanic is developed `on GitHub <https://github.com/channelcat/sanic/>`_. Contributions are welcome!
|
||||
|
||||
Sanic aspires to be simple
|
||||
---------------------------
|
||||
|
||||
.. code:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic()
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
.. note::
|
||||
|
||||
Sanic does not support Python 3.5 from version 19.6 and forward. However, version 18.12LTS is supported thru
|
||||
December 2020. Official Python support for version 3.5 is set to expire in September 2020.
|
||||
@@ -1,103 +0,0 @@
|
||||
Logging
|
||||
=======
|
||||
|
||||
Sanic allows you to do different types of logging (access log, error
|
||||
log) on the requests based on the `python3 logging API`_. You should
|
||||
have some basic knowledge on python3 logging if you want to create a new
|
||||
configuration.
|
||||
|
||||
Quick Start
|
||||
~~~~~~~~~~~
|
||||
|
||||
A simple example using default settings would be like this:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.log import logger
|
||||
from sanic.response import text
|
||||
|
||||
app = Sanic('test')
|
||||
|
||||
@app.route('/')
|
||||
async def test(request):
|
||||
logger.info('Here is your log')
|
||||
return text('Hello World!')
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, access_log=True)
|
||||
|
||||
After the server is running, you can see some messages looks like:
|
||||
|
||||
::
|
||||
|
||||
[2018-11-06 21:16:53 +0800] [24622] [INFO] Goin' Fast @ http://127.0.0.1:8000
|
||||
[2018-11-06 21:16:53 +0800] [24667] [INFO] Starting worker [24667]
|
||||
|
||||
You can send a request to server and it will print the log messages:
|
||||
|
||||
::
|
||||
|
||||
[2018-11-06 21:18:53 +0800] [25685] [INFO] Here is your log
|
||||
[2018-11-06 21:18:53 +0800] - (sanic.access)[INFO][127.0.0.1:57038]: GET http://localhost:8000/ 200 12
|
||||
|
||||
To use your own logging config, simply use
|
||||
``logging.config.dictConfig``, or pass ``log_config`` when you
|
||||
initialize ``Sanic`` app:
|
||||
|
||||
.. code:: python
|
||||
|
||||
app = Sanic('test', log_config=LOGGING_CONFIG)
|
||||
|
||||
And to close logging, simply assign access_log=False:
|
||||
|
||||
.. code:: python
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(access_log=False)
|
||||
|
||||
This would skip calling logging functions when handling requests. And
|
||||
you could even do further in production to gain extra speed:
|
||||
|
||||
.. code:: python
|
||||
|
||||
if __name__ == "__main__":
|
||||
# disable debug messages
|
||||
app.run(debug=False, access_log=False)
|
||||
|
||||
Configuration
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
By default, ``log_config`` parameter is set to use
|
||||
``sanic.log.LOGGING_CONFIG_DEFAULTS`` dictionary for configuration.
|
||||
|
||||
There are three ``loggers`` used in sanic, and **must be defined if you
|
||||
want to create your own logging configuration**:
|
||||
|
||||
================ ==============================
|
||||
Logger Name Usecase
|
||||
================ ==============================
|
||||
``sanic.root`` Used to log internal messages.
|
||||
``sanic.error`` Used to log error logs.
|
||||
``sanic.access`` Used to log access logs.
|
||||
================ ==============================
|
||||
|
||||
Log format:
|
||||
^^^^^^^^^^^
|
||||
|
||||
In addition to default parameters provided by python (``asctime``,
|
||||
``levelname``, ``message``), Sanic provides additional parameters for
|
||||
access logger with:
|
||||
|
||||
===================== ========================================== ========
|
||||
Log Context Parameter Parameter Value Datatype
|
||||
===================== ========================================== ========
|
||||
``host`` ``request.ip`` str
|
||||
``request`` ``request.method`` + " " + ``request.url`` str
|
||||
``status`` ``response.status`` int
|
||||
``byte`` ``len(response.body)`` int
|
||||
===================== ========================================== ========
|
||||
|
||||
The default access log format is ``%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: %(request)s %(message)s %(status)d %(byte)d``
|
||||
|
||||
.. _python3 logging API: https://docs.python.org/3/howto/logging.html
|
||||
@@ -1,177 +0,0 @@
|
||||
Middleware And Listeners
|
||||
========================
|
||||
|
||||
Middleware are functions which are executed before or after requests to the
|
||||
server. They can be used to modify the *request to* or *response from*
|
||||
user-defined handler functions.
|
||||
|
||||
Additionally, Sanic provides listeners which allow you to run code at various points of your application's lifecycle.
|
||||
|
||||
Middleware
|
||||
----------
|
||||
|
||||
There are two types of middleware: request and response. Both are declared
|
||||
using the `@app.middleware` decorator, with the decorator's parameter being a
|
||||
string representing its type: `'request'` or `'response'`.
|
||||
|
||||
* Request middleware receives only the `request` as argument.
|
||||
* Response middleware receives both the `request` and `response`.
|
||||
|
||||
The simplest middleware doesn't modify the request or response at all:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.middleware('request')
|
||||
async def print_on_request(request):
|
||||
print("I print when a request is received by the server")
|
||||
|
||||
@app.middleware('response')
|
||||
async def print_on_response(request, response):
|
||||
print("I print when a response is returned by the server")
|
||||
|
||||
Modifying the request or response
|
||||
---------------------------------
|
||||
|
||||
Middleware can modify the request or response parameter it is given, *as long
|
||||
as it does not return it*. The following example shows a practical use-case for
|
||||
this.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
|
||||
@app.middleware('request')
|
||||
async def add_key(request):
|
||||
# Arbitrary data may be stored in request context:
|
||||
request.ctx.foo = 'bar'
|
||||
|
||||
|
||||
@app.middleware('response')
|
||||
async def custom_banner(request, response):
|
||||
response.headers["Server"] = "Fake-Server"
|
||||
|
||||
|
||||
@app.middleware('response')
|
||||
async def prevent_xss(request, response):
|
||||
response.headers["x-xss-protection"] = "1; mode=block"
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def index(request):
|
||||
return sanic.response.text(request.ctx.foo)
|
||||
|
||||
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
The three middlewares are executed in order:
|
||||
|
||||
1. The first request middleware **add_key** adds a new key `foo` into request context.
|
||||
2. Request is routed to handler **index**, which gets the key from context and returns a text response.
|
||||
3. The first response middleware **custom_banner** changes the HTTP response header *Server* to say *Fake-Server*
|
||||
4. The second response middleware **prevent_xss** adds the HTTP header for preventing Cross-Site-Scripting (XSS) attacks.
|
||||
|
||||
Responding early
|
||||
----------------
|
||||
|
||||
If middleware returns a `HTTPResponse` object, the request will stop processing
|
||||
and the response will be returned. If this occurs to a request before the
|
||||
relevant user route handler is reached, the handler will never be called.
|
||||
Returning a response will also prevent any further middleware from running.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.middleware('request')
|
||||
async def halt_request(request):
|
||||
return text('I halted the request')
|
||||
|
||||
@app.middleware('response')
|
||||
async def halt_response(request, response):
|
||||
return text('I halted the response')
|
||||
|
||||
Custom context
|
||||
--------------
|
||||
|
||||
Arbitrary data may be stored in `request.ctx`. A typical use case
|
||||
would be to store the user object acquired from database in an authentication
|
||||
middleware. Keys added are accessible to all later middleware as well as
|
||||
the handler over the duration of the request.
|
||||
|
||||
Custom context is reserved for applications and extensions. Sanic itself makes
|
||||
no use of it.
|
||||
|
||||
Listeners
|
||||
---------
|
||||
|
||||
If you want to execute startup/teardown code as your server starts or closes, you can use the following listeners:
|
||||
|
||||
- `before_server_start`
|
||||
- `after_server_start`
|
||||
- `before_server_stop`
|
||||
- `after_server_stop`
|
||||
|
||||
These listeners are implemented as decorators on functions which accept the app object as well as the asyncio loop.
|
||||
|
||||
For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.listener('before_server_start')
|
||||
async def setup_db(app, loop):
|
||||
app.db = await db_setup()
|
||||
|
||||
@app.listener('after_server_start')
|
||||
async def notify_server_started(app, loop):
|
||||
print('Server successfully started!')
|
||||
|
||||
@app.listener('before_server_stop')
|
||||
async def notify_server_stopping(app, loop):
|
||||
print('Server shutting down!')
|
||||
|
||||
@app.listener('after_server_stop')
|
||||
async def close_db(app, loop):
|
||||
await app.db.close()
|
||||
|
||||
It's also possible to register a listener using the `register_listener` method.
|
||||
This may be useful if you define your listeners in another module besides
|
||||
the one you instantiate your app in.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic()
|
||||
|
||||
async def setup_db(app, loop):
|
||||
app.db = await db_setup()
|
||||
|
||||
app.register_listener(setup_db, 'before_server_start')
|
||||
|
||||
If you want to schedule a background task to run after the loop has started,
|
||||
Sanic provides the `add_task` method to easily do so.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def notify_server_started_after_five_seconds():
|
||||
await asyncio.sleep(5)
|
||||
print('Server successfully started!')
|
||||
|
||||
app.add_task(notify_server_started_after_five_seconds())
|
||||
|
||||
Sanic will attempt to automatically inject the app, passing it as an argument to the task:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def notify_server_started_after_five_seconds(app):
|
||||
await asyncio.sleep(5)
|
||||
print(app.name)
|
||||
|
||||
app.add_task(notify_server_started_after_five_seconds)
|
||||
|
||||
Or you can pass the app explicitly for the same effect:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def notify_server_started_after_five_seconds(app):
|
||||
await asyncio.sleep(5)
|
||||
print(app.name)
|
||||
|
||||
app.add_task(notify_server_started_after_five_seconds(app))
|
||||
@@ -1,274 +0,0 @@
|
||||
Request Data
|
||||
============
|
||||
|
||||
When an endpoint receives a HTTP request, the route function is passed a
|
||||
`Request` object.
|
||||
|
||||
The following variables are accessible as properties on `Request` objects:
|
||||
|
||||
- `json` (any) - JSON body
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
|
||||
@app.route("/json")
|
||||
def post_json(request):
|
||||
return json({ "received": True, "message": request.json })
|
||||
|
||||
|
||||
- `args` (dict) - Query string variables. A query string is the section of a
|
||||
URL that resembles ``?key1=value1&key2=value2``.
|
||||
If that URL were to be parsed, the `args` dictionary would look like `{'key1': ['value1'], 'key2': ['value2']}`.
|
||||
The request's `query_string` variable holds the unparsed string value. Property is providing the default parsing
|
||||
strategy. If you would like to change it look to the section below (`Changing the default parsing rules of the queryset`).
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
|
||||
@app.route("/query_string")
|
||||
def query_string(request):
|
||||
return json({ "parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string })
|
||||
|
||||
- `query_args` (list) - On many cases you would need to access the url arguments in
|
||||
a less packed form. `query_args` is the list of `(key, value)` tuples.
|
||||
Property is providing the default parsing strategy. If you would like to change it look to the section below
|
||||
(`Changing the default parsing rules of the queryset`). For the same previous URL queryset `?key1=value1&key2=value2`,
|
||||
the `query_args` list would look like `[('key1', 'value1'), ('key2', 'value2')]`. And in case of the multiple params
|
||||
with the same key like `?key1=value1&key2=value2&key1=value3` the `query_args` list would look like
|
||||
`[('key1', 'value1'), ('key2', 'value2'), ('key1', 'value3')]`.
|
||||
|
||||
The difference between Request.args and Request.query_args for the queryset `?key1=value1&key2=value2&key1=value3`
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
|
||||
@app.route("/test_request_args")
|
||||
async def test_request_args(request):
|
||||
return json({
|
||||
"parsed": True,
|
||||
"url": request.url,
|
||||
"query_string": request.query_string,
|
||||
"args": request.args,
|
||||
"raw_args": request.raw_args,
|
||||
"query_args": request.query_args,
|
||||
})
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
Output
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"parsed":true,
|
||||
"url":"http:\/\/0.0.0.0:8000\/test_request_args?key1=value1&key2=value2&key1=value3",
|
||||
"query_string":"key1=value1&key2=value2&key1=value3",
|
||||
"args":{"key1":["value1","value3"],"key2":["value2"]},
|
||||
"raw_args":{"key1":"value1","key2":"value2"},
|
||||
"query_args":[["key1","value1"],["key2","value2"],["key1","value3"]]
|
||||
}
|
||||
|
||||
- `raw_args` contains only the first entry of `key1`. Will be deprecated in the future versions.
|
||||
|
||||
- `files` (dictionary of `File` objects) - List of files that have a name, body, and type
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
|
||||
@app.route("/files")
|
||||
def post_json(request):
|
||||
test_file = request.files.get('test')
|
||||
|
||||
file_parameters = {
|
||||
'body': test_file.body,
|
||||
'name': test_file.name,
|
||||
'type': test_file.type,
|
||||
}
|
||||
|
||||
return json({ "received": True, "file_names": request.files.keys(), "test_file_parameters": file_parameters })
|
||||
|
||||
- `form` (dict) - Posted form variables.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
|
||||
@app.route("/form")
|
||||
def post_json(request):
|
||||
return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })
|
||||
|
||||
- `body` (bytes) - Posted raw body. This property allows retrieval of the
|
||||
request's raw data, regardless of content type.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route("/users", methods=["POST",])
|
||||
def create_user(request):
|
||||
return text("You are trying to create a user with the following POST: %s" % request.body)
|
||||
|
||||
|
||||
- `headers` (dict) - A case-insensitive dictionary that contains the request headers.
|
||||
|
||||
- `method` (str) - HTTP method of the request (ie `GET`, `POST`).
|
||||
|
||||
- `ip` (str) - IP address of the requester.
|
||||
|
||||
- `port` (str) - Port address of the requester.
|
||||
|
||||
- `socket` (tuple) - (IP, port) of the requester.
|
||||
|
||||
- `app` - a reference to the Sanic application object that is handling this request. This is useful when inside blueprints or other handlers in modules that do not have access to the global `app` object.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
from sanic import Blueprint
|
||||
|
||||
bp = Blueprint('my_blueprint')
|
||||
|
||||
@bp.route('/')
|
||||
async def bp_root(request):
|
||||
if request.app.config['DEBUG']:
|
||||
return json({'status': 'debug'})
|
||||
else:
|
||||
return json({'status': 'production'})
|
||||
|
||||
- `url`: The full URL of the request, ie: `http://localhost:8000/posts/1/?foo=bar`
|
||||
- `scheme`: The URL scheme associated with the request: 'http|https|ws|wss' or arbitrary value given by the headers.
|
||||
- `host`: The host associated with the request(which in the `Host` header): `localhost:8080`
|
||||
- `server_name`: The hostname of the server, without port number. the value is seeked in this order: `config.SERVER_NAME`, `x-forwarded-host` header, :func:`Request.host`
|
||||
- `server_port`: Like `server_name`. Seeked in this order: `x-forwarded-port` header, :func:`Request.host`, actual port used by the transport layer socket.
|
||||
- `path`: The path of the request: `/posts/1/`
|
||||
- `query_string`: The query string of the request: `foo=bar` or a blank string `''`
|
||||
- `uri_template`: Template for matching route handler: `/posts/<id>/`
|
||||
- `token`: The value of Authorization header: `Basic YWRtaW46YWRtaW4=`
|
||||
|
||||
- `url_for`: Just like `sanic.Sanic.url_for`, but automatically determine `scheme` and `netloc` base on the request. Since this method is aiming to generate correct schema & netloc, `_external` is implied.
|
||||
|
||||
|
||||
Changing the default parsing rules of the queryset
|
||||
--------------------------------------------------
|
||||
|
||||
The default parameters that are using internally in `args` and `query_args` properties to parse queryset:
|
||||
|
||||
- `keep_blank_values` (bool): `False` - flag indicating whether blank values in
|
||||
percent-encoded queries should be treated as blank strings.
|
||||
A true value indicates that blanks should be retained as blank
|
||||
strings. The default false value indicates that blank values
|
||||
are to be ignored and treated as if they were not included.
|
||||
- `strict_parsing` (bool): `False` - flag indicating what to do with parsing errors. If
|
||||
false (the default), errors are silently ignored. If true,
|
||||
errors raise a ValueError exception.
|
||||
- `encoding` and `errors` (str): 'utf-8' and 'replace' - specify how to decode percent-encoded sequences
|
||||
into Unicode characters, as accepted by the bytes.decode() method.
|
||||
|
||||
If you would like to change that default parameters you could call `get_args` and `get_query_args` methods
|
||||
with the new values.
|
||||
|
||||
For the queryset `/?test1=value1&test2=&test3=value3`:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
|
||||
@app.route("/query_string")
|
||||
def query_string(request):
|
||||
args_with_blank_values = request.get_args(keep_blank_values=True)
|
||||
return json({
|
||||
"parsed": True,
|
||||
"url": request.url,
|
||||
"args_with_blank_values": args_with_blank_values,
|
||||
"query_string": request.query_string
|
||||
})
|
||||
|
||||
The output will be:
|
||||
|
||||
.. code-block:: JSON
|
||||
|
||||
{
|
||||
"parsed": true,
|
||||
"url": "http:\/\/0.0.0.0:8000\/query_string?test1=value1&test2=&test3=value3",
|
||||
"args_with_blank_values": {"test1": ["value1"], "test2": "", "test3": ["value3"]},
|
||||
"query_string": "test1=value1&test2=&test3=value3"
|
||||
}
|
||||
|
||||
Accessing values using `get` and `getlist`
|
||||
------------------------------------------
|
||||
|
||||
The `request.args` returns a subclass of `dict` called `RequestParameters`.
|
||||
The key difference when using this object is the distinction between the `get` and `getlist` methods.
|
||||
|
||||
- `get(key, default=None)` operates as normal, except that when the value of
|
||||
the given key is a list, *only the first item is returned*.
|
||||
- `getlist(key, default=None)` operates as normal, *returning the entire list*.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.request import RequestParameters
|
||||
|
||||
args = RequestParameters()
|
||||
args['titles'] = ['Post 1', 'Post 2']
|
||||
|
||||
args.get('titles') # => 'Post 1'
|
||||
|
||||
args.getlist('titles') # => ['Post 1', 'Post 2']
|
||||
|
||||
.. code-block:: python
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
app = Sanic(name="example")
|
||||
|
||||
@app.route("/")
|
||||
def get_handler(request):
|
||||
return json({
|
||||
"p1": request.args.getlist("p1")
|
||||
})
|
||||
|
||||
Accessing the handler name with the request.endpoint attribute
|
||||
--------------------------------------------------------------
|
||||
|
||||
The `request.endpoint` attribute holds the handler's name. For instance, the below
|
||||
route will return "hello".
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
from sanic import Sanic
|
||||
|
||||
app = Sanic()
|
||||
|
||||
@app.get("/")
|
||||
def hello(request):
|
||||
return text(request.endpoint)
|
||||
|
||||
Or, with a blueprint it will be include both, separated by a period. For example, the below route would return foo.bar:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic import Blueprint
|
||||
from sanic.response import text
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
blueprint = Blueprint('foo')
|
||||
|
||||
@blueprint.get('/')
|
||||
async def bar(request):
|
||||
return text(request.endpoint)
|
||||
|
||||
app.blueprint(blueprint)
|
||||
|
||||
app.run(host="0.0.0.0", port=8000, debug=True)
|
||||
@@ -1,126 +0,0 @@
|
||||
Response
|
||||
========
|
||||
|
||||
Use functions in `sanic.response` module to create responses.
|
||||
|
||||
Plain Text
|
||||
----------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/text')
|
||||
def handle_request(request):
|
||||
return response.text('Hello world!')
|
||||
|
||||
HTML
|
||||
----
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/html')
|
||||
def handle_request(request):
|
||||
return response.html('<p>Hello world!</p>')
|
||||
|
||||
JSON
|
||||
----
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/json')
|
||||
def handle_request(request):
|
||||
return response.json({'message': 'Hello world!'})
|
||||
|
||||
File
|
||||
----
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/file')
|
||||
async def handle_request(request):
|
||||
return await response.file('/srv/www/whatever.png')
|
||||
|
||||
Streaming
|
||||
---------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
@app.route("/streaming")
|
||||
async def index(request):
|
||||
async def streaming_fn(response):
|
||||
await response.write('foo')
|
||||
await response.write('bar')
|
||||
return response.stream(streaming_fn, content_type='text/plain')
|
||||
|
||||
See `Streaming <streaming.html>`_ for more information.
|
||||
|
||||
File Streaming
|
||||
--------------
|
||||
|
||||
For large files, a combination of File and Streaming above
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
@app.route('/big_file.png')
|
||||
async def handle_request(request):
|
||||
return await response.file_stream('/srv/www/whatever.png')
|
||||
|
||||
Redirect
|
||||
--------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/redirect')
|
||||
def handle_request(request):
|
||||
return response.redirect('/json')
|
||||
|
||||
Raw
|
||||
---
|
||||
|
||||
Response without encoding the body
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/raw')
|
||||
def handle_request(request):
|
||||
return response.raw(b'raw data')
|
||||
|
||||
Modify headers or status
|
||||
------------------------
|
||||
|
||||
To modify headers or status code, pass the `headers` or `status` argument to those functions:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/json')
|
||||
def handle_request(request):
|
||||
return response.json(
|
||||
{'message': 'Hello world!'},
|
||||
headers={'X-Served-By': 'sanic'},
|
||||
status=200
|
||||
)
|
||||
@@ -1,433 +0,0 @@
|
||||
Routing
|
||||
-------
|
||||
|
||||
Routing allows the user to specify handler functions for different URL endpoints.
|
||||
|
||||
A basic route looks like the following, where `app` is an instance of the
|
||||
`Sanic` class:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import json
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
return json({ "hello": "world" })
|
||||
|
||||
When the url `http://server.url/` is accessed (the base url of the server), the
|
||||
final `/` is matched by the router to the handler function, `test`, which then
|
||||
returns a JSON object.
|
||||
|
||||
Sanic handler functions must be defined using the `async def` syntax, as they
|
||||
are asynchronous functions.
|
||||
|
||||
Request parameters
|
||||
==================
|
||||
|
||||
Sanic comes with a basic router that supports request parameters.
|
||||
|
||||
To specify a parameter, surround it with angle quotes like so: `<PARAM>`.
|
||||
Request parameters will be passed to the route handler functions as keyword
|
||||
arguments.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route('/tag/<tag>')
|
||||
async def tag_handler(request, tag):
|
||||
return text('Tag - {}'.format(tag))
|
||||
|
||||
To specify a type for the parameter, add a `:type` after the parameter name,
|
||||
inside the quotes. If the parameter does not match the specified type, Sanic
|
||||
will throw a `NotFound` exception, resulting in a `404: Page not found` error
|
||||
on the URL.
|
||||
|
||||
Supported types
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
* `string`
|
||||
* "Bob"
|
||||
* "Python 3"
|
||||
* `int`
|
||||
* 10
|
||||
* 20
|
||||
* 30
|
||||
* -10
|
||||
* (No floats work here)
|
||||
* `number`
|
||||
* 1
|
||||
* 1.5
|
||||
* 10
|
||||
* -10
|
||||
* `alpha`
|
||||
* "Bob"
|
||||
* "Python"
|
||||
* (If it contains a symbol or a non alphanumeric character it will fail)
|
||||
* `path`
|
||||
* "hello"
|
||||
* "hello.text"
|
||||
* "hello world"
|
||||
* `uuid`
|
||||
* 123a123a-a12a-1a1a-a1a1-1a12a1a12345 (UUIDv4 Support)
|
||||
* `regex expression`
|
||||
|
||||
If no type is set then a string is expected. The argument given to the function will always be a string, independent of the type.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route('/string/<string_arg:string>')
|
||||
async def string_handler(request, string_arg):
|
||||
return text('String - {}'.format(string_arg))
|
||||
|
||||
@app.route('/int/<integer_arg:int>')
|
||||
async def integer_handler(request, integer_arg):
|
||||
return text('Integer - {}'.format(integer_arg))
|
||||
|
||||
@app.route('/number/<number_arg:number>')
|
||||
async def number_handler(request, number_arg):
|
||||
return text('Number - {}'.format(number_arg))
|
||||
|
||||
@app.route('/alpha/<alpha_arg:alpha>')
|
||||
async def number_handler(request, alpha_arg):
|
||||
return text('Alpha - {}'.format(alpha_arg))
|
||||
|
||||
@app.route('/path/<path_arg:path>')
|
||||
async def number_handler(request, path_arg):
|
||||
return text('Path - {}'.format(path_arg))
|
||||
|
||||
@app.route('/uuid/<uuid_arg:uuid>')
|
||||
async def number_handler(request, uuid_arg):
|
||||
return text('Uuid - {}'.format(uuid_arg))
|
||||
|
||||
@app.route('/person/<name:[A-z]+>')
|
||||
async def person_handler(request, name):
|
||||
return text('Person - {}'.format(name))
|
||||
|
||||
@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
|
||||
async def folder_handler(request, folder_id):
|
||||
return text('Folder - {}'.format(folder_id))
|
||||
|
||||
.. warning::
|
||||
|
||||
`str` is not a valid type tag. If you want `str` recognition then you must use `string`
|
||||
|
||||
HTTP request types
|
||||
==================
|
||||
|
||||
By default, a route defined on a URL will be available for only GET requests to that URL.
|
||||
However, the `@app.route` decorator accepts an optional parameter, `methods`,
|
||||
which allows the handler function to work with any of the HTTP methods in the list.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.route('/post', methods=['POST'])
|
||||
async def post_handler(request):
|
||||
return text('POST request - {}'.format(request.json))
|
||||
|
||||
@app.route('/get', methods=['GET'])
|
||||
async def get_handler(request):
|
||||
return text('GET request - {}'.format(request.args))
|
||||
|
||||
There is also an optional `host` argument (which can be a list or a string). This restricts a route to the host or hosts provided. If there is a also a route with no host, it will be the default.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.route('/get', methods=['GET'], host='example.com')
|
||||
async def get_handler(request):
|
||||
return text('GET request - {}'.format(request.args))
|
||||
|
||||
# if the host header doesn't match example.com, this route will be used
|
||||
@app.route('/get', methods=['GET'])
|
||||
async def get_handler(request):
|
||||
return text('GET request in default - {}'.format(request.args))
|
||||
|
||||
There are also shorthand method decorators:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
@app.post('/post')
|
||||
async def post_handler(request):
|
||||
return text('POST request - {}'.format(request.json))
|
||||
|
||||
@app.get('/get')
|
||||
async def get_handler(request):
|
||||
return text('GET request - {}'.format(request.args))
|
||||
|
||||
The `add_route` method
|
||||
======================
|
||||
|
||||
As we have seen, routes are often specified using the `@app.route` decorator.
|
||||
However, this decorator is really just a wrapper for the `app.add_route`
|
||||
method, which is used as follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import text
|
||||
|
||||
# Define the handler functions
|
||||
async def handler1(request):
|
||||
return text('OK')
|
||||
|
||||
async def handler2(request, name):
|
||||
return text('Folder - {}'.format(name))
|
||||
|
||||
async def person_handler2(request, name):
|
||||
return text('Person - {}'.format(name))
|
||||
|
||||
# Add each handler function as a route
|
||||
app.add_route(handler1, '/test')
|
||||
app.add_route(handler2, '/folder/<name>')
|
||||
app.add_route(person_handler2, '/person/<name:[A-z]>', methods=['GET'])
|
||||
|
||||
URL building with `url_for`
|
||||
===========================
|
||||
|
||||
Sanic provides a `url_for` method, to generate URLs based on the handler method name. This is useful if you want to avoid hardcoding url paths into your app; instead, you can just reference the handler name. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic.response import redirect
|
||||
|
||||
@app.route('/')
|
||||
async def index(request):
|
||||
# generate a URL for the endpoint `post_handler`
|
||||
url = app.url_for('post_handler', post_id=5)
|
||||
# the URL is `/posts/5`, redirect to it
|
||||
return redirect(url)
|
||||
|
||||
@app.route('/posts/<post_id>')
|
||||
async def post_handler(request, post_id):
|
||||
return text('Post - {}'.format(post_id))
|
||||
|
||||
Other things to keep in mind when using `url_for`:
|
||||
|
||||
- Keyword arguments passed to `url_for` that are not request parameters will be included in the URL's query string. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
url = app.url_for('post_handler', post_id=5, arg_one='one', arg_two='two')
|
||||
# /posts/5?arg_one=one&arg_two=two
|
||||
|
||||
- Multivalue argument can be passed to `url_for`. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two'])
|
||||
# /posts/5?arg_one=one&arg_one=two
|
||||
|
||||
- Also some special arguments (`_anchor`, `_external`, `_scheme`, `_method`, `_server`) passed to `url_for` will have special url building (`_method` is not supported now and will be ignored). For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
url = app.url_for('post_handler', post_id=5, arg_one='one', _anchor='anchor')
|
||||
# /posts/5?arg_one=one#anchor
|
||||
|
||||
url = app.url_for('post_handler', post_id=5, arg_one='one', _external=True)
|
||||
# //server/posts/5?arg_one=one
|
||||
# _external requires you to pass an argument _server or set SERVER_NAME in app.config if not url will be same as no _external
|
||||
|
||||
url = app.url_for('post_handler', post_id=5, arg_one='one', _scheme='http', _external=True)
|
||||
# http://server/posts/5?arg_one=one
|
||||
# when specifying _scheme, _external must be True
|
||||
|
||||
# you can pass all special arguments at once
|
||||
url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two'], arg_two=2, _anchor='anchor', _scheme='http', _external=True, _server='another_server:8888')
|
||||
# http://another_server:8888/posts/5?arg_one=one&arg_one=two&arg_two=2#anchor
|
||||
|
||||
- All valid parameters must be passed to `url_for` to build a URL. If a parameter is not supplied, or if a parameter does not match the specified type, a `URLBuildError` will be raised.
|
||||
|
||||
WebSocket routes
|
||||
================
|
||||
|
||||
Routes for the WebSocket protocol can be defined with the `@app.websocket`
|
||||
decorator:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.websocket('/feed')
|
||||
async def feed(request, ws):
|
||||
while True:
|
||||
data = 'hello!'
|
||||
print('Sending: ' + data)
|
||||
await ws.send(data)
|
||||
data = await ws.recv()
|
||||
print('Received: ' + data)
|
||||
|
||||
Alternatively, the `app.add_websocket_route` method can be used instead of the
|
||||
decorator:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def feed(request, ws):
|
||||
pass
|
||||
|
||||
app.add_websocket_route(my_websocket_handler, '/feed')
|
||||
|
||||
Handlers to a WebSocket route are invoked with the request as first argument, and a
|
||||
WebSocket protocol object as second argument. The protocol object has `send`
|
||||
and `recv` methods to send and receive data respectively.
|
||||
|
||||
WebSocket support requires the `websockets <https://github.com/aaugustin/websockets>`_
|
||||
package by Aymeric Augustin.
|
||||
|
||||
|
||||
About `strict_slashes`
|
||||
======================
|
||||
|
||||
You can make `routes` strict to trailing slash or not, it's configurable.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# provide default strict_slashes value for all routes
|
||||
app = Sanic('test_route_strict_slash', strict_slashes=True)
|
||||
|
||||
# you can also overwrite strict_slashes value for specific route
|
||||
@app.get('/get', strict_slashes=False)
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
# It also works for blueprints
|
||||
bp = Blueprint('test_bp_strict_slash', strict_slashes=True)
|
||||
|
||||
@bp.get('/bp/get', strict_slashes=False)
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
app.blueprint(bp)
|
||||
|
||||
The behavior of how the `strict_slashes` flag follows a defined hierarchy which decides if a specific route
|
||||
falls under the `strict_slashes` behavior.
|
||||
|
||||
| Route/
|
||||
| ├──Blueprint/
|
||||
| ├──Application/
|
||||
|
||||
Above hierarchy defines how the `strict_slashes` flag will behave. The first non `None` value of the `strict_slashes`
|
||||
found in the above order will be applied to the route in question.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic, Blueprint
|
||||
from sanic.response import text
|
||||
|
||||
app = Sanic("sample_strict_slashes", strict_slashes=True)
|
||||
|
||||
@app.get("/r1")
|
||||
def r1(request):
|
||||
return text("strict_slashes is applicable from App level")
|
||||
|
||||
@app.get("/r2", strict_slashes=False)
|
||||
def r2(request):
|
||||
return text("strict_slashes is not applicable due to False value set in route level")
|
||||
|
||||
bp = Blueprint("bp", strict_slashes=False)
|
||||
|
||||
@bp.get("/r3", strict_slashes=True)
|
||||
def r3(request):
|
||||
return text("strict_slashes applicable from blueprint route level")
|
||||
|
||||
bp1 = Blueprint("bp1", strict_slashes=True)
|
||||
|
||||
@bp.get("/r4")
|
||||
def r3(request):
|
||||
return text("strict_slashes applicable from blueprint level")
|
||||
|
||||
User defined route name
|
||||
=======================
|
||||
|
||||
A custom route name can be used by passing a `name` argument while registering the route which will
|
||||
override the default route name generated using the `handler.__name__` attribute.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic('test_named_route')
|
||||
|
||||
@app.get('/get', name='get_handler')
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
# then you need use `app.url_for('get_handler')`
|
||||
# instead of # `app.url_for('handler')`
|
||||
|
||||
# It also works for blueprints
|
||||
bp = Blueprint('test_named_bp')
|
||||
|
||||
@bp.get('/bp/get', name='get_handler')
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
app.blueprint(bp)
|
||||
|
||||
# then you need use `app.url_for('test_named_bp.get_handler')`
|
||||
# instead of `app.url_for('test_named_bp.handler')`
|
||||
|
||||
# different names can be used for same url with different methods
|
||||
|
||||
@app.get('/test', name='route_test')
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
@app.post('/test', name='route_post')
|
||||
def handler2(request):
|
||||
return text('OK POST')
|
||||
|
||||
@app.put('/test', name='route_put')
|
||||
def handler3(request):
|
||||
return text('OK PUT')
|
||||
|
||||
# below url are the same, you can use any of them
|
||||
# '/test'
|
||||
app.url_for('route_test')
|
||||
# app.url_for('route_post')
|
||||
# app.url_for('route_put')
|
||||
|
||||
# for same handler name with different methods
|
||||
# you need specify the name (it's url_for issue)
|
||||
@app.get('/get')
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
@app.post('/post', name='post_handler')
|
||||
def handler(request):
|
||||
return text('OK')
|
||||
|
||||
# then
|
||||
# app.url_for('handler') == '/get'
|
||||
# app.url_for('post_handler') == '/post'
|
||||
|
||||
Build URL for static files
|
||||
==========================
|
||||
|
||||
Sanic supports using `url_for` method to build static file urls. In case if the static url
|
||||
is pointing to a directory, `filename` parameter to the `url_for` can be ignored. q
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
app = Sanic('test_static')
|
||||
app.static('/static', './static')
|
||||
app.static('/uploads', './uploads', name='uploads')
|
||||
app.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
|
||||
|
||||
bp = Blueprint('bp', url_prefix='bp')
|
||||
bp.static('/static', './static')
|
||||
bp.static('/uploads', './uploads', name='uploads')
|
||||
bp.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
|
||||
app.blueprint(bp)
|
||||
|
||||
# then build the url
|
||||
app.url_for('static', filename='file.txt') == '/static/file.txt'
|
||||
app.url_for('static', name='static', filename='file.txt') == '/static/file.txt'
|
||||
app.url_for('static', name='uploads', filename='file.txt') == '/uploads/file.txt'
|
||||
app.url_for('static', name='best_png') == '/the_best.png'
|
||||
|
||||
# blueprint url building
|
||||
app.url_for('static', name='bp.static', filename='file.txt') == '/bp/static/file.txt'
|
||||
app.url_for('static', name='bp.uploads', filename='file.txt') == '/bp/uploads/file.txt'
|
||||
app.url_for('static', name='bp.best_png') == '/bp/static/the_best.png'
|
||||
@@ -1,66 +0,0 @@
|
||||
Sockets
|
||||
=======
|
||||
|
||||
Sanic can use the python
|
||||
`socket module <https://docs.python.org/3/library/socket.html>`_ to accommodate
|
||||
non IPv4 sockets.
|
||||
|
||||
IPv6 example:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
import socket
|
||||
|
||||
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||
sock.bind(('::', 7777))
|
||||
|
||||
app = Sanic()
|
||||
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(sock=sock)
|
||||
|
||||
to test IPv6 ``curl -g -6 "http://[::1]:7777/"``
|
||||
|
||||
|
||||
UNIX socket example:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import signal
|
||||
import sys
|
||||
import socket
|
||||
import os
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
|
||||
|
||||
server_socket = '/tmp/sanic.sock'
|
||||
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.bind(server_socket)
|
||||
|
||||
app = Sanic()
|
||||
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
return json({"hello": "world"})
|
||||
|
||||
|
||||
def signal_handler(sig, frame):
|
||||
print('Exiting')
|
||||
os.unlink(server_socket)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(sock=sock)
|
||||
|
||||
to test UNIX: ``curl -v --unix-socket /tmp/sanic.sock http://localhost/hello``
|
||||
@@ -1,20 +0,0 @@
|
||||
SSL Example
|
||||
-----------
|
||||
|
||||
Optionally pass in an SSLContext:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import ssl
|
||||
context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
|
||||
context.load_cert_chain("/path/to/cert", keyfile="/path/to/keyfile")
|
||||
|
||||
app.run(host="0.0.0.0", port=8443, ssl=context)
|
||||
|
||||
You can also pass in the locations of a certificate and key as a dictionary:
|
||||
|
||||
|
||||
.. code:: python
|
||||
|
||||
ssl = {'cert': "/path/to/cert", 'key': "/path/to/keyfile"}
|
||||
app.run(host="0.0.0.0", port=8443, ssl=ssl)
|
||||
@@ -1,92 +0,0 @@
|
||||
Static Files
|
||||
============
|
||||
|
||||
Static files and directories, such as an image file, are served by Sanic when
|
||||
registered with the `app.static()` method. The method takes an endpoint URL and a
|
||||
filename. The file specified will then be accessible via the given endpoint.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.blueprints import Blueprint
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
# Serves files from the static folder to the URL /static
|
||||
app.static('/static', './static')
|
||||
# use url_for to build the url, name defaults to 'static' and can be ignored
|
||||
app.url_for('static', filename='file.txt') == '/static/file.txt'
|
||||
app.url_for('static', name='static', filename='file.txt') == '/static/file.txt'
|
||||
|
||||
# Serves the file /home/ubuntu/test.png when the URL /the_best.png
|
||||
# is requested
|
||||
app.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
|
||||
|
||||
# you can use url_for to build the static file url
|
||||
# you can ignore name and filename parameters if you don't define it
|
||||
app.url_for('static', name='best_png') == '/the_best.png'
|
||||
app.url_for('static', name='best_png', filename='any') == '/the_best.png'
|
||||
|
||||
# you need define the name for other static files
|
||||
app.static('/another.png', '/home/ubuntu/another.png', name='another')
|
||||
app.url_for('static', name='another') == '/another.png'
|
||||
app.url_for('static', name='another', filename='any') == '/another.png'
|
||||
|
||||
# also, you can use static for blueprint
|
||||
bp = Blueprint('bp', url_prefix='/bp')
|
||||
bp.static('/static', './static')
|
||||
|
||||
# specify a different content_type for your files
|
||||
# such as adding 'charset'
|
||||
app.static('/', '/public/index.html', content_type="text/html; charset=utf-8")
|
||||
|
||||
# servers the file directly
|
||||
bp.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
|
||||
app.blueprint(bp)
|
||||
|
||||
app.url_for('static', name='bp.static', filename='file.txt') == '/bp/static/file.txt'
|
||||
app.url_for('static', name='bp.best_png') == '/bp/test_best.png'
|
||||
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
> **Note:** Sanic does not provide directory index when you serve a static directory.
|
||||
|
||||
Virtual Host
|
||||
------------
|
||||
|
||||
The `app.static()` method also support **virtual host**. You can serve your static files with specific **virtual host** with `host` argument. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
app.static('/static', './static')
|
||||
app.static('/example_static', './example_static', host='www.example.com')
|
||||
|
||||
Streaming Large File
|
||||
--------------------
|
||||
|
||||
In some cases, you might server large file(ex: videos, images, etc.) with Sanic. You can choose to use **streaming file** rather than download directly.
|
||||
|
||||
Here is an example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
app.static('/large_video.mp4', '/home/ubuntu/large_video.mp4', stream_large_files=True)
|
||||
|
||||
When `stream_large_files` is `True`, Sanic will use `file_stream()` instead of `file()` to serve static files. This will use **1KB** as the default chunk size. And, if needed, you can also use a custom chunk size. For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
chunk_size = 1024 * 1024 * 8 # Set chunk size to 8KB
|
||||
app.static('/large_video.mp4', '/home/ubuntu/large_video.mp4', stream_large_files=chunk_size)
|
||||
@@ -1,147 +0,0 @@
|
||||
Streaming
|
||||
=========
|
||||
|
||||
Request Streaming
|
||||
-----------------
|
||||
|
||||
Sanic allows you to get request data by stream, as below. When the request ends, `await request.stream.read()` returns `None`. Only post, put and patch decorator have stream argument.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
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
|
||||
|
||||
bp = Blueprint('blueprint_request_stream')
|
||||
app = Sanic('request_stream')
|
||||
|
||||
|
||||
class SimpleView(HTTPMethodView):
|
||||
|
||||
@stream_decorator
|
||||
async def post(self, request):
|
||||
result = ''
|
||||
while True:
|
||||
body = await request.stream.read()
|
||||
if body is None:
|
||||
break
|
||||
result += body.decode('utf-8')
|
||||
return text(result)
|
||||
|
||||
|
||||
@app.post('/stream', stream=True)
|
||||
async def handler(request):
|
||||
async def streaming(response):
|
||||
while True:
|
||||
body = await request.stream.read()
|
||||
if body is None:
|
||||
break
|
||||
body = body.decode('utf-8').replace('1', 'A')
|
||||
await response.write(body)
|
||||
return stream(streaming)
|
||||
|
||||
|
||||
@bp.put('/bp_stream', stream=True)
|
||||
async def bp_put_handler(request):
|
||||
result = ''
|
||||
while True:
|
||||
body = await request.stream.read()
|
||||
if body is None:
|
||||
break
|
||||
result += body.decode('utf-8').replace('1', 'A')
|
||||
return text(result)
|
||||
|
||||
|
||||
# You can also use `bp.add_route()` with stream argument
|
||||
async def bp_post_handler(request):
|
||||
result = ''
|
||||
while True:
|
||||
body = await request.stream.read()
|
||||
if body is None:
|
||||
break
|
||||
result += body.decode('utf-8').replace('1', 'A')
|
||||
return text(result)
|
||||
|
||||
bp.add_route(bp_post_handler, '/bp_stream', methods=['POST'], stream=True)
|
||||
|
||||
|
||||
async def post_handler(request):
|
||||
result = ''
|
||||
while True:
|
||||
body = await request.stream.read()
|
||||
if body is None:
|
||||
break
|
||||
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')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='127.0.0.1', port=8000)
|
||||
|
||||
Response Streaming
|
||||
------------------
|
||||
|
||||
Sanic allows you to stream content to the client with the `stream` method. This method accepts a coroutine callback which is passed a `StreamingHTTPResponse` object that is written to. A simple example is like follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import stream
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
async def sample_streaming_fn(response):
|
||||
await response.write('foo,')
|
||||
await response.write('bar')
|
||||
|
||||
return stream(sample_streaming_fn, content_type='text/csv')
|
||||
|
||||
This is useful in situations where you want to stream content to the client that originates in an external service, like a database. For example, you can stream database records to the client with the asynchronous cursor that `asyncpg` provides:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.route("/")
|
||||
async def index(request):
|
||||
async def stream_from_db(response):
|
||||
conn = await asyncpg.connect(database='test')
|
||||
async with conn.transaction():
|
||||
async for record in conn.cursor('SELECT generate_series(0, 10)'):
|
||||
await response.write(record[0])
|
||||
|
||||
return stream(stream_from_db)
|
||||
|
||||
If a client supports HTTP/1.1, Sanic will use `chunked transfer encoding <https://en.wikipedia.org/wiki/Chunked_transfer_encoding>`_; you can explicitly enable or disable it using `chunked` option of the `stream` function.
|
||||
|
||||
File Streaming
|
||||
--------------
|
||||
|
||||
Sanic provides `sanic.response.file_stream` function that is useful when you want to send a large file. It returns a `StreamingHTTPResponse` object and will use chunked transfer encoding by default; for this reason Sanic doesn't add `Content-Length` HTTP header in the response. If you want to use this header, you can disable chunked transfer encoding and add it manually:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from aiofiles import os as async_os
|
||||
from sanic.response import file_stream
|
||||
|
||||
@app.route("/")
|
||||
async def index(request):
|
||||
file_path = "/srv/www/whatever.png"
|
||||
|
||||
file_stat = await async_os.stat(file_path)
|
||||
headers = {"Content-Length": str(file_stat.st_size)}
|
||||
|
||||
return await file_stream(
|
||||
file_path,
|
||||
headers=headers,
|
||||
chunked=False,
|
||||
)
|
||||
@@ -1,145 +0,0 @@
|
||||
Testing
|
||||
=======
|
||||
|
||||
Sanic endpoints can be tested locally using the `test_client` object, which
|
||||
depends on an additional package: `httpx <https://www.encode.io/httpx/>`_
|
||||
library, which implements an API that mirrors the `requests` library.
|
||||
|
||||
The `test_client` exposes `get`, `post`, `put`, `delete`, `patch`, `head` and `options` methods
|
||||
for you to run against your application. A simple example (using pytest) is like follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Import the Sanic app, usually created with Sanic(__name__)
|
||||
from external_server import app
|
||||
|
||||
def test_index_returns_200():
|
||||
request, response = app.test_client.get('/')
|
||||
assert response.status == 200
|
||||
|
||||
def test_index_put_not_allowed():
|
||||
request, response = app.test_client.put('/')
|
||||
assert response.status == 405
|
||||
|
||||
Internally, each time you call one of the `test_client` methods, the Sanic app is run at `127.0.0.1:42101` and
|
||||
your test request is executed against your application, using `httpx`.
|
||||
|
||||
The `test_client` methods accept the following arguments and keyword arguments:
|
||||
|
||||
- `uri` *(default `'/'`)* A string representing the URI to test.
|
||||
- `gather_request` *(default `True`)* A boolean which determines whether the
|
||||
original request will be returned by the function. If set to `True`, the
|
||||
return value is a tuple of `(request, response)`, if `False` only the
|
||||
response is returned.
|
||||
- `server_kwargs` *(default `{}`)* a dict of additional arguments to pass into `app.run` before the test request is run.
|
||||
- `debug` *(default `False`)* A boolean which determines whether to run the server in debug mode.
|
||||
|
||||
The function further takes the `*request_args` and `**request_kwargs`, which are passed directly to the request.
|
||||
|
||||
For example, to supply data to a GET request, you would do the following:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def test_get_request_includes_data():
|
||||
params = {'key1': 'value1', 'key2': 'value2'}
|
||||
request, response = app.test_client.get('/', params=params)
|
||||
assert request.args.get('key1') == 'value1'
|
||||
|
||||
And to supply data to a JSON POST request:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def test_post_json_request_includes_data():
|
||||
data = {'key1': 'value1', 'key2': 'value2'}
|
||||
request, response = app.test_client.post('/', data=json.dumps(data))
|
||||
assert request.json.get('key1') == 'value1'
|
||||
|
||||
More information about
|
||||
the available arguments to `httpx` can be found
|
||||
[in the documentation for `httpx <https://www.encode.io/httpx/>`_.
|
||||
|
||||
|
||||
Using a random port
|
||||
-------------------
|
||||
|
||||
If you need to test using a free unpriveleged port chosen by the kernel
|
||||
instead of the default with `SanicTestClient`, you can do so by specifying
|
||||
`port=None`. On most systems the port will be in the range 1024 to 65535.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Import the Sanic app, usually created with Sanic(__name__)
|
||||
from external_server import app
|
||||
from sanic.testing import SanicTestClient
|
||||
|
||||
def test_index_returns_200():
|
||||
request, response = SanicTestClient(app, port=None).get('/')
|
||||
assert response.status == 200
|
||||
|
||||
pytest-sanic
|
||||
------------
|
||||
|
||||
`pytest-sanic <https://github.com/yunstanford/pytest-sanic>`_ is a pytest plugin, it helps you to test your code asynchronously.
|
||||
Just write tests like,
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def test_sanic_db_find_by_id(app):
|
||||
"""
|
||||
Let's assume that, in db we have,
|
||||
{
|
||||
"id": "123",
|
||||
"name": "Kobe Bryant",
|
||||
"team": "Lakers",
|
||||
}
|
||||
"""
|
||||
doc = await app.db["players"].find_by_id("123")
|
||||
assert doc.name == "Kobe Bryant"
|
||||
assert doc.team == "Lakers"
|
||||
|
||||
`pytest-sanic <https://github.com/yunstanford/pytest-sanic>`_ also provides some useful fixtures, like loop, unused_port,
|
||||
test_server, test_client.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@pytest.yield_fixture
|
||||
def app():
|
||||
app = Sanic("test_sanic_app")
|
||||
|
||||
@app.route("/test_get", methods=['GET'])
|
||||
async def test_get(request):
|
||||
return response.json({"GET": True})
|
||||
|
||||
@app.route("/test_post", methods=['POST'])
|
||||
async def test_post(request):
|
||||
return response.json({"POST": True})
|
||||
|
||||
yield app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_cli(loop, app, test_client):
|
||||
return loop.run_until_complete(test_client(app, protocol=WebSocketProtocol))
|
||||
|
||||
|
||||
#########
|
||||
# Tests #
|
||||
#########
|
||||
|
||||
async def test_fixture_test_client_get(test_cli):
|
||||
"""
|
||||
GET request
|
||||
"""
|
||||
resp = await test_cli.get('/test_get')
|
||||
assert resp.status == 200
|
||||
resp_json = await resp.json()
|
||||
assert resp_json == {"GET": True}
|
||||
|
||||
async def test_fixture_test_client_post(test_cli):
|
||||
"""
|
||||
POST request
|
||||
"""
|
||||
resp = await test_cli.post('/test_post')
|
||||
assert resp.status == 200
|
||||
resp_json = await resp.json()
|
||||
assert resp_json == {"POST": True}
|
||||
@@ -1,54 +0,0 @@
|
||||
Versioning
|
||||
==========
|
||||
|
||||
You can pass the `version` keyword to the route decorators, or to a blueprint initializer. It will result in the `v{version}` url prefix where `{version}` is the version number.
|
||||
|
||||
Per route
|
||||
---------
|
||||
|
||||
You can pass a version number to the routes directly.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
|
||||
|
||||
@app.route('/text', version=1)
|
||||
def handle_request(request):
|
||||
return response.text('Hello world! Version 1')
|
||||
|
||||
@app.route('/text', version=2)
|
||||
def handle_request(request):
|
||||
return response.text('Hello world! Version 2')
|
||||
|
||||
app.run(port=80)
|
||||
|
||||
Then with curl:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl localhost/v1/text
|
||||
curl localhost/v2/text
|
||||
|
||||
|
||||
Global blueprint version
|
||||
------------------------
|
||||
|
||||
You can also pass a version number to the blueprint, which will apply to all routes.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import response
|
||||
from sanic.blueprints import Blueprint
|
||||
|
||||
bp = Blueprint('test', version=1)
|
||||
|
||||
@bp.route('/html')
|
||||
def handle_request(request):
|
||||
return response.html('<p>Hello world!</p>')
|
||||
|
||||
Then with curl:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl localhost/v1/html
|
||||
@@ -1,55 +0,0 @@
|
||||
WebSocket
|
||||
=========
|
||||
|
||||
Sanic provides an easy to use abstraction on top of `websockets`.
|
||||
Sanic Supports websocket versions 7 and 8.
|
||||
|
||||
To setup a WebSocket:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import json
|
||||
from sanic.websocket import WebSocketProtocol
|
||||
|
||||
app = Sanic()
|
||||
|
||||
@app.websocket('/feed')
|
||||
async def feed(request, ws):
|
||||
while True:
|
||||
data = 'hello!'
|
||||
print('Sending: ' + data)
|
||||
await ws.send(data)
|
||||
data = await ws.recv()
|
||||
print('Received: ' + data)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000, protocol=WebSocketProtocol)
|
||||
|
||||
|
||||
Alternatively, the ``app.add_websocket_route`` method can be used instead of the
|
||||
decorator:
|
||||
|
||||
.. code:: python
|
||||
|
||||
async def feed(request, ws):
|
||||
pass
|
||||
|
||||
app.add_websocket_route(feed, '/feed')
|
||||
|
||||
|
||||
Handlers for a WebSocket route is invoked with the request as first argument, and a
|
||||
WebSocket protocol object as second argument. The protocol object has ``send``
|
||||
and ``recv`` methods to send and receive data respectively.
|
||||
|
||||
|
||||
You could setup your own WebSocket configuration through ``app.config``, like
|
||||
|
||||
.. code:: python
|
||||
|
||||
app.config.WEBSOCKET_MAX_SIZE = 2 ** 20
|
||||
app.config.WEBSOCKET_MAX_QUEUE = 32
|
||||
app.config.WEBSOCKET_READ_LIMIT = 2 ** 16
|
||||
app.config.WEBSOCKET_WRITE_LIMIT = 2 ** 16
|
||||
|
||||
Find more in ``Configuration`` section.
|
||||
@@ -1,19 +0,0 @@
|
||||
name: py36
|
||||
dependencies:
|
||||
- pip=18.1=py36_0
|
||||
- python=3.6=0
|
||||
- setuptools=40.4.3=py36_0
|
||||
- pip:
|
||||
- httptools>=0.0.10
|
||||
- uvloop>=0.5.3
|
||||
- ujson>=1.35
|
||||
- aiofiles>=0.3.0
|
||||
- websockets>=6.0,<7.0
|
||||
- multidict>=4.0,<5.0
|
||||
- sphinx==1.8.3
|
||||
- sphinx_rtd_theme==0.4.2
|
||||
- recommonmark==0.5.0
|
||||
- httpx==0.9.3
|
||||
- sphinxcontrib-asyncio>=0.2.0
|
||||
- docutils==0.14
|
||||
- pygments==2.3.1
|
||||
@@ -1,11 +1,8 @@
|
||||
FROM python:3.5
|
||||
MAINTAINER Channel Cat <channelcat@gmail.com>
|
||||
FROM sanicframework/sanic:LTS
|
||||
|
||||
ADD . /code
|
||||
RUN pip3 install git+https://github.com/channelcat/sanic
|
||||
RUN mkdir /srv
|
||||
COPY . /srv
|
||||
|
||||
EXPOSE 8000
|
||||
WORKDIR /srv
|
||||
|
||||
WORKDIR /code
|
||||
|
||||
CMD ["python", "simple_server.py"]
|
||||
CMD ["sanic", "simple_server.app"]
|
||||
|
||||
43
examples/blueprint_middlware_execution_order.py
Normal file
43
examples/blueprint_middlware_execution_order.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from sanic import Sanic, Blueprint
|
||||
from sanic.response import text
|
||||
'''
|
||||
Demonstrates that blueprint request middleware are executed in the order they
|
||||
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__)
|
||||
|
||||
bp = Blueprint("bp_"+__name__)
|
||||
|
||||
@bp.middleware('request')
|
||||
def request_middleware_1(request):
|
||||
print('1')
|
||||
|
||||
@bp.middleware('request')
|
||||
def request_middleware_2(request):
|
||||
print('2')
|
||||
|
||||
@bp.middleware('request')
|
||||
def request_middleware_3(request):
|
||||
print('3')
|
||||
|
||||
@bp.middleware('response')
|
||||
def resp_middleware_4(request, response):
|
||||
print('4')
|
||||
|
||||
@bp.middleware('response')
|
||||
def resp_middleware_5(request, response):
|
||||
print('5')
|
||||
|
||||
@bp.middleware('response')
|
||||
def resp_middleware_6(request, response):
|
||||
print('6')
|
||||
|
||||
@bp.route('/')
|
||||
def pop_handler(request):
|
||||
return text('hello world')
|
||||
|
||||
app.blueprint(bp, url_prefix='/bp')
|
||||
|
||||
app.run(host="0.0.0.0", port=8000, debug=True, auto_reload=False)
|
||||
@@ -2,37 +2,38 @@ 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')
|
||||
blueprint = Blueprint("name", url_prefix="/my_blueprint")
|
||||
blueprint2 = Blueprint("name2", url_prefix="/my_blueprint2")
|
||||
blueprint3 = Blueprint("name3", url_prefix="/my_blueprint3")
|
||||
|
||||
|
||||
@blueprint.route('/foo')
|
||||
@blueprint.route("/foo")
|
||||
async def foo(request):
|
||||
return json({'msg': 'hi from blueprint'})
|
||||
return json({"msg": "hi from blueprint"})
|
||||
|
||||
|
||||
@blueprint2.route('/foo')
|
||||
@blueprint2.route("/foo")
|
||||
async def foo2(request):
|
||||
return json({'msg': 'hi from blueprint2'})
|
||||
return json({"msg": "hi from blueprint2"})
|
||||
|
||||
|
||||
@blueprint3.route('/foo')
|
||||
@blueprint3.route("/foo")
|
||||
async def index(request):
|
||||
return await file('websocket.html')
|
||||
return await file("websocket.html")
|
||||
|
||||
|
||||
@app.websocket('/feed')
|
||||
@app.websocket("/feed")
|
||||
async def foo3(request, ws):
|
||||
while True:
|
||||
data = 'hello!'
|
||||
print('Sending: ' + data)
|
||||
data = "hello!"
|
||||
print("Sending: " + data)
|
||||
await ws.send(data)
|
||||
data = await ws.recv()
|
||||
print('Received: ' + data)
|
||||
print("Received: " + data)
|
||||
|
||||
|
||||
app.blueprint(blueprint)
|
||||
app.blueprint(blueprint2)
|
||||
app.blueprint(blueprint3)
|
||||
|
||||
app.run(host="0.0.0.0", port=8000, debug=True)
|
||||
app.run(host="0.0.0.0", port=9999, debug=True)
|
||||
|
||||
18
examples/delayed_response.py
Normal file
18
examples/delayed_response.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from asyncio import sleep
|
||||
|
||||
from sanic import Sanic, response
|
||||
|
||||
app = Sanic(__name__, strict_slashes=True)
|
||||
|
||||
@app.get("/")
|
||||
async def handler(request):
|
||||
return response.redirect("/sleep/3")
|
||||
|
||||
@app.get("/sleep/<t:number>")
|
||||
async def handler2(request, t=0.3):
|
||||
await sleep(t)
|
||||
return response.text(f"Slept {t:.1f} seconds.\n")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
51
examples/http_redirect.py
Normal file
51
examples/http_redirect.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from sanic import Sanic, response, text
|
||||
|
||||
|
||||
HTTP_PORT = 9999
|
||||
HTTPS_PORT = 8888
|
||||
|
||||
http = Sanic("http")
|
||||
http.config.SERVER_NAME = f"localhost:{HTTP_PORT}"
|
||||
https = Sanic("https")
|
||||
https.config.SERVER_NAME = f"localhost:{HTTPS_PORT}"
|
||||
|
||||
|
||||
@https.get("/foo")
|
||||
def foo(request):
|
||||
return text("foo")
|
||||
|
||||
|
||||
@https.get("/bar")
|
||||
def bar(request):
|
||||
return text("bar")
|
||||
|
||||
|
||||
@http.get("/<path:path>")
|
||||
def proxy(request, path):
|
||||
url = request.app.url_for(
|
||||
"proxy",
|
||||
path=path,
|
||||
_server=https.config.SERVER_NAME,
|
||||
_external=True,
|
||||
_scheme="http",
|
||||
)
|
||||
return response.redirect(url)
|
||||
|
||||
|
||||
@https.listener("main_process_start")
|
||||
async def start(app, _):
|
||||
global http
|
||||
app.http_server = await http.create_server(
|
||||
port=HTTP_PORT, return_asyncio_server=True
|
||||
)
|
||||
app.http_server.after_start()
|
||||
|
||||
|
||||
@https.listener("main_process_stop")
|
||||
async def stop(app, _):
|
||||
app.http_server.before_stop()
|
||||
await app.http_server.close()
|
||||
app.http_server.after_stop()
|
||||
|
||||
|
||||
https.run(port=HTTPS_PORT, debug=True)
|
||||
@@ -1,86 +1,75 @@
|
||||
'''
|
||||
Based on example from https://github.com/Skyscanner/aiotask-context
|
||||
and `examples/{override_logging,run_async}.py`.
|
||||
|
||||
Needs https://github.com/Skyscanner/aiotask-context/tree/52efbc21e2e1def2d52abb9a8e951f3ce5e6f690 or newer
|
||||
|
||||
$ pip install git+https://github.com/Skyscanner/aiotask-context.git
|
||||
'''
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
import logging
|
||||
from signal import signal, SIGINT
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic import response
|
||||
|
||||
import uvloop
|
||||
import aiotask_context as context
|
||||
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RequestIdFilter(logging.Filter):
|
||||
def filter(self, record):
|
||||
record.request_id = context.get('X-Request-ID')
|
||||
try:
|
||||
record.request_id = context.get("X-Request-ID")
|
||||
except ValueError:
|
||||
record.request_id = "n/a"
|
||||
return True
|
||||
|
||||
|
||||
LOG_SETTINGS = {
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
'handlers': {
|
||||
'console': {
|
||||
'class': 'logging.StreamHandler',
|
||||
'level': 'DEBUG',
|
||||
'formatter': 'default',
|
||||
'filters': ['requestid'],
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "default",
|
||||
"filters": ["requestid"],
|
||||
},
|
||||
},
|
||||
'filters': {
|
||||
'requestid': {
|
||||
'()': RequestIdFilter,
|
||||
"filters": {
|
||||
"requestid": {
|
||||
"()": RequestIdFilter,
|
||||
},
|
||||
},
|
||||
'formatters': {
|
||||
'default': {
|
||||
'format': '%(asctime)s %(levelname)s %(name)s:%(lineno)d %(request_id)s | %(message)s',
|
||||
"formatters": {
|
||||
"default": {
|
||||
"format": "%(asctime)s %(levelname)s %(name)s:%(lineno)d %(request_id)s | %(message)s",
|
||||
},
|
||||
},
|
||||
'loggers': {
|
||||
'': {
|
||||
'level': 'DEBUG',
|
||||
'handlers': ['console'],
|
||||
'propagate': True
|
||||
"loggers": {
|
||||
"": {"level": "DEBUG", "handlers": ["console"], "propagate": True},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
app = Sanic(__name__, log_config=LOG_SETTINGS)
|
||||
|
||||
|
||||
@app.middleware('request')
|
||||
@app.on_request
|
||||
async def set_request_id(request):
|
||||
request_id = request.headers.get('X-Request-ID') or str(uuid.uuid4())
|
||||
request_id = request.id
|
||||
context.set("X-Request-ID", request_id)
|
||||
log.info(f"Setting {request.id=}")
|
||||
|
||||
|
||||
@app.on_response
|
||||
async def set_request_header(request, response):
|
||||
response.headers["X-Request-ID"] = request.id
|
||||
|
||||
|
||||
@app.route("/")
|
||||
async def test(request):
|
||||
log.debug('X-Request-ID: %s', context.get('X-Request-ID'))
|
||||
log.info('Hello from test!')
|
||||
log.debug("X-Request-ID: %s", context.get("X-Request-ID"))
|
||||
log.info("Hello from test!")
|
||||
return response.json({"test": True})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.set_event_loop(uvloop.new_event_loop())
|
||||
server = app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True)
|
||||
loop = asyncio.get_event_loop()
|
||||
@app.before_server_start
|
||||
def setup(app, loop):
|
||||
loop.set_task_factory(context.task_factory)
|
||||
task = asyncio.ensure_future(server)
|
||||
try:
|
||||
loop.run_forever()
|
||||
except:
|
||||
loop.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(port=9999, debug=True)
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
from sanic import Sanic
|
||||
from sanic import response
|
||||
import logging
|
||||
|
||||
from sanic import Sanic, text
|
||||
|
||||
|
||||
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
|
||||
logging_format += "%(module)s::%(funcName)s():l%(lineno)d: "
|
||||
logging_format += "%(message)s"
|
||||
|
||||
logging.basicConfig(
|
||||
format=logging_format,
|
||||
level=logging.DEBUG
|
||||
)
|
||||
logging.basicConfig(format=logging_format, level=logging.DEBUG)
|
||||
log = logging.getLogger()
|
||||
|
||||
# Set logger to override default basicConfig
|
||||
sanic = Sanic()
|
||||
app = Sanic("app")
|
||||
|
||||
|
||||
@sanic.route("/")
|
||||
@app.route("/")
|
||||
def test(request):
|
||||
log.info("received request; responding with 'hey'")
|
||||
return response.text("hey")
|
||||
return text("hey")
|
||||
|
||||
sanic.run(host="0.0.0.0", port=8000)
|
||||
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
|
||||
@@ -9,15 +9,19 @@ Run with xdist params:
|
||||
$ pytest examples/pytest_xdist.py -n 8 # 8 workers
|
||||
"""
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from sanic_testing import SanicTestClient
|
||||
from sanic_testing.testing import PORT as PORT_BASE
|
||||
|
||||
from sanic import Sanic
|
||||
from sanic.response import text
|
||||
from sanic.testing import PORT as PORT_BASE, SanicTestClient
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def test_port(worker_id):
|
||||
m = re.search(r'[0-9]+', worker_id)
|
||||
m = re.search(r"[0-9]+", worker_id)
|
||||
if m:
|
||||
num_id = m.group(0)
|
||||
else:
|
||||
@@ -30,9 +34,9 @@ def test_port(worker_id):
|
||||
def app():
|
||||
app = Sanic()
|
||||
|
||||
@app.route('/')
|
||||
@app.route("/")
|
||||
async def index(request):
|
||||
return text('OK')
|
||||
return text("OK")
|
||||
|
||||
return app
|
||||
|
||||
@@ -42,8 +46,8 @@ def client(app, test_port):
|
||||
return SanicTestClient(app, test_port)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('run_id', range(100))
|
||||
@pytest.mark.parametrize("run_id", range(100))
|
||||
def test_index(client, run_id):
|
||||
request, response = client._sanic_endpoint_test('get', '/')
|
||||
request, response = client._sanic_endpoint_test("get", "/")
|
||||
assert response.status == 200
|
||||
assert response.text == 'OK'
|
||||
assert response.text == "OK"
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from sanic import Sanic, response
|
||||
|
||||
|
||||
@@ -47,14 +48,14 @@ async def handler_file_stream(request):
|
||||
)
|
||||
|
||||
|
||||
@app.route("/stream", stream=True)
|
||||
@app.post("/stream", stream=True)
|
||||
async def handler_stream(request):
|
||||
while True:
|
||||
body = await request.stream.read()
|
||||
if body is None:
|
||||
break
|
||||
body = body.decode("utf-8").replace("1", "A")
|
||||
# await response.write(body)
|
||||
await response.write(body)
|
||||
return response.stream(body)
|
||||
|
||||
|
||||
|
||||
BIN
examples/static/favicon.ico
Normal file
BIN
examples/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
examples/static/images/logo.png
Normal file
BIN
examples/static/images/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
2
examples/static/robots.txt
Normal file
2
examples/static/robots.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Disallow: /
|
||||
6
examples/static_assets.py
Normal file
6
examples/static_assets.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from sanic import Sanic
|
||||
|
||||
|
||||
app = Sanic(__name__)
|
||||
|
||||
app.static("/", "./static")
|
||||
35
examples/versioned_blueprint_group.py
Normal file
35
examples/versioned_blueprint_group.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from sanic import Sanic
|
||||
from sanic.blueprints import Blueprint
|
||||
from sanic.response import json
|
||||
|
||||
|
||||
app = Sanic(name="blue-print-group-version-example")
|
||||
|
||||
bp1 = Blueprint(name="ultron", url_prefix="/ultron")
|
||||
bp2 = Blueprint(name="vision", url_prefix="/vision", strict_slashes=None)
|
||||
|
||||
bpg = Blueprint.group([bp1, bp2], url_prefix="/sentient/robot", version=1, strict_slashes=True)
|
||||
|
||||
|
||||
@bp1.get("/name")
|
||||
async def bp1_name(request):
|
||||
"""This will expose an Endpoint GET /v1/sentient/robot/ultron/name"""
|
||||
return json({"name": "Ultron"})
|
||||
|
||||
|
||||
@bp2.get("/name")
|
||||
async def bp2_name(request):
|
||||
"""This will expose an Endpoint GET /v1/sentient/robot/vision/name"""
|
||||
return json({"name": "vision"})
|
||||
|
||||
|
||||
@bp2.get("/name", version=2)
|
||||
async def bp2_revised_name(request):
|
||||
"""This will expose an Endpoint GET /v2/sentient/robot/vision/name"""
|
||||
return json({"name": "new vision"})
|
||||
|
||||
|
||||
app.blueprint(bpg)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
@@ -1,39 +1,45 @@
|
||||
from sanic import response
|
||||
from sanic import Sanic
|
||||
from sanic import Sanic, response
|
||||
from sanic.blueprints import Blueprint
|
||||
|
||||
|
||||
# Usage
|
||||
# curl -H "Host: example.com" localhost:8000
|
||||
# curl -H "Host: sub.example.com" localhost:8000
|
||||
# curl -H "Host: bp.example.com" localhost:8000/question
|
||||
# curl -H "Host: bp.example.com" localhost:8000/answer
|
||||
|
||||
app = Sanic()
|
||||
app = Sanic(__name__)
|
||||
bp = Blueprint("bp", host="bp.example.com")
|
||||
|
||||
|
||||
@app.route('/', host=["example.com",
|
||||
"somethingelse.com",
|
||||
"therestofyourdomains.com"])
|
||||
async def hello(request):
|
||||
@app.route(
|
||||
"/", host=["example.com", "somethingelse.com", "therestofyourdomains.com"]
|
||||
)
|
||||
async def hello_0(request):
|
||||
return response.text("Some defaults")
|
||||
|
||||
|
||||
@app.route('/', host="sub.example.com")
|
||||
async def hello(request):
|
||||
@app.route("/", host="sub.example.com")
|
||||
async def hello_1(request):
|
||||
return response.text("42")
|
||||
|
||||
|
||||
@bp.route("/question")
|
||||
async def hello(request):
|
||||
async def hello_2(request):
|
||||
return response.text("What is the meaning of life?")
|
||||
|
||||
|
||||
@bp.route("/answer")
|
||||
async def hello(request):
|
||||
async def hello_3(request):
|
||||
return response.text("42")
|
||||
|
||||
|
||||
@app.get("/name")
|
||||
def name(request):
|
||||
return response.text(request.app.url_for("name", _external=True))
|
||||
|
||||
|
||||
app.blueprint(bp)
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8000)
|
||||
@@ -1,2 +1,9 @@
|
||||
conda:
|
||||
file: environment.yml
|
||||
version: 2
|
||||
python:
|
||||
version: 3.8
|
||||
install:
|
||||
- method: pip
|
||||
path: .
|
||||
extra_requirements:
|
||||
- docs
|
||||
system_packages: true
|
||||
@@ -1,6 +1,17 @@
|
||||
from sanic.__version__ import __version__
|
||||
from sanic.app import Sanic
|
||||
from sanic.blueprints import Blueprint
|
||||
from sanic.request import Request
|
||||
from sanic.response import HTTPResponse, html, json, text
|
||||
|
||||
|
||||
__all__ = ["Sanic", "Blueprint", "__version__"]
|
||||
__all__ = (
|
||||
"__version__",
|
||||
"Sanic",
|
||||
"Blueprint",
|
||||
"HTTPResponse",
|
||||
"Request",
|
||||
"html",
|
||||
"json",
|
||||
"text",
|
||||
)
|
||||
|
||||
@@ -1,39 +1,105 @@
|
||||
from argparse import ArgumentParser
|
||||
import os
|
||||
import sys
|
||||
|
||||
from argparse import ArgumentParser, RawDescriptionHelpFormatter
|
||||
from importlib import import_module
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from sanic import __version__
|
||||
from sanic.app import Sanic
|
||||
from sanic.config import BASE_LOGO
|
||||
from sanic.log import logger
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser(prog="sanic")
|
||||
parser.add_argument("--host", dest="host", type=str, default="127.0.0.1")
|
||||
parser.add_argument("--port", dest="port", type=int, default=8000)
|
||||
class SanicArgumentParser(ArgumentParser):
|
||||
def add_bool_arguments(self, *args, **kwargs):
|
||||
group = self.add_mutually_exclusive_group()
|
||||
group.add_argument(*args, action="store_true", **kwargs)
|
||||
kwargs["help"] = "no " + kwargs["help"]
|
||||
group.add_argument(
|
||||
"--no-" + args[0][2:], *args[1:], action="store_false", **kwargs
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = SanicArgumentParser(
|
||||
prog="sanic",
|
||||
description=BASE_LOGO,
|
||||
formatter_class=RawDescriptionHelpFormatter,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-H",
|
||||
"--host",
|
||||
dest="host",
|
||||
type=str,
|
||||
default="127.0.0.1",
|
||||
help="host address [default 127.0.0.1]",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--port",
|
||||
dest="port",
|
||||
type=int,
|
||||
default=8000,
|
||||
help="port to serve on [default 8000]",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u",
|
||||
"--unix",
|
||||
dest="unix",
|
||||
type=str,
|
||||
default="",
|
||||
help="location of unix socket",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cert", dest="cert", type=str, help="location of certificate for SSL"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--key", dest="key", type=str, help="location of keyfile for SSL."
|
||||
)
|
||||
parser.add_argument("--workers", dest="workers", type=int, default=1)
|
||||
parser.add_argument(
|
||||
"-w",
|
||||
"--workers",
|
||||
dest="workers",
|
||||
type=int,
|
||||
default=1,
|
||||
help="number of worker processes [default 1]",
|
||||
)
|
||||
parser.add_argument("--debug", dest="debug", action="store_true")
|
||||
parser.add_argument("module")
|
||||
parser.add_bool_arguments(
|
||||
"--access-logs", dest="access_log", help="display access logs"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-v",
|
||||
"--version",
|
||||
action="version",
|
||||
version=f"Sanic {__version__}",
|
||||
)
|
||||
parser.add_argument(
|
||||
"module", help="path to your Sanic app. Example: path.to.server:app"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
module_path = os.path.abspath(os.getcwd())
|
||||
if module_path not in sys.path:
|
||||
sys.path.append(module_path)
|
||||
|
||||
if ":" in args.module:
|
||||
module_name, app_name = args.module.rsplit(":", 1)
|
||||
else:
|
||||
module_parts = args.module.split(".")
|
||||
module_name = ".".join(module_parts[:-1])
|
||||
app_name = module_parts[-1]
|
||||
|
||||
module = import_module(module_name)
|
||||
app = getattr(module, app_name, None)
|
||||
app_name = type(app).__name__
|
||||
|
||||
if not isinstance(app, Sanic):
|
||||
raise ValueError(
|
||||
"Module is not a Sanic app, it is a {}. "
|
||||
"Perhaps you meant {}.app?".format(
|
||||
type(app).__name__, args.module
|
||||
)
|
||||
f"Module is not a Sanic app, it is a {app_name}. "
|
||||
f"Perhaps you meant {args.module}.app?"
|
||||
)
|
||||
if args.cert is not None or args.key is not None:
|
||||
ssl = {
|
||||
@@ -46,15 +112,21 @@ if __name__ == "__main__":
|
||||
app.run(
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
unix=args.unix,
|
||||
workers=args.workers,
|
||||
debug=args.debug,
|
||||
access_log=args.access_log,
|
||||
ssl=ssl,
|
||||
)
|
||||
except ImportError as e:
|
||||
logger.error(
|
||||
"No module named {} found.\n"
|
||||
" Example File: project/sanic_server.py -> app\n"
|
||||
" Example Module: project.sanic_server.app".format(e.name)
|
||||
f"No module named {e.name} found.\n"
|
||||
f" Example File: project/sanic_server.py -> app\n"
|
||||
f" Example Module: project.sanic_server.app"
|
||||
)
|
||||
except ValueError:
|
||||
logger.exception("Failed to run app")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "19.12.0"
|
||||
__version__ = "21.3.1"
|
||||
|
||||
1534
sanic/app.py
1534
sanic/app.py
File diff suppressed because it is too large
Load Diff
287
sanic/asgi.py
287
sanic/asgi.py
@@ -1,118 +1,19 @@
|
||||
import asyncio
|
||||
import warnings
|
||||
|
||||
from inspect import isawaitable
|
||||
from typing import (
|
||||
Any,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Dict,
|
||||
List,
|
||||
MutableMapping,
|
||||
Optional,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import sanic.app # noqa
|
||||
|
||||
from sanic.compat import Header
|
||||
from sanic.exceptions import InvalidUsage, ServerError
|
||||
from sanic.log import logger
|
||||
from sanic.exceptions import ServerError
|
||||
from sanic.models.asgi import ASGIReceive, ASGIScope, ASGISend, MockTransport
|
||||
from sanic.request import Request
|
||||
from sanic.response import HTTPResponse, StreamingHTTPResponse
|
||||
from sanic.server import StreamBuffer
|
||||
from sanic.server import ConnInfo
|
||||
from sanic.websocket import WebSocketConnection
|
||||
|
||||
|
||||
ASGIScope = MutableMapping[str, Any]
|
||||
ASGIMessage = MutableMapping[str, Any]
|
||||
ASGISend = Callable[[ASGIMessage], Awaitable[None]]
|
||||
ASGIReceive = Callable[[], Awaitable[ASGIMessage]]
|
||||
|
||||
|
||||
class MockProtocol:
|
||||
def __init__(self, transport: "MockTransport", loop):
|
||||
self.transport = transport
|
||||
self._not_paused = asyncio.Event(loop=loop)
|
||||
self._not_paused.set()
|
||||
self._complete = asyncio.Event(loop=loop)
|
||||
|
||||
def pause_writing(self) -> None:
|
||||
self._not_paused.clear()
|
||||
|
||||
def resume_writing(self) -> None:
|
||||
self._not_paused.set()
|
||||
|
||||
async def complete(self) -> None:
|
||||
self._not_paused.set()
|
||||
await self.transport.send(
|
||||
{"type": "http.response.body", "body": b"", "more_body": False}
|
||||
)
|
||||
|
||||
@property
|
||||
def is_complete(self) -> bool:
|
||||
return self._complete.is_set()
|
||||
|
||||
async def push_data(self, data: bytes) -> None:
|
||||
if not self.is_complete:
|
||||
await self.transport.send(
|
||||
{"type": "http.response.body", "body": data, "more_body": True}
|
||||
)
|
||||
|
||||
async def drain(self) -> None:
|
||||
await self._not_paused.wait()
|
||||
|
||||
|
||||
class MockTransport:
|
||||
_protocol: Optional[MockProtocol]
|
||||
|
||||
def __init__(
|
||||
self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend
|
||||
) -> None:
|
||||
self.scope = scope
|
||||
self._receive = receive
|
||||
self._send = send
|
||||
self._protocol = None
|
||||
self.loop = None
|
||||
|
||||
def get_protocol(self) -> MockProtocol:
|
||||
if not self._protocol:
|
||||
self._protocol = MockProtocol(self, self.loop)
|
||||
return self._protocol
|
||||
|
||||
def get_extra_info(self, info: str) -> Union[str, bool, None]:
|
||||
if info == "peername":
|
||||
return self.scope.get("server")
|
||||
elif info == "sslcontext":
|
||||
return self.scope.get("scheme") in ["https", "wss"]
|
||||
return None
|
||||
|
||||
def get_websocket_connection(self) -> WebSocketConnection:
|
||||
try:
|
||||
return self._websocket_connection
|
||||
except AttributeError:
|
||||
raise InvalidUsage("Improper websocket connection.")
|
||||
|
||||
def create_websocket_connection(
|
||||
self, send: ASGISend, receive: ASGIReceive
|
||||
) -> WebSocketConnection:
|
||||
self._websocket_connection = WebSocketConnection(send, receive)
|
||||
return self._websocket_connection
|
||||
|
||||
def add_task(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
async def send(self, data) -> None:
|
||||
# TODO:
|
||||
# - Validation on data and that it is formatted properly and is valid
|
||||
await self._send(data)
|
||||
|
||||
async def receive(self) -> ASGIMessage:
|
||||
return await self._receive()
|
||||
|
||||
|
||||
class Lifespan:
|
||||
def __init__(self, asgi_app: "ASGIApp") -> None:
|
||||
self.asgi_app = asgi_app
|
||||
@@ -141,6 +42,9 @@ class Lifespan:
|
||||
in sequence since the ASGI lifespan protocol only supports a single
|
||||
startup event.
|
||||
"""
|
||||
self.asgi_app.sanic_app.router.finalize()
|
||||
if self.asgi_app.sanic_app.signal_router.routes:
|
||||
self.asgi_app.sanic_app.signal_router.finalize()
|
||||
listeners = self.asgi_app.sanic_app.listeners.get(
|
||||
"before_server_start", []
|
||||
) + self.asgi_app.sanic_app.listeners.get("after_server_start", [])
|
||||
@@ -149,7 +53,7 @@ class Lifespan:
|
||||
response = handler(
|
||||
self.asgi_app.sanic_app, self.asgi_app.sanic_app.loop
|
||||
)
|
||||
if isawaitable(response):
|
||||
if response and isawaitable(response):
|
||||
await response
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
@@ -169,7 +73,7 @@ class Lifespan:
|
||||
response = handler(
|
||||
self.asgi_app.sanic_app, self.asgi_app.sanic_app.loop
|
||||
)
|
||||
if isawaitable(response):
|
||||
if response and isawaitable(response):
|
||||
await response
|
||||
|
||||
async def __call__(
|
||||
@@ -190,7 +94,6 @@ class ASGIApp:
|
||||
sanic_app: "sanic.app.Sanic"
|
||||
request: Request
|
||||
transport: MockTransport
|
||||
do_stream: bool
|
||||
lifespan: Lifespan
|
||||
ws: Optional[WebSocketConnection]
|
||||
|
||||
@@ -213,9 +116,6 @@ class ASGIApp:
|
||||
for key, value in scope.get("headers", [])
|
||||
]
|
||||
)
|
||||
instance.do_stream = (
|
||||
True if headers.get("expect") == "100-continue" else False
|
||||
)
|
||||
instance.lifespan = Lifespan(instance)
|
||||
|
||||
if scope["type"] == "lifespan":
|
||||
@@ -242,9 +142,7 @@ class ASGIApp:
|
||||
)
|
||||
await instance.ws.accept()
|
||||
else:
|
||||
pass
|
||||
# TODO:
|
||||
# - close connection
|
||||
raise ServerError("Received unknown ASGI scope")
|
||||
|
||||
request_class = sanic_app.request_class or Request
|
||||
instance.request = request_class(
|
||||
@@ -255,142 +153,57 @@ class ASGIApp:
|
||||
instance.transport,
|
||||
sanic_app,
|
||||
)
|
||||
|
||||
if sanic_app.is_request_stream:
|
||||
is_stream_handler = sanic_app.router.is_stream_handler(
|
||||
instance.request
|
||||
)
|
||||
if is_stream_handler:
|
||||
instance.request.stream = StreamBuffer(
|
||||
sanic_app.config.REQUEST_BUFFER_QUEUE_SIZE
|
||||
)
|
||||
instance.do_stream = True
|
||||
instance.request.stream = instance
|
||||
instance.request_body = True
|
||||
instance.request.conn_info = ConnInfo(instance.transport)
|
||||
|
||||
return instance
|
||||
|
||||
async def read_body(self) -> bytes:
|
||||
"""
|
||||
Read and return the entire body from an incoming ASGI message.
|
||||
"""
|
||||
body = b""
|
||||
more_body = True
|
||||
while more_body:
|
||||
message = await self.transport.receive()
|
||||
body += message.get("body", b"")
|
||||
more_body = message.get("more_body", False)
|
||||
|
||||
return body
|
||||
|
||||
async def stream_body(self) -> None:
|
||||
async def read(self) -> Optional[bytes]:
|
||||
"""
|
||||
Read and stream the body in chunks from an incoming ASGI message.
|
||||
"""
|
||||
more_body = True
|
||||
|
||||
while more_body:
|
||||
message = await self.transport.receive()
|
||||
chunk = message.get("body", b"")
|
||||
await self.request.stream.put(chunk)
|
||||
if not message.get("more_body", False):
|
||||
self.request_body = False
|
||||
return None
|
||||
return message.get("body", b"")
|
||||
|
||||
more_body = message.get("more_body", False)
|
||||
async def __aiter__(self):
|
||||
while self.request_body:
|
||||
data = await self.read()
|
||||
if data:
|
||||
yield data
|
||||
|
||||
await self.request.stream.put(None)
|
||||
def respond(self, response):
|
||||
response.stream, self.response = self, response
|
||||
return response
|
||||
|
||||
async def send(self, data, end_stream):
|
||||
if self.response:
|
||||
response, self.response = self.response, None
|
||||
await self.transport.send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": response.status,
|
||||
"headers": response.processed_headers,
|
||||
}
|
||||
)
|
||||
response_body = getattr(response, "body", None)
|
||||
if response_body:
|
||||
data = response_body + data if data else response_body
|
||||
await self.transport.send(
|
||||
{
|
||||
"type": "http.response.body",
|
||||
"body": data.encode() if hasattr(data, "encode") else data,
|
||||
"more_body": not end_stream,
|
||||
}
|
||||
)
|
||||
|
||||
_asgi_single_callable = True # We conform to ASGI 3.0 single-callable
|
||||
|
||||
async def __call__(self) -> None:
|
||||
"""
|
||||
Handle the incoming request.
|
||||
"""
|
||||
if not self.do_stream:
|
||||
self.request.body = await self.read_body()
|
||||
else:
|
||||
self.sanic_app.loop.create_task(self.stream_body())
|
||||
|
||||
handler = self.sanic_app.handle_request
|
||||
callback = None if self.ws else self.stream_callback
|
||||
await handler(self.request, None, callback)
|
||||
|
||||
async def stream_callback(self, response: HTTPResponse) -> None:
|
||||
"""
|
||||
Write the response.
|
||||
"""
|
||||
headers: List[Tuple[bytes, bytes]] = []
|
||||
cookies: Dict[str, str] = {}
|
||||
try:
|
||||
cookies = {
|
||||
v.key: v
|
||||
for _, v in list(
|
||||
filter(
|
||||
lambda item: item[0].lower() == "set-cookie",
|
||||
response.headers.items(),
|
||||
)
|
||||
)
|
||||
}
|
||||
headers += [
|
||||
(str(name).encode("latin-1"), str(value).encode("latin-1"))
|
||||
for name, value in response.headers.items()
|
||||
if name.lower() not in ["set-cookie"]
|
||||
]
|
||||
except AttributeError:
|
||||
logger.error(
|
||||
"Invalid response object for url %s, "
|
||||
"Expected Type: HTTPResponse, Actual Type: %s",
|
||||
self.request.url,
|
||||
type(response),
|
||||
)
|
||||
exception = ServerError("Invalid response type")
|
||||
response = self.sanic_app.error_handler.response(
|
||||
self.request, exception
|
||||
)
|
||||
headers = [
|
||||
(str(name).encode("latin-1"), str(value).encode("latin-1"))
|
||||
for name, value in response.headers.items()
|
||||
if name not in (b"Set-Cookie",)
|
||||
]
|
||||
|
||||
if "content-length" not in response.headers and not isinstance(
|
||||
response, StreamingHTTPResponse
|
||||
):
|
||||
headers += [
|
||||
(b"content-length", str(len(response.body)).encode("latin-1"))
|
||||
]
|
||||
|
||||
if "content-type" not in response.headers:
|
||||
headers += [
|
||||
(b"content-type", str(response.content_type).encode("latin-1"))
|
||||
]
|
||||
|
||||
if response.cookies:
|
||||
cookies.update(
|
||||
{
|
||||
v.key: v
|
||||
for _, v in response.cookies.items()
|
||||
if v.key not in cookies.keys()
|
||||
}
|
||||
)
|
||||
|
||||
headers += [
|
||||
(b"set-cookie", cookie.encode("utf-8"))
|
||||
for k, cookie in cookies.items()
|
||||
]
|
||||
|
||||
await self.transport.send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": response.status,
|
||||
"headers": headers,
|
||||
}
|
||||
)
|
||||
|
||||
if isinstance(response, StreamingHTTPResponse):
|
||||
response.protocol = self.transport.get_protocol()
|
||||
await response.stream()
|
||||
await response.protocol.complete()
|
||||
|
||||
else:
|
||||
await self.transport.send(
|
||||
{
|
||||
"type": "http.response.body",
|
||||
"body": response.body,
|
||||
"more_body": False,
|
||||
}
|
||||
)
|
||||
await self.sanic_app.handle_request(self.request)
|
||||
|
||||
41
sanic/base.py
Normal file
41
sanic/base.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from typing import Any, Tuple
|
||||
from warnings import warn
|
||||
|
||||
from sanic.mixins.exceptions import ExceptionMixin
|
||||
from sanic.mixins.listeners import ListenerMixin
|
||||
from sanic.mixins.middleware import MiddlewareMixin
|
||||
from sanic.mixins.routes import RouteMixin
|
||||
from sanic.mixins.signals import SignalMixin
|
||||
|
||||
|
||||
class BaseSanic(
|
||||
RouteMixin,
|
||||
MiddlewareMixin,
|
||||
ListenerMixin,
|
||||
ExceptionMixin,
|
||||
SignalMixin,
|
||||
):
|
||||
__fake_slots__: Tuple[str, ...]
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
for base in BaseSanic.__bases__:
|
||||
base.__init__(self, *args, **kwargs) # type: ignore
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<{self.__class__.__name__} {self.name}>"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
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(
|
||||
f"Setting variables on {self.__class__.__name__} instances is "
|
||||
"deprecated and will be removed in version 21.9. You should "
|
||||
f"change your {self.__class__.__name__} instance to use "
|
||||
f"instance.ctx.{name} instead."
|
||||
)
|
||||
super().__setattr__(name, value)
|
||||
@@ -1,4 +1,7 @@
|
||||
from collections.abc import MutableSequence
|
||||
from typing import List, Optional, Union
|
||||
|
||||
import sanic
|
||||
|
||||
|
||||
class BlueprintGroup(MutableSequence):
|
||||
@@ -9,37 +12,105 @@ class BlueprintGroup(MutableSequence):
|
||||
some of the existing implementation, this class provides a custom
|
||||
iterator implementation that will let you use the object of this
|
||||
class as a list/tuple inside the existing implementation.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bp1 = Blueprint('bp1', url_prefix='/bp1')
|
||||
bp2 = Blueprint('bp2', url_prefix='/bp2')
|
||||
|
||||
bp3 = Blueprint('bp3', url_prefix='/bp4')
|
||||
bp3 = Blueprint('bp3', url_prefix='/bp4')
|
||||
|
||||
bpg = BlueprintGroup(bp3, bp4, url_prefix="/api", version="v1")
|
||||
|
||||
@bp1.middleware('request')
|
||||
async def bp1_only_middleware(request):
|
||||
print('applied on Blueprint : bp1 Only')
|
||||
|
||||
@bp1.route('/')
|
||||
async def bp1_route(request):
|
||||
return text('bp1')
|
||||
|
||||
@bp2.route('/<param>')
|
||||
async def bp2_route(request, param):
|
||||
return text(param)
|
||||
|
||||
@bp3.route('/')
|
||||
async def bp1_route(request):
|
||||
return text('bp1')
|
||||
|
||||
@bp4.route('/<param>')
|
||||
async def bp2_route(request, param):
|
||||
return text(param)
|
||||
|
||||
group = Blueprint.group(bp1, bp2)
|
||||
|
||||
@group.middleware('request')
|
||||
async def group_middleware(request):
|
||||
print('common middleware applied for both bp1 and bp2')
|
||||
|
||||
# Register Blueprint group under the app
|
||||
app.blueprint(group)
|
||||
app.blueprint(bpg)
|
||||
"""
|
||||
|
||||
__slots__ = ("_blueprints", "_url_prefix")
|
||||
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
|
||||
|
||||
def __init__(self, url_prefix=None):
|
||||
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
|
||||
"""
|
||||
Create a new Blueprint Group
|
||||
|
||||
:param url_prefix: URL: to be prefixed before all the Blueprint Prefix
|
||||
:param version: API Version for the blueprint group. This will be
|
||||
inherited by each of the Blueprint
|
||||
:param strict_slashes: URL Strict slash behavior indicator
|
||||
"""
|
||||
self._blueprints = []
|
||||
self._url_prefix = url_prefix
|
||||
self._version = version
|
||||
self._strict_slashes = strict_slashes
|
||||
|
||||
@property
|
||||
def url_prefix(self):
|
||||
def url_prefix(self) -> str:
|
||||
"""
|
||||
Retrieve the URL prefix being used for the Current Blueprint Group
|
||||
|
||||
:return: string with url prefix
|
||||
"""
|
||||
return self._url_prefix
|
||||
|
||||
@property
|
||||
def blueprints(self):
|
||||
def blueprints(self) -> List["sanic.Blueprint"]:
|
||||
"""
|
||||
Retrieve a list of all the available blueprints under this group.
|
||||
|
||||
:return: List of Blueprint instance
|
||||
"""
|
||||
return self._blueprints
|
||||
|
||||
@property
|
||||
def version(self) -> Optional[Union[str, int, float]]:
|
||||
"""
|
||||
API Version for the Blueprint Group. This will be applied only in case
|
||||
if the Blueprint doesn't already have a version specified
|
||||
|
||||
:return: Version information
|
||||
"""
|
||||
return self._version
|
||||
|
||||
@property
|
||||
def strict_slashes(self) -> Optional[bool]:
|
||||
"""
|
||||
URL Slash termination behavior configuration
|
||||
|
||||
:return: bool
|
||||
"""
|
||||
return self._strict_slashes
|
||||
|
||||
def __iter__(self):
|
||||
"""Tun the class Blueprint Group into an Iterable item"""
|
||||
"""
|
||||
Tun the class Blueprint Group into an Iterable item
|
||||
"""
|
||||
return iter(self._blueprints)
|
||||
|
||||
def __getitem__(self, item):
|
||||
@@ -85,11 +156,39 @@ class BlueprintGroup(MutableSequence):
|
||||
def __len__(self) -> int:
|
||||
"""
|
||||
Get the Length of the blueprint group object.
|
||||
|
||||
:return: Length of Blueprint group object
|
||||
"""
|
||||
return len(self._blueprints)
|
||||
|
||||
def insert(self, index: int, item: object) -> None:
|
||||
def _sanitize_blueprint(self, bp: "sanic.Blueprint") -> "sanic.Blueprint":
|
||||
"""
|
||||
Sanitize the Blueprint Entity to override the Version and strict slash
|
||||
behaviors as required.
|
||||
|
||||
:param bp: Sanic Blueprint entity Object
|
||||
:return: Modified Blueprint
|
||||
"""
|
||||
if self._url_prefix:
|
||||
merged_prefix = "/".join(
|
||||
u.strip("/") for u in [self._url_prefix, bp.url_prefix or ""]
|
||||
).rstrip("/")
|
||||
bp.url_prefix = f"/{merged_prefix}"
|
||||
for _attr in ["version", "strict_slashes"]:
|
||||
if getattr(bp, _attr) is None:
|
||||
setattr(bp, _attr, getattr(self, _attr))
|
||||
return bp
|
||||
|
||||
def append(self, value: "sanic.Blueprint") -> None:
|
||||
"""
|
||||
The Abstract class `MutableSequence` leverages this append method to
|
||||
perform the `BlueprintGroup.append` operation.
|
||||
:param value: New `Blueprint` object.
|
||||
:return: None
|
||||
"""
|
||||
self._blueprints.append(self._sanitize_blueprint(bp=value))
|
||||
|
||||
def insert(self, index: int, item: "sanic.Blueprint") -> None:
|
||||
"""
|
||||
The Abstract class `MutableSequence` leverages this insert method to
|
||||
perform the `BlueprintGroup.append` operation.
|
||||
@@ -98,7 +197,7 @@ class BlueprintGroup(MutableSequence):
|
||||
:param item: New `Blueprint` object.
|
||||
:return: None
|
||||
"""
|
||||
self._blueprints.insert(index, item)
|
||||
self._blueprints.insert(index, self._sanitize_blueprint(item))
|
||||
|
||||
def middleware(self, *args, **kwargs):
|
||||
"""
|
||||
@@ -112,10 +211,13 @@ class BlueprintGroup(MutableSequence):
|
||||
:param kwargs: Optional Keyword arg to use with Middleware
|
||||
:return: Partial function to apply the middleware
|
||||
"""
|
||||
kwargs["bp_group"] = True
|
||||
|
||||
def register_middleware_for_blueprints(fn):
|
||||
for blueprint in self.blueprints:
|
||||
blueprint.middleware(fn, *args, **kwargs)
|
||||
|
||||
if args and callable(args[0]):
|
||||
fn = args[0]
|
||||
args = list(args)[1:]
|
||||
return register_middleware_for_blueprints(fn)
|
||||
return register_middleware_for_blueprints
|
||||
|
||||
@@ -1,49 +1,40 @@
|
||||
from collections import defaultdict, namedtuple
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from collections import defaultdict
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Union
|
||||
|
||||
from sanic_routing.exceptions import NotFound # type: ignore
|
||||
from sanic_routing.route import Route # type: ignore
|
||||
|
||||
from sanic.base import BaseSanic
|
||||
from sanic.blueprint_group import BlueprintGroup
|
||||
from sanic.constants import HTTP_METHODS
|
||||
from sanic.views import CompositionView
|
||||
|
||||
|
||||
FutureRoute = namedtuple(
|
||||
"FutureRoute",
|
||||
[
|
||||
"handler",
|
||||
"uri",
|
||||
"methods",
|
||||
"host",
|
||||
"strict_slashes",
|
||||
"stream",
|
||||
"version",
|
||||
"name",
|
||||
],
|
||||
)
|
||||
FutureListener = namedtuple(
|
||||
"FutureListener", ["handler", "uri", "methods", "host"]
|
||||
)
|
||||
FutureMiddleware = namedtuple(
|
||||
"FutureMiddleware", ["middleware", "args", "kwargs"]
|
||||
)
|
||||
FutureException = namedtuple("FutureException", ["handler", "args", "kwargs"])
|
||||
FutureStatic = namedtuple(
|
||||
"FutureStatic", ["uri", "file_or_directory", "args", "kwargs"]
|
||||
from sanic.exceptions import SanicException
|
||||
from sanic.models.futures import FutureRoute, FutureStatic
|
||||
from sanic.models.handler_types import (
|
||||
ListenerType,
|
||||
MiddlewareType,
|
||||
RouteHandler,
|
||||
)
|
||||
|
||||
|
||||
class Blueprint:
|
||||
def __init__(
|
||||
self,
|
||||
name,
|
||||
url_prefix=None,
|
||||
host=None,
|
||||
version=None,
|
||||
strict_slashes=None,
|
||||
):
|
||||
if TYPE_CHECKING:
|
||||
from sanic import Sanic # noqa
|
||||
|
||||
|
||||
class Blueprint(BaseSanic):
|
||||
"""
|
||||
In *Sanic* terminology, a **Blueprint** is a logical collection of
|
||||
URLs that perform a specific set of tasks which can be identified by
|
||||
a unique name.
|
||||
|
||||
It is the main tool for grouping functionality and similar endpoints.
|
||||
|
||||
`See user guide re: blueprints
|
||||
<https://sanicframework.org/guide/best-practices/blueprints.html>`__
|
||||
|
||||
:param name: unique name of the blueprint
|
||||
:param url_prefix: URL to be prefixed before all route URLs
|
||||
:param host: IP Address of FQDN for the sanic server to use.
|
||||
@@ -51,30 +42,116 @@ class Blueprint:
|
||||
:param strict_slashes: Enforce the API urls are requested with a
|
||||
training */*
|
||||
"""
|
||||
self.name = name
|
||||
self.url_prefix = url_prefix
|
||||
self.host = host
|
||||
|
||||
self.routes = []
|
||||
self.websocket_routes = []
|
||||
self.exceptions = []
|
||||
self.listeners = defaultdict(list)
|
||||
self.middlewares = []
|
||||
self.statics = []
|
||||
self.version = version
|
||||
__fake_slots__ = (
|
||||
"_apps",
|
||||
"_future_routes",
|
||||
"_future_statics",
|
||||
"_future_middleware",
|
||||
"_future_listeners",
|
||||
"_future_exceptions",
|
||||
"_future_signals",
|
||||
"ctx",
|
||||
"exceptions",
|
||||
"host",
|
||||
"listeners",
|
||||
"middlewares",
|
||||
"name",
|
||||
"routes",
|
||||
"statics",
|
||||
"strict_slashes",
|
||||
"url_prefix",
|
||||
"version",
|
||||
"websocket_routes",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
url_prefix: Optional[str] = None,
|
||||
host: Optional[str] = None,
|
||||
version: Optional[int] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self._apps: Set[Sanic] = set()
|
||||
self.ctx = SimpleNamespace()
|
||||
self.exceptions: List[RouteHandler] = []
|
||||
self.host = host
|
||||
self.listeners: Dict[str, List[ListenerType]] = {}
|
||||
self.middlewares: List[MiddlewareType] = []
|
||||
self.name = name
|
||||
self.routes: List[Route] = []
|
||||
self.statics: List[RouteHandler] = []
|
||||
self.strict_slashes = strict_slashes
|
||||
self.url_prefix = url_prefix
|
||||
self.version = version
|
||||
self.websocket_routes: List[Route] = []
|
||||
|
||||
def __repr__(self) -> str:
|
||||
args = ", ".join(
|
||||
[
|
||||
f'{attr}="{getattr(self, attr)}"'
|
||||
if isinstance(getattr(self, attr), str)
|
||||
else f"{attr}={getattr(self, attr)}"
|
||||
for attr in (
|
||||
"name",
|
||||
"url_prefix",
|
||||
"host",
|
||||
"version",
|
||||
"strict_slashes",
|
||||
)
|
||||
]
|
||||
)
|
||||
return f"Blueprint({args})"
|
||||
|
||||
@property
|
||||
def apps(self):
|
||||
if not self._apps:
|
||||
raise SanicException(
|
||||
f"{self} has not yet been registered to an app"
|
||||
)
|
||||
return self._apps
|
||||
|
||||
def route(self, *args, **kwargs):
|
||||
kwargs["apply"] = False
|
||||
return super().route(*args, **kwargs)
|
||||
|
||||
def static(self, *args, **kwargs):
|
||||
kwargs["apply"] = False
|
||||
return super().static(*args, **kwargs)
|
||||
|
||||
def middleware(self, *args, **kwargs):
|
||||
kwargs["apply"] = False
|
||||
return super().middleware(*args, **kwargs)
|
||||
|
||||
def listener(self, *args, **kwargs):
|
||||
kwargs["apply"] = False
|
||||
return super().listener(*args, **kwargs)
|
||||
|
||||
def exception(self, *args, **kwargs):
|
||||
kwargs["apply"] = False
|
||||
return super().exception(*args, **kwargs)
|
||||
|
||||
def signal(self, event: str, *args, **kwargs):
|
||||
kwargs["apply"] = False
|
||||
return super().signal(event, *args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def group(*blueprints, url_prefix=""):
|
||||
def group(*blueprints, url_prefix="", version=None, strict_slashes=None):
|
||||
"""
|
||||
Create a list of blueprints, optionally grouping them under a
|
||||
general URL prefix.
|
||||
|
||||
:param blueprints: blueprints to be registered as a group
|
||||
:param url_prefix: URL route to be prepended to all sub-prefixes
|
||||
:param version: API Version to be used for Blueprint group
|
||||
:param strict_slashes: Indicate strict slash termination behavior
|
||||
for URL
|
||||
"""
|
||||
|
||||
def chain(nested):
|
||||
def chain(nested) -> Iterable[Blueprint]:
|
||||
"""itertools.chain() but leaves strings untouched"""
|
||||
for i in nested:
|
||||
if isinstance(i, (list, tuple)):
|
||||
@@ -84,11 +161,12 @@ class Blueprint:
|
||||
else:
|
||||
yield i
|
||||
|
||||
bps = BlueprintGroup(url_prefix=url_prefix)
|
||||
bps = BlueprintGroup(
|
||||
url_prefix=url_prefix,
|
||||
version=version,
|
||||
strict_slashes=strict_slashes,
|
||||
)
|
||||
for bp in chain(blueprints):
|
||||
if bp.url_prefix is None:
|
||||
bp.url_prefix = ""
|
||||
bp.url_prefix = url_prefix + bp.url_prefix
|
||||
bps.append(bp)
|
||||
return bps
|
||||
|
||||
@@ -102,469 +180,107 @@ class Blueprint:
|
||||
*url_prefix* - URL Prefix to override the blueprint prefix
|
||||
"""
|
||||
|
||||
self._apps.add(app)
|
||||
url_prefix = options.get("url_prefix", self.url_prefix)
|
||||
|
||||
routes = []
|
||||
middleware = []
|
||||
exception_handlers = []
|
||||
listeners = defaultdict(list)
|
||||
|
||||
# Routes
|
||||
for future in self.routes:
|
||||
for future in self._future_routes:
|
||||
# attach the blueprint name to the handler so that it can be
|
||||
# prefixed properly in the router
|
||||
future.handler.__blueprintname__ = self.name
|
||||
# Prepend the blueprint URI prefix if available
|
||||
uri = url_prefix + future.uri if url_prefix else future.uri
|
||||
|
||||
version = future.version or self.version
|
||||
|
||||
_routes, _ = app.route(
|
||||
uri=uri[1:] if uri.startswith("//") else uri,
|
||||
methods=future.methods,
|
||||
host=future.host or self.host,
|
||||
strict_slashes=future.strict_slashes,
|
||||
stream=future.stream,
|
||||
version=version,
|
||||
name=future.name,
|
||||
)(future.handler)
|
||||
if _routes:
|
||||
routes += _routes
|
||||
|
||||
for future in self.websocket_routes:
|
||||
# attach the blueprint name to the handler so that it can be
|
||||
# prefixed properly in the router
|
||||
future.handler.__blueprintname__ = self.name
|
||||
# Prepend the blueprint URI prefix if available
|
||||
uri = url_prefix + future.uri if url_prefix else future.uri
|
||||
_routes, _ = app.websocket(
|
||||
uri=uri,
|
||||
host=future.host or self.host,
|
||||
strict_slashes=future.strict_slashes,
|
||||
name=future.name,
|
||||
)(future.handler)
|
||||
if _routes:
|
||||
routes += _routes
|
||||
|
||||
route_names = [route.name for route in routes]
|
||||
# Middleware
|
||||
for future in self.middlewares:
|
||||
if future.args or future.kwargs:
|
||||
app.register_named_middleware(
|
||||
future.middleware,
|
||||
route_names,
|
||||
*future.args,
|
||||
**future.kwargs
|
||||
strict_slashes = (
|
||||
self.strict_slashes
|
||||
if future.strict_slashes is None
|
||||
and self.strict_slashes is not None
|
||||
else future.strict_slashes
|
||||
)
|
||||
else:
|
||||
app.register_named_middleware(future.middleware, route_names)
|
||||
name = app._generate_name(future.name)
|
||||
|
||||
# Exceptions
|
||||
for future in self.exceptions:
|
||||
app.exception(*future.args, **future.kwargs)(future.handler)
|
||||
apply_route = FutureRoute(
|
||||
future.handler,
|
||||
uri[1:] if uri.startswith("//") else uri,
|
||||
future.methods,
|
||||
future.host or self.host,
|
||||
strict_slashes,
|
||||
future.stream,
|
||||
future.version or self.version,
|
||||
name,
|
||||
future.ignore_body,
|
||||
future.websocket,
|
||||
future.subprotocols,
|
||||
future.unquote,
|
||||
future.static,
|
||||
)
|
||||
|
||||
route = app._apply_route(apply_route)
|
||||
operation = (
|
||||
routes.extend if isinstance(route, list) else routes.append
|
||||
)
|
||||
operation(route)
|
||||
|
||||
# Static Files
|
||||
for future in self.statics:
|
||||
for future in self._future_statics:
|
||||
# Prepend the blueprint URI prefix if available
|
||||
uri = url_prefix + future.uri if url_prefix else future.uri
|
||||
app.static(
|
||||
uri, future.file_or_directory, *future.args, **future.kwargs
|
||||
)
|
||||
apply_route = FutureStatic(uri, *future[1:])
|
||||
route = app._apply_static(apply_route)
|
||||
routes.append(route)
|
||||
|
||||
route_names = [route.name for route in routes if route]
|
||||
|
||||
# Middleware
|
||||
if route_names:
|
||||
for future in self._future_middleware:
|
||||
middleware.append(app._apply_middleware(future, route_names))
|
||||
|
||||
# Exceptions
|
||||
for future in self._future_exceptions:
|
||||
exception_handlers.append(app._apply_exception_handler(future))
|
||||
|
||||
# Event listeners
|
||||
for event, listeners in self.listeners.items():
|
||||
for listener in listeners:
|
||||
app.listener(event)(listener)
|
||||
for listener in self._future_listeners:
|
||||
listeners[listener.event].append(app._apply_listener(listener))
|
||||
|
||||
def route(
|
||||
self,
|
||||
uri,
|
||||
methods=frozenset({"GET"}),
|
||||
host=None,
|
||||
strict_slashes=None,
|
||||
stream=False,
|
||||
version=None,
|
||||
name=None,
|
||||
):
|
||||
"""Create a blueprint route from a decorated function.
|
||||
for signal in self._future_signals:
|
||||
signal.condition.update({"blueprint": self.name})
|
||||
app._apply_signal(signal)
|
||||
|
||||
:param uri: endpoint at which the route will be accessible.
|
||||
:param methods: list of acceptable HTTP methods.
|
||||
:param host: IP Address of FQDN for the sanic server to use.
|
||||
:param strict_slashes: Enforce the API urls are requested with a
|
||||
training */*
|
||||
:param stream: If the route should provide a streaming support
|
||||
:param version: Blueprint Version
|
||||
:param name: Unique name to identify the Route
|
||||
self.routes = [route for route in routes if isinstance(route, Route)]
|
||||
|
||||
:return a decorated method that when invoked will return an object
|
||||
of type :class:`FutureRoute`
|
||||
"""
|
||||
if strict_slashes is None:
|
||||
strict_slashes = self.strict_slashes
|
||||
# Deprecate these in 21.6
|
||||
self.websocket_routes = [
|
||||
route for route in self.routes if route.ctx.websocket
|
||||
]
|
||||
self.middlewares = middleware
|
||||
self.exceptions = exception_handlers
|
||||
self.listeners = dict(listeners)
|
||||
|
||||
def decorator(handler):
|
||||
route = FutureRoute(
|
||||
handler,
|
||||
uri,
|
||||
methods,
|
||||
host,
|
||||
strict_slashes,
|
||||
stream,
|
||||
version,
|
||||
name,
|
||||
)
|
||||
self.routes.append(route)
|
||||
return handler
|
||||
|
||||
return decorator
|
||||
|
||||
def add_route(
|
||||
self,
|
||||
handler,
|
||||
uri,
|
||||
methods=frozenset({"GET"}),
|
||||
host=None,
|
||||
strict_slashes=None,
|
||||
version=None,
|
||||
name=None,
|
||||
stream=False,
|
||||
):
|
||||
"""Create a blueprint route from a function.
|
||||
|
||||
:param handler: function for handling uri requests. Accepts function,
|
||||
or class instance with a view_class method.
|
||||
:param uri: endpoint at which the route will be accessible.
|
||||
:param methods: list of acceptable HTTP methods.
|
||||
:param host: IP Address of FQDN for the sanic server to use.
|
||||
:param strict_slashes: Enforce the API urls are requested with a
|
||||
training */*
|
||||
:param version: Blueprint Version
|
||||
:param name: user defined route name for url_for
|
||||
:param stream: boolean specifying if the handler is a stream handler
|
||||
:return: function or class instance
|
||||
"""
|
||||
# Handle HTTPMethodView differently
|
||||
if hasattr(handler, "view_class"):
|
||||
methods = set()
|
||||
|
||||
for method in HTTP_METHODS:
|
||||
if getattr(handler.view_class, method.lower(), None):
|
||||
methods.add(method)
|
||||
|
||||
if strict_slashes is None:
|
||||
strict_slashes = self.strict_slashes
|
||||
|
||||
# handle composition view differently
|
||||
if isinstance(handler, CompositionView):
|
||||
methods = handler.handlers.keys()
|
||||
|
||||
self.route(
|
||||
uri=uri,
|
||||
methods=methods,
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
)(handler)
|
||||
return handler
|
||||
|
||||
def websocket(
|
||||
self, uri, host=None, strict_slashes=None, version=None, name=None
|
||||
):
|
||||
"""Create a blueprint websocket route from a decorated function.
|
||||
|
||||
:param uri: endpoint at which the route will be accessible.
|
||||
:param host: IP Address of FQDN for the sanic server to use.
|
||||
:param strict_slashes: Enforce the API urls are requested with a
|
||||
training */*
|
||||
:param version: Blueprint Version
|
||||
:param name: Unique name to identify the Websocket Route
|
||||
"""
|
||||
if strict_slashes is None:
|
||||
strict_slashes = self.strict_slashes
|
||||
|
||||
def decorator(handler):
|
||||
route = FutureRoute(
|
||||
handler, uri, [], host, strict_slashes, False, version, name
|
||||
)
|
||||
self.websocket_routes.append(route)
|
||||
return handler
|
||||
|
||||
return decorator
|
||||
|
||||
def add_websocket_route(
|
||||
self, handler, uri, host=None, version=None, name=None
|
||||
):
|
||||
"""Create a blueprint websocket route from a function.
|
||||
|
||||
:param handler: function for handling uri requests. Accepts function,
|
||||
or class instance with a view_class method.
|
||||
:param uri: endpoint at which the route will be accessible.
|
||||
:param host: IP Address of FQDN for the sanic server to use.
|
||||
:param version: Blueprint Version
|
||||
:param name: Unique name to identify the Websocket Route
|
||||
:return: function or class instance
|
||||
"""
|
||||
self.websocket(uri=uri, host=host, version=version, name=name)(handler)
|
||||
return handler
|
||||
|
||||
def listener(self, event):
|
||||
"""Create a listener from a decorated function.
|
||||
|
||||
:param event: Event to listen to.
|
||||
"""
|
||||
|
||||
def decorator(listener):
|
||||
self.listeners[event].append(listener)
|
||||
return listener
|
||||
|
||||
return decorator
|
||||
|
||||
def middleware(self, *args, **kwargs):
|
||||
"""
|
||||
Create a blueprint middleware from a decorated function.
|
||||
|
||||
:param args: Positional arguments to be used while invoking the
|
||||
middleware
|
||||
:param kwargs: optional keyword args that can be used with the
|
||||
middleware.
|
||||
"""
|
||||
|
||||
def register_middleware(_middleware):
|
||||
future_middleware = FutureMiddleware(_middleware, args, kwargs)
|
||||
self.middlewares.append(future_middleware)
|
||||
return _middleware
|
||||
|
||||
# Detect which way this was called, @middleware or @middleware('AT')
|
||||
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
|
||||
middleware = args[0]
|
||||
args = []
|
||||
return register_middleware(middleware)
|
||||
else:
|
||||
if kwargs.get("bp_group") and callable(args[0]):
|
||||
middleware = args[0]
|
||||
args = args[1:]
|
||||
kwargs.pop("bp_group")
|
||||
return register_middleware(middleware)
|
||||
else:
|
||||
return register_middleware
|
||||
|
||||
def exception(self, *args, **kwargs):
|
||||
"""
|
||||
This method enables the process of creating a global exception
|
||||
handler for the current blueprint under question.
|
||||
|
||||
:param args: List of Python exceptions to be caught by the handler
|
||||
:param kwargs: Additional optional arguments to be passed to the
|
||||
exception handler
|
||||
|
||||
:return a decorated method to handle global exceptions for any
|
||||
route registered under this blueprint.
|
||||
"""
|
||||
|
||||
def decorator(handler):
|
||||
exception = FutureException(handler, args, kwargs)
|
||||
self.exceptions.append(exception)
|
||||
return handler
|
||||
|
||||
return decorator
|
||||
|
||||
def static(self, uri, file_or_directory, *args, **kwargs):
|
||||
"""Create a blueprint static route from a decorated function.
|
||||
|
||||
:param uri: endpoint at which the route will be accessible.
|
||||
:param file_or_directory: Static asset.
|
||||
"""
|
||||
name = kwargs.pop("name", "static")
|
||||
if not name.startswith(self.name + "."):
|
||||
name = "{}.{}".format(self.name, name)
|
||||
kwargs.update(name=name)
|
||||
|
||||
strict_slashes = kwargs.get("strict_slashes")
|
||||
if strict_slashes is None and self.strict_slashes is not None:
|
||||
kwargs.update(strict_slashes=self.strict_slashes)
|
||||
|
||||
static = FutureStatic(uri, file_or_directory, args, kwargs)
|
||||
self.statics.append(static)
|
||||
|
||||
# Shorthand method decorators
|
||||
def get(
|
||||
self, uri, host=None, strict_slashes=None, version=None, name=None
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **GET** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **GET** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"GET"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
async def dispatch(self, *args, **kwargs):
|
||||
condition = kwargs.pop("condition", {})
|
||||
condition.update({"blueprint": self.name})
|
||||
kwargs["condition"] = condition
|
||||
await asyncio.gather(
|
||||
*[app.dispatch(*args, **kwargs) for app in self.apps]
|
||||
)
|
||||
|
||||
def post(
|
||||
self,
|
||||
uri,
|
||||
host=None,
|
||||
strict_slashes=None,
|
||||
stream=False,
|
||||
version=None,
|
||||
name=None,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **POST** *HTTP* method
|
||||
def event(self, event: str, timeout: Optional[Union[int, float]] = None):
|
||||
events = set()
|
||||
for app in self.apps:
|
||||
signal = app.signal_router.name_index.get(event)
|
||||
if not signal:
|
||||
raise NotFound("Could not find signal %s" % event)
|
||||
events.add(signal.ctx.event)
|
||||
|
||||
:param uri: URL to be tagged to **POST** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def put(
|
||||
self,
|
||||
uri,
|
||||
host=None,
|
||||
strict_slashes=None,
|
||||
stream=False,
|
||||
version=None,
|
||||
name=None,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **PUT** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **PUT** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def head(
|
||||
self, uri, host=None, strict_slashes=None, version=None, name=None
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **HEAD** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **HEAD** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"HEAD"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
)
|
||||
|
||||
def options(
|
||||
self, uri, host=None, strict_slashes=None, version=None, name=None
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **OPTIONS** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **OPTIONS** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"OPTIONS"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
)
|
||||
|
||||
def patch(
|
||||
self,
|
||||
uri,
|
||||
host=None,
|
||||
strict_slashes=None,
|
||||
stream=False,
|
||||
version=None,
|
||||
name=None,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **PATCH** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **PATCH** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def delete(
|
||||
self, uri, host=None, strict_slashes=None, version=None, name=None
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **DELETE** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **DELETE** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
|
||||
if the request URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:return: Object decorated with :func:`route` method
|
||||
"""
|
||||
return self.route(
|
||||
uri,
|
||||
methods=frozenset({"DELETE"}),
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
return asyncio.wait(
|
||||
[event.wait() for event in events],
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,76 @@
|
||||
import asyncio
|
||||
import os
|
||||
import signal
|
||||
|
||||
from sys import argv
|
||||
|
||||
from multidict import CIMultiDict # type: ignore
|
||||
|
||||
|
||||
OS_IS_WINDOWS = os.name == "nt"
|
||||
|
||||
|
||||
class Header(CIMultiDict):
|
||||
def get_all(self, key):
|
||||
"""
|
||||
Container used for both request and response headers. It is a subclass of
|
||||
`CIMultiDict
|
||||
<https://multidict.readthedocs.io/en/stable/multidict.html#cimultidictproxy>`_.
|
||||
|
||||
It allows for multiple values for a single key in keeping with the HTTP
|
||||
spec. Also, all keys are *case in-sensitive*.
|
||||
|
||||
Please checkout `the MultiDict documentation
|
||||
<https://multidict.readthedocs.io/en/stable/multidict.html#multidict>`_
|
||||
for more details about how to use the object. In general, it should work
|
||||
very similar to a regular dictionary.
|
||||
"""
|
||||
|
||||
def get_all(self, key: str):
|
||||
"""
|
||||
Convenience method mapped to ``getall()``.
|
||||
"""
|
||||
return self.getall(key, default=[])
|
||||
|
||||
|
||||
use_trio = argv[0].endswith("hypercorn") and "trio" in argv
|
||||
|
||||
if use_trio: # pragma: no cover
|
||||
import trio # type: ignore
|
||||
|
||||
def stat_async(path):
|
||||
return trio.Path(path).stat()
|
||||
|
||||
open_async = trio.open_file
|
||||
CancelledErrors = tuple([asyncio.CancelledError, trio.Cancelled])
|
||||
else:
|
||||
from aiofiles import open as aio_open # type: ignore
|
||||
from aiofiles.os import stat as stat_async # type: ignore # noqa: F401
|
||||
|
||||
async def open_async(file, mode="r", **kwargs):
|
||||
return aio_open(file, mode, **kwargs)
|
||||
|
||||
CancelledErrors = tuple([asyncio.CancelledError])
|
||||
|
||||
|
||||
def ctrlc_workaround_for_windows(app):
|
||||
async def stay_active(app):
|
||||
"""Asyncio wakeups to allow receiving SIGINT in Python"""
|
||||
while not die:
|
||||
# If someone else stopped the app, just exit
|
||||
if app.is_stopping:
|
||||
return
|
||||
# Windows Python blocks signal handlers while the event loop is
|
||||
# waiting for I/O. Frequent wakeups keep interrupts flowing.
|
||||
await asyncio.sleep(0.1)
|
||||
# Can't be called from signal handler, so call it from here
|
||||
app.stop()
|
||||
|
||||
def ctrlc_handler(sig, frame):
|
||||
nonlocal die
|
||||
if die:
|
||||
raise KeyboardInterrupt("Non-graceful Ctrl+C")
|
||||
die = True
|
||||
|
||||
die = False
|
||||
signal.signal(signal.SIGINT, ctrlc_handler)
|
||||
app.add_task(stay_active)
|
||||
|
||||
176
sanic/config.py
176
sanic/config.py
@@ -1,8 +1,9 @@
|
||||
import os
|
||||
import types
|
||||
from inspect import isclass
|
||||
from os import environ
|
||||
from pathlib import Path
|
||||
from typing import Any, Union
|
||||
|
||||
from sanic.exceptions import PyFileError
|
||||
from sanic.helpers import import_string
|
||||
from .utils import load_module_from_file_location, str_to_bool
|
||||
|
||||
|
||||
SANIC_PREFIX = "SANIC_"
|
||||
@@ -16,20 +17,26 @@ BASE_LOGO = """
|
||||
DEFAULT_CONFIG = {
|
||||
"REQUEST_MAX_SIZE": 100000000, # 100 megabytes
|
||||
"REQUEST_BUFFER_QUEUE_SIZE": 100,
|
||||
"REQUEST_BUFFER_SIZE": 65536, # 64 KiB
|
||||
"REQUEST_TIMEOUT": 60, # 60 seconds
|
||||
"RESPONSE_TIMEOUT": 60, # 60 seconds
|
||||
"KEEP_ALIVE": True,
|
||||
"KEEP_ALIVE_TIMEOUT": 5, # 5 seconds
|
||||
"WEBSOCKET_MAX_SIZE": 2 ** 20, # 1 megabytes
|
||||
"WEBSOCKET_MAX_SIZE": 2 ** 20, # 1 megabyte
|
||||
"WEBSOCKET_MAX_QUEUE": 32,
|
||||
"WEBSOCKET_READ_LIMIT": 2 ** 16,
|
||||
"WEBSOCKET_WRITE_LIMIT": 2 ** 16,
|
||||
"WEBSOCKET_PING_TIMEOUT": 20,
|
||||
"WEBSOCKET_PING_INTERVAL": 20,
|
||||
"GRACEFUL_SHUTDOWN_TIMEOUT": 15.0, # 15 sec
|
||||
"ACCESS_LOG": True,
|
||||
"FORWARDED_SECRET": None,
|
||||
"REAL_IP_HEADER": None,
|
||||
"PROXIES_COUNT": None,
|
||||
"FORWARDED_FOR_HEADER": "X-Forwarded-For",
|
||||
"REQUEST_ID_HEADER": "X-Request-ID",
|
||||
"FALLBACK_ERROR_FORMAT": "html",
|
||||
"REGISTER": True,
|
||||
}
|
||||
|
||||
|
||||
@@ -51,81 +58,26 @@ class Config(dict):
|
||||
try:
|
||||
return self[attr]
|
||||
except KeyError as ke:
|
||||
raise AttributeError("Config has no '{}'".format(ke.args[0]))
|
||||
raise AttributeError(f"Config has no '{ke.args[0]}'")
|
||||
|
||||
def __setattr__(self, attr, value):
|
||||
self[attr] = value
|
||||
|
||||
def from_envvar(self, variable_name):
|
||||
"""Load a configuration from an environment variable pointing to
|
||||
a configuration file.
|
||||
|
||||
:param variable_name: name of the environment variable
|
||||
:return: bool. ``True`` if able to load config, ``False`` otherwise.
|
||||
"""
|
||||
config_file = os.environ.get(variable_name)
|
||||
if not config_file:
|
||||
raise RuntimeError(
|
||||
"The environment variable %r is not set and "
|
||||
"thus configuration could not be loaded." % variable_name
|
||||
)
|
||||
return self.from_pyfile(config_file)
|
||||
|
||||
def from_pyfile(self, filename):
|
||||
"""Update the values in the config from a Python file.
|
||||
Only the uppercase variables in that module are stored in the config.
|
||||
|
||||
:param filename: an absolute path to the config file
|
||||
"""
|
||||
module = types.ModuleType("config")
|
||||
module.__file__ = filename
|
||||
try:
|
||||
with open(filename) as config_file:
|
||||
exec( # nosec
|
||||
compile(config_file.read(), filename, "exec"),
|
||||
module.__dict__,
|
||||
)
|
||||
except IOError as e:
|
||||
e.strerror = "Unable to load configuration file (%s)" % e.strerror
|
||||
raise
|
||||
except Exception as e:
|
||||
raise PyFileError(filename) from e
|
||||
|
||||
self.from_object(module)
|
||||
return True
|
||||
|
||||
def from_object(self, obj):
|
||||
"""Update the values from the given object.
|
||||
Objects are usually either modules or classes.
|
||||
|
||||
Just the uppercase variables in that object are stored in the config.
|
||||
Example usage::
|
||||
|
||||
from yourapplication import default_config
|
||||
app.config.from_object(default_config)
|
||||
|
||||
or also:
|
||||
app.config.from_object('myproject.config.MyConfigClass')
|
||||
|
||||
You should not use this function to load the actual configuration but
|
||||
rather configuration defaults. The actual config should be loaded
|
||||
with :meth:`from_pyfile` and ideally from a location not within the
|
||||
package because the package might be installed system wide.
|
||||
|
||||
:param obj: an object holding the configuration
|
||||
"""
|
||||
if isinstance(obj, str):
|
||||
obj = import_string(obj)
|
||||
for key in dir(obj):
|
||||
if key.isupper():
|
||||
self[key] = getattr(obj, key)
|
||||
|
||||
def load_environment_vars(self, prefix=SANIC_PREFIX):
|
||||
"""
|
||||
Looks for prefixed environment variables and applies
|
||||
them to the configuration if present.
|
||||
them to the configuration if present. This is called automatically when
|
||||
Sanic starts up to load environment variables into config.
|
||||
|
||||
It will automatically hyrdate the following types:
|
||||
|
||||
- ``int``
|
||||
- ``float``
|
||||
- ``bool``
|
||||
|
||||
Anything else will be imported as a ``str``.
|
||||
"""
|
||||
for k, v in os.environ.items():
|
||||
for k, v in environ.items():
|
||||
if k.startswith(prefix):
|
||||
_, config_key = k.split(prefix, 1)
|
||||
try:
|
||||
@@ -135,23 +87,75 @@ class Config(dict):
|
||||
self[config_key] = float(v)
|
||||
except ValueError:
|
||||
try:
|
||||
self[config_key] = strtobool(v)
|
||||
self[config_key] = str_to_bool(v)
|
||||
except ValueError:
|
||||
self[config_key] = v
|
||||
|
||||
|
||||
def strtobool(val):
|
||||
def update_config(self, config: Union[bytes, str, dict, Any]):
|
||||
"""
|
||||
This function was borrowed from distutils.utils. While distutils
|
||||
is part of stdlib, it feels odd to use distutils in main application code.
|
||||
Update app.config.
|
||||
|
||||
The function was modified to walk its talk and actually return bool
|
||||
and not int.
|
||||
.. note::
|
||||
|
||||
Only upper case settings are considered
|
||||
|
||||
You can upload app config by providing path to py file
|
||||
holding settings.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# /some/py/file
|
||||
A = 1
|
||||
B = 2
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
config.update_config("${some}/py/file")
|
||||
|
||||
Yes you can put environment variable here, but they must be provided
|
||||
in format: ``${some_env_var}``, and mark that ``$some_env_var`` is
|
||||
treated as plain string.
|
||||
|
||||
You can upload app config by providing dict holding settings.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
d = {"A": 1, "B": 2}
|
||||
config.update_config(d)
|
||||
|
||||
You can upload app config by providing any object holding settings,
|
||||
but in such case config.__dict__ will be used as dict holding settings.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class C:
|
||||
A = 1
|
||||
B = 2
|
||||
|
||||
config.update_config(C)
|
||||
|
||||
`See user guide re: config
|
||||
<https://sanicframework.org/guide/deployment/configuration.html>`__
|
||||
"""
|
||||
val = val.lower()
|
||||
if val in ("y", "yes", "t", "true", "on", "1"):
|
||||
return True
|
||||
elif val in ("n", "no", "f", "false", "off", "0"):
|
||||
return False
|
||||
else:
|
||||
raise ValueError("invalid truth value %r" % (val,))
|
||||
|
||||
if isinstance(config, (bytes, str, Path)):
|
||||
config = load_module_from_file_location(location=config)
|
||||
|
||||
if not isinstance(config, dict):
|
||||
cfg = {}
|
||||
if not isclass(config):
|
||||
cfg.update(
|
||||
{
|
||||
key: getattr(config, key)
|
||||
for key in config.__class__.__dict__.keys()
|
||||
}
|
||||
)
|
||||
|
||||
config = dict(config.__dict__)
|
||||
config.update(cfg)
|
||||
|
||||
config = dict(filter(lambda i: i[0].isupper(), config.items()))
|
||||
|
||||
self.update(config)
|
||||
|
||||
load = update_config
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
HTTP_METHODS = ("GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE")
|
||||
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
|
||||
|
||||
@@ -2,6 +2,7 @@ import re
|
||||
import string
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Dict
|
||||
|
||||
|
||||
DEFAULT_MAX_AGE = 0
|
||||
@@ -41,16 +42,17 @@ _is_legal_key = re.compile("[%s]+" % re.escape(_LegalChars)).fullmatch
|
||||
|
||||
|
||||
class CookieJar(dict):
|
||||
"""CookieJar dynamically writes headers as cookies are added and removed
|
||||
"""
|
||||
CookieJar dynamically writes headers as cookies are added and removed
|
||||
It gets around the limitation of one header per name by using the
|
||||
MultiHeader class to provide a unique key that encodes to Set-Cookie.
|
||||
"""
|
||||
|
||||
def __init__(self, headers):
|
||||
super().__init__()
|
||||
self.headers = headers
|
||||
self.cookie_headers = {}
|
||||
self.header_key = "Set-Cookie"
|
||||
self.headers: Dict[str, str] = headers
|
||||
self.cookie_headers: Dict[str, str] = {}
|
||||
self.header_key: str = "Set-Cookie"
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
# If this cookie doesn't exist, add it to the header keys
|
||||
@@ -109,7 +111,7 @@ class Cookie(dict):
|
||||
if value is not False:
|
||||
if key.lower() == "max-age":
|
||||
if not str(value).isdigit():
|
||||
value = DEFAULT_MAX_AGE
|
||||
raise ValueError("Cookie max-age must be an integer")
|
||||
elif key.lower() == "expires":
|
||||
if not isinstance(value, datetime):
|
||||
raise TypeError(
|
||||
|
||||
380
sanic/errorpages.py
Normal file
380
sanic/errorpages.py
Normal file
@@ -0,0 +1,380 @@
|
||||
"""
|
||||
Sanic `provides a pattern
|
||||
<https://sanicframework.org/guide/best-practices/exceptions.html#using-sanic-exceptions>`_
|
||||
for providing a response when an exception occurs. However, if you do no handle
|
||||
an exception, it will provide a fallback. There are three fallback types:
|
||||
|
||||
- HTML - *default*
|
||||
- Text
|
||||
- JSON
|
||||
|
||||
Setting ``app.config.FALLBACK_ERROR_FORMAT = "auto"`` will enable a switch that
|
||||
will attempt to provide an appropriate response format based upon the
|
||||
request type.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import typing as t
|
||||
|
||||
from functools import partial
|
||||
from traceback import extract_tb
|
||||
|
||||
from sanic.exceptions import InvalidUsage, SanicException
|
||||
from sanic.helpers import STATUS_CODES
|
||||
from sanic.request import Request
|
||||
from sanic.response import HTTPResponse, html, json, text
|
||||
|
||||
|
||||
try:
|
||||
from ujson import dumps
|
||||
|
||||
dumps = partial(dumps, escape_forward_slashes=False)
|
||||
except ImportError: # noqa
|
||||
from json import dumps # type: ignore
|
||||
|
||||
|
||||
FALLBACK_TEXT = (
|
||||
"The server encountered an internal error and "
|
||||
"cannot complete your request."
|
||||
)
|
||||
FALLBACK_STATUS = 500
|
||||
|
||||
|
||||
class BaseRenderer:
|
||||
"""
|
||||
Base class that all renderers must inherit from.
|
||||
"""
|
||||
|
||||
def __init__(self, request, exception, debug):
|
||||
self.request = request
|
||||
self.exception = exception
|
||||
self.debug = debug
|
||||
|
||||
@property
|
||||
def headers(self):
|
||||
if isinstance(self.exception, SanicException):
|
||||
return getattr(self.exception, "headers", {})
|
||||
return {}
|
||||
|
||||
@property
|
||||
def status(self):
|
||||
if isinstance(self.exception, SanicException):
|
||||
return getattr(self.exception, "status_code", FALLBACK_STATUS)
|
||||
return FALLBACK_STATUS
|
||||
|
||||
@property
|
||||
def text(self):
|
||||
if self.debug or isinstance(self.exception, SanicException):
|
||||
return str(self.exception)
|
||||
return FALLBACK_TEXT
|
||||
|
||||
@property
|
||||
def title(self):
|
||||
status_text = STATUS_CODES.get(self.status, b"Error Occurred").decode()
|
||||
return f"{self.status} — {status_text}"
|
||||
|
||||
def render(self) -> HTTPResponse:
|
||||
"""
|
||||
Outputs the exception as a :class:`HTTPResponse`.
|
||||
|
||||
:return: The formatted exception
|
||||
:rtype: str
|
||||
"""
|
||||
output = (
|
||||
self.full
|
||||
if self.debug and not getattr(self.exception, "quiet", False)
|
||||
else self.minimal
|
||||
)
|
||||
return output()
|
||||
|
||||
def minimal(self) -> HTTPResponse: # noqa
|
||||
"""
|
||||
Provide a formatted message that is meant to not show any sensitive
|
||||
data or details.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def full(self) -> HTTPResponse: # noqa
|
||||
"""
|
||||
Provide a formatted message that has all details and is mean to be used
|
||||
primarily for debugging and non-production environments.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class HTMLRenderer(BaseRenderer):
|
||||
"""
|
||||
Render an exception as HTML.
|
||||
|
||||
The default fallback type.
|
||||
"""
|
||||
|
||||
TRACEBACK_STYLE = """
|
||||
html { font-family: sans-serif }
|
||||
h2 { color: #888; }
|
||||
.tb-wrapper p { margin: 0 }
|
||||
.frame-border { margin: 1rem }
|
||||
.frame-line > * { padding: 0.3rem 0.6rem }
|
||||
.frame-line { margin-bottom: 0.3rem }
|
||||
.frame-code { font-size: 16px; padding-left: 4ch }
|
||||
.tb-wrapper { border: 1px solid #eee }
|
||||
.tb-header { background: #eee; padding: 0.3rem; font-weight: bold }
|
||||
.frame-descriptor { background: #e2eafb; font-size: 14px }
|
||||
"""
|
||||
TRACEBACK_WRAPPER_HTML = (
|
||||
"<div class=tb-header>{exc_name}: {exc_value}</div>"
|
||||
"<div class=tb-wrapper>{frame_html}</div>"
|
||||
)
|
||||
TRACEBACK_BORDER = (
|
||||
"<div class=frame-border>"
|
||||
"The above exception was the direct cause of the following exception:"
|
||||
"</div>"
|
||||
)
|
||||
TRACEBACK_LINE_HTML = (
|
||||
"<div class=frame-line>"
|
||||
"<p class=frame-descriptor>"
|
||||
"File {0.filename}, line <i>{0.lineno}</i>, "
|
||||
"in <code><b>{0.name}</b></code>"
|
||||
"<p class=frame-code><code>{0.line}</code>"
|
||||
"</div>"
|
||||
)
|
||||
OUTPUT_HTML = (
|
||||
"<!DOCTYPE html><html lang=en>"
|
||||
"<meta charset=UTF-8><title>{title}</title>\n"
|
||||
"<style>{style}</style>\n"
|
||||
"<h1>{title}</h1><p>{text}\n"
|
||||
"{body}"
|
||||
)
|
||||
|
||||
def full(self) -> HTTPResponse:
|
||||
return html(
|
||||
self.OUTPUT_HTML.format(
|
||||
title=self.title,
|
||||
text=self.text,
|
||||
style=self.TRACEBACK_STYLE,
|
||||
body=self._generate_body(),
|
||||
),
|
||||
status=self.status,
|
||||
)
|
||||
|
||||
def minimal(self) -> HTTPResponse:
|
||||
return html(
|
||||
self.OUTPUT_HTML.format(
|
||||
title=self.title,
|
||||
text=self.text,
|
||||
style=self.TRACEBACK_STYLE,
|
||||
body="",
|
||||
),
|
||||
status=self.status,
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
@property
|
||||
def text(self):
|
||||
return escape(super().text)
|
||||
|
||||
@property
|
||||
def title(self):
|
||||
return escape(f"⚠️ {super().title}")
|
||||
|
||||
def _generate_body(self):
|
||||
_, exc_value, __ = sys.exc_info()
|
||||
exceptions = []
|
||||
while exc_value:
|
||||
exceptions.append(self._format_exc(exc_value))
|
||||
exc_value = exc_value.__cause__
|
||||
|
||||
traceback_html = self.TRACEBACK_BORDER.join(reversed(exceptions))
|
||||
appname = escape(self.request.app.name)
|
||||
name = escape(self.exception.__class__.__name__)
|
||||
value = escape(self.exception)
|
||||
path = escape(self.request.path)
|
||||
lines = [
|
||||
f"<h2>Traceback of {appname} (most recent call last):</h2>",
|
||||
f"{traceback_html}",
|
||||
"<div class=summary><p>",
|
||||
f"<b>{name}: {value}</b> while handling path <code>{path}</code>",
|
||||
"</div>",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
def _format_exc(self, exc):
|
||||
frames = extract_tb(exc.__traceback__)
|
||||
frame_html = "".join(
|
||||
self.TRACEBACK_LINE_HTML.format(frame) for frame in frames
|
||||
)
|
||||
return self.TRACEBACK_WRAPPER_HTML.format(
|
||||
exc_name=escape(exc.__class__.__name__),
|
||||
exc_value=escape(exc),
|
||||
frame_html=frame_html,
|
||||
)
|
||||
|
||||
|
||||
class TextRenderer(BaseRenderer):
|
||||
"""
|
||||
Render an exception as plain text.
|
||||
"""
|
||||
|
||||
OUTPUT_TEXT = "{title}\n{bar}\n{text}\n\n{body}"
|
||||
SPACER = " "
|
||||
|
||||
def full(self) -> HTTPResponse:
|
||||
return text(
|
||||
self.OUTPUT_TEXT.format(
|
||||
title=self.title,
|
||||
text=self.text,
|
||||
bar=("=" * len(self.title)),
|
||||
body=self._generate_body(),
|
||||
),
|
||||
status=self.status,
|
||||
)
|
||||
|
||||
def minimal(self) -> HTTPResponse:
|
||||
return text(
|
||||
self.OUTPUT_TEXT.format(
|
||||
title=self.title,
|
||||
text=self.text,
|
||||
bar=("=" * len(self.title)),
|
||||
body="",
|
||||
),
|
||||
status=self.status,
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
@property
|
||||
def title(self):
|
||||
return f"⚠️ {super().title}"
|
||||
|
||||
def _generate_body(self):
|
||||
_, exc_value, __ = sys.exc_info()
|
||||
exceptions = []
|
||||
|
||||
lines = [
|
||||
f"{self.exception.__class__.__name__}: {self.exception} while "
|
||||
f"handling path {self.request.path}",
|
||||
f"Traceback of {self.request.app.name} (most recent call last):\n",
|
||||
]
|
||||
|
||||
while exc_value:
|
||||
exceptions.append(self._format_exc(exc_value))
|
||||
exc_value = exc_value.__cause__
|
||||
|
||||
return "\n".join(lines + exceptions[::-1])
|
||||
|
||||
def _format_exc(self, exc):
|
||||
frames = "\n\n".join(
|
||||
[
|
||||
f"{self.SPACER * 2}File {frame.filename}, "
|
||||
f"line {frame.lineno}, in "
|
||||
f"{frame.name}\n{self.SPACER * 2}{frame.line}"
|
||||
for frame in extract_tb(exc.__traceback__)
|
||||
]
|
||||
)
|
||||
return f"{self.SPACER}{exc.__class__.__name__}: {exc}\n{frames}"
|
||||
|
||||
|
||||
class JSONRenderer(BaseRenderer):
|
||||
"""
|
||||
Render an exception as JSON.
|
||||
"""
|
||||
|
||||
def full(self) -> HTTPResponse:
|
||||
output = self._generate_output(full=True)
|
||||
return json(output, status=self.status, dumps=dumps)
|
||||
|
||||
def minimal(self) -> HTTPResponse:
|
||||
output = self._generate_output(full=False)
|
||||
return json(output, status=self.status, dumps=dumps)
|
||||
|
||||
def _generate_output(self, *, full):
|
||||
output = {
|
||||
"description": self.title,
|
||||
"status": self.status,
|
||||
"message": self.text,
|
||||
}
|
||||
|
||||
if full:
|
||||
_, exc_value, __ = sys.exc_info()
|
||||
exceptions = []
|
||||
|
||||
while exc_value:
|
||||
exceptions.append(
|
||||
{
|
||||
"type": exc_value.__class__.__name__,
|
||||
"exception": str(exc_value),
|
||||
"frames": [
|
||||
{
|
||||
"file": frame.filename,
|
||||
"line": frame.lineno,
|
||||
"name": frame.name,
|
||||
"src": frame.line,
|
||||
}
|
||||
for frame in extract_tb(exc_value.__traceback__)
|
||||
],
|
||||
}
|
||||
)
|
||||
exc_value = exc_value.__cause__
|
||||
|
||||
output["path"] = self.request.path
|
||||
output["args"] = self.request.args
|
||||
output["exceptions"] = exceptions[::-1]
|
||||
|
||||
return output
|
||||
|
||||
@property
|
||||
def title(self):
|
||||
return STATUS_CODES.get(self.status, b"Error Occurred").decode()
|
||||
|
||||
|
||||
def escape(text):
|
||||
"""
|
||||
Minimal HTML escaping, not for attribute values (unlike html.escape).
|
||||
"""
|
||||
return f"{text}".replace("&", "&").replace("<", "<")
|
||||
|
||||
|
||||
RENDERERS_BY_CONFIG = {
|
||||
"html": HTMLRenderer,
|
||||
"json": JSONRenderer,
|
||||
"text": TextRenderer,
|
||||
}
|
||||
|
||||
RENDERERS_BY_CONTENT_TYPE = {
|
||||
"multipart/form-data": HTMLRenderer,
|
||||
"application/json": JSONRenderer,
|
||||
"text/plain": TextRenderer,
|
||||
}
|
||||
|
||||
|
||||
def exception_response(
|
||||
request: Request,
|
||||
exception: Exception,
|
||||
debug: bool,
|
||||
renderer: t.Type[t.Optional[BaseRenderer]] = None,
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Render a response for the default FALLBACK exception handler.
|
||||
"""
|
||||
|
||||
if not renderer:
|
||||
renderer = HTMLRenderer
|
||||
|
||||
if request:
|
||||
if request.app.config.FALLBACK_ERROR_FORMAT == "auto":
|
||||
try:
|
||||
renderer = JSONRenderer if request.json else HTMLRenderer
|
||||
except InvalidUsage:
|
||||
renderer = HTMLRenderer
|
||||
|
||||
content_type, *_ = request.headers.get(
|
||||
"content-type", ""
|
||||
).split(";")
|
||||
renderer = RENDERERS_BY_CONTENT_TYPE.get(
|
||||
content_type, renderer
|
||||
)
|
||||
else:
|
||||
render_format = request.app.config.FALLBACK_ERROR_FORMAT
|
||||
renderer = RENDERERS_BY_CONFIG.get(render_format, renderer)
|
||||
|
||||
renderer = t.cast(t.Type[BaseRenderer], renderer)
|
||||
return renderer(request, exception, debug).render()
|
||||
@@ -1,133 +1,20 @@
|
||||
from typing import Optional, Union
|
||||
|
||||
from sanic.helpers import STATUS_CODES
|
||||
|
||||
|
||||
TRACEBACK_STYLE = """
|
||||
<style>
|
||||
body {
|
||||
padding: 20px;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.summary {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
h3 code {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.frame-line > * {
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
.frame-line {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.frame-code {
|
||||
font-size: 16px;
|
||||
padding-left: 30px;
|
||||
}
|
||||
|
||||
.tb-wrapper {
|
||||
border: 1px solid #f3f3f3;
|
||||
}
|
||||
|
||||
.tb-header {
|
||||
background-color: #f3f3f3;
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
.tb-border {
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
.frame-descriptor {
|
||||
background-color: #e2eafb;
|
||||
}
|
||||
|
||||
.frame-descriptor {
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
"""
|
||||
|
||||
TRACEBACK_WRAPPER_HTML = """
|
||||
<html>
|
||||
<head>
|
||||
{style}
|
||||
</head>
|
||||
<body>
|
||||
{inner_html}
|
||||
<div class="summary">
|
||||
<p>
|
||||
<b>{exc_name}: {exc_value}</b>
|
||||
while handling path <code>{path}</code>
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
TRACEBACK_WRAPPER_INNER_HTML = """
|
||||
<h1>{exc_name}</h1>
|
||||
<h3><code>{exc_value}</code></h3>
|
||||
<div class="tb-wrapper">
|
||||
<p class="tb-header">Traceback (most recent call last):</p>
|
||||
{frame_html}
|
||||
</div>
|
||||
"""
|
||||
|
||||
TRACEBACK_BORDER = """
|
||||
<div class="tb-border">
|
||||
<b><i>
|
||||
The above exception was the direct cause of the
|
||||
following exception:
|
||||
</i></b>
|
||||
</div>
|
||||
"""
|
||||
|
||||
TRACEBACK_LINE_HTML = """
|
||||
<div class="frame-line">
|
||||
<p class="frame-descriptor">
|
||||
File {0.filename}, line <i>{0.lineno}</i>,
|
||||
in <code><b>{0.name}</b></code>
|
||||
</p>
|
||||
<p class="frame-code"><code>{0.line}</code></p>
|
||||
</div>
|
||||
"""
|
||||
|
||||
INTERNAL_SERVER_ERROR_HTML = """
|
||||
<h1>Internal Server Error</h1>
|
||||
<p>
|
||||
The server encountered an internal error and cannot complete
|
||||
your request.
|
||||
</p>
|
||||
"""
|
||||
|
||||
|
||||
_sanic_exceptions = {}
|
||||
|
||||
|
||||
def add_status_code(code):
|
||||
def add_status_code(code, quiet=None):
|
||||
"""
|
||||
Decorator used for adding exceptions to :class:`SanicException`.
|
||||
"""
|
||||
|
||||
def class_decorator(cls):
|
||||
cls.status_code = code
|
||||
if quiet or quiet is None and code != 500:
|
||||
cls.quiet = True
|
||||
_sanic_exceptions[code] = cls
|
||||
return cls
|
||||
|
||||
@@ -135,51 +22,80 @@ def add_status_code(code):
|
||||
|
||||
|
||||
class SanicException(Exception):
|
||||
def __init__(self, message, status_code=None):
|
||||
def __init__(self, message, status_code=None, quiet=None):
|
||||
super().__init__(message)
|
||||
|
||||
if status_code is not None:
|
||||
self.status_code = status_code
|
||||
|
||||
# quiet=None/False/True with None meaning choose by status
|
||||
if quiet or quiet is None and status_code not in (None, 500):
|
||||
self.quiet = True
|
||||
|
||||
|
||||
@add_status_code(404)
|
||||
class NotFound(SanicException):
|
||||
"""
|
||||
**Status**: 404 Not Found
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@add_status_code(400)
|
||||
class InvalidUsage(SanicException):
|
||||
"""
|
||||
**Status**: 400 Bad Request
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@add_status_code(405)
|
||||
class MethodNotSupported(SanicException):
|
||||
"""
|
||||
**Status**: 405 Method Not Allowed
|
||||
"""
|
||||
|
||||
def __init__(self, message, method, allowed_methods):
|
||||
super().__init__(message)
|
||||
self.headers = dict()
|
||||
self.headers["Allow"] = ", ".join(allowed_methods)
|
||||
if method in ["HEAD", "PATCH", "PUT", "DELETE"]:
|
||||
self.headers["Content-Length"] = 0
|
||||
self.headers = {"Allow": ", ".join(allowed_methods)}
|
||||
|
||||
|
||||
@add_status_code(500)
|
||||
class ServerError(SanicException):
|
||||
"""
|
||||
**Status**: 500 Internal Server Error
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@add_status_code(503)
|
||||
class ServiceUnavailable(SanicException):
|
||||
"""The server is currently unavailable (because it is overloaded or
|
||||
down for maintenance). Generally, this is a temporary state."""
|
||||
"""
|
||||
**Status**: 503 Service Unavailable
|
||||
|
||||
The server is currently unavailable (because it is overloaded or
|
||||
down for maintenance). Generally, this is a temporary state.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class URLBuildError(ServerError):
|
||||
"""
|
||||
**Status**: 500 Internal Server Error
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileNotFound(NotFound):
|
||||
"""
|
||||
**Status**: 404 Not Found
|
||||
"""
|
||||
|
||||
def __init__(self, message, path, relative_url):
|
||||
super().__init__(message)
|
||||
self.path = path
|
||||
@@ -201,34 +117,55 @@ class RequestTimeout(SanicException):
|
||||
|
||||
@add_status_code(413)
|
||||
class PayloadTooLarge(SanicException):
|
||||
"""
|
||||
**Status**: 413 Payload Too Large
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class HeaderNotFound(InvalidUsage):
|
||||
"""
|
||||
**Status**: 400 Bad Request
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@add_status_code(416)
|
||||
class ContentRangeError(SanicException):
|
||||
"""
|
||||
**Status**: 416 Range Not Satisfiable
|
||||
"""
|
||||
|
||||
def __init__(self, message, content_range):
|
||||
super().__init__(message)
|
||||
self.headers = {
|
||||
"Content-Type": "text/plain",
|
||||
"Content-Range": "bytes */%s" % (content_range.total,),
|
||||
}
|
||||
self.headers = {"Content-Range": f"bytes */{content_range.total}"}
|
||||
|
||||
|
||||
@add_status_code(417)
|
||||
class HeaderExpectationFailed(SanicException):
|
||||
"""
|
||||
**Status**: 417 Expectation Failed
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@add_status_code(403)
|
||||
class Forbidden(SanicException):
|
||||
"""
|
||||
**Status**: 403 Forbidden
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRangeType(ContentRangeError):
|
||||
"""
|
||||
**Status**: 416 Range Not Satisfiable
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@@ -240,7 +177,7 @@ class PyFileError(Exception):
|
||||
@add_status_code(401)
|
||||
class Unauthorized(SanicException):
|
||||
"""
|
||||
Unauthorized exception (401 HTTP status code).
|
||||
**Status**: 401 Unauthorized
|
||||
|
||||
:param message: Message describing the exception.
|
||||
:param status_code: HTTP Status code.
|
||||
@@ -282,22 +219,31 @@ class Unauthorized(SanicException):
|
||||
challenge = ", ".join(values)
|
||||
|
||||
self.headers = {
|
||||
"WWW-Authenticate": "{} {}".format(scheme, challenge).rstrip()
|
||||
"WWW-Authenticate": f"{scheme} {challenge}".rstrip()
|
||||
}
|
||||
|
||||
|
||||
def abort(status_code, message=None):
|
||||
class LoadFileException(SanicException):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidSignal(SanicException):
|
||||
pass
|
||||
|
||||
|
||||
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 response.py for the given status code.
|
||||
:param message: The HTTP response body. Defaults to the messages in
|
||||
"""
|
||||
if message is None:
|
||||
message = STATUS_CODES.get(status_code)
|
||||
msg: bytes = STATUS_CODES[status_code]
|
||||
# These are stored as bytes in the STATUS_CODES dict
|
||||
message = message.decode("utf8")
|
||||
message = msg.decode("utf8")
|
||||
sanic_exception = _sanic_exceptions.get(status_code, SanicException)
|
||||
raise sanic_exception(message=message, status_code=status_code)
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import sys
|
||||
|
||||
from traceback import extract_tb, format_exc
|
||||
from traceback import format_exc
|
||||
|
||||
from sanic.errorpages import exception_response
|
||||
from sanic.exceptions import (
|
||||
INTERNAL_SERVER_ERROR_HTML,
|
||||
TRACEBACK_BORDER,
|
||||
TRACEBACK_LINE_HTML,
|
||||
TRACEBACK_STYLE,
|
||||
TRACEBACK_WRAPPER_HTML,
|
||||
TRACEBACK_WRAPPER_INNER_HTML,
|
||||
ContentRangeError,
|
||||
HeaderNotFound,
|
||||
InvalidRangeType,
|
||||
SanicException,
|
||||
)
|
||||
from sanic.log import logger
|
||||
from sanic.response import html, text
|
||||
from sanic.response import text
|
||||
|
||||
|
||||
class ErrorHandler:
|
||||
@@ -40,35 +32,6 @@ class ErrorHandler:
|
||||
self.cached_handlers = {}
|
||||
self.debug = False
|
||||
|
||||
def _render_exception(self, exception):
|
||||
frames = extract_tb(exception.__traceback__)
|
||||
|
||||
frame_html = []
|
||||
for frame in frames:
|
||||
frame_html.append(TRACEBACK_LINE_HTML.format(frame))
|
||||
|
||||
return TRACEBACK_WRAPPER_INNER_HTML.format(
|
||||
exc_name=exception.__class__.__name__,
|
||||
exc_value=exception,
|
||||
frame_html="".join(frame_html),
|
||||
)
|
||||
|
||||
def _render_traceback_html(self, exception, request):
|
||||
exc_type, exc_value, tb = sys.exc_info()
|
||||
exceptions = []
|
||||
|
||||
while exc_value:
|
||||
exceptions.append(self._render_exception(exc_value))
|
||||
exc_value = exc_value.__cause__
|
||||
|
||||
return TRACEBACK_WRAPPER_HTML.format(
|
||||
style=TRACEBACK_STYLE,
|
||||
exc_name=exception.__class__.__name__,
|
||||
exc_value=exception,
|
||||
inner_html=TRACEBACK_BORDER.join(reversed(exceptions)),
|
||||
path=request.path,
|
||||
)
|
||||
|
||||
def add(self, exception, handler):
|
||||
"""
|
||||
Add a new exception handler to an already existing handler object.
|
||||
@@ -166,27 +129,17 @@ class ErrorHandler:
|
||||
:class:`Exception`
|
||||
:return:
|
||||
"""
|
||||
self.log(format_exc())
|
||||
quiet = getattr(exception, "quiet", False)
|
||||
if quiet is False:
|
||||
try:
|
||||
url = repr(request.url)
|
||||
except AttributeError:
|
||||
url = "unknown"
|
||||
|
||||
response_message = "Exception occurred while handling uri: %s"
|
||||
logger.exception(response_message, url)
|
||||
self.log(format_exc())
|
||||
logger.exception("Exception occurred while handling uri: %s", url)
|
||||
|
||||
if issubclass(type(exception), SanicException):
|
||||
return text(
|
||||
"Error: {}".format(exception),
|
||||
status=getattr(exception, "status_code", 500),
|
||||
headers=getattr(exception, "headers", dict()),
|
||||
)
|
||||
elif self.debug:
|
||||
html_output = self._render_traceback_html(exception, request)
|
||||
|
||||
return html(html_output, status=500)
|
||||
else:
|
||||
return html(INTERNAL_SERVER_ERROR_HTML, status=500)
|
||||
return exception_response(request, exception, self.debug)
|
||||
|
||||
|
||||
class ContentRangeHandler:
|
||||
|
||||
@@ -3,8 +3,14 @@ import re
|
||||
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
|
||||
from urllib.parse import unquote
|
||||
|
||||
from sanic.helpers import STATUS_CODES
|
||||
|
||||
|
||||
# TODO:
|
||||
# - the Options object should be a typed object to allow for less casting
|
||||
# across the application (in request.py for example)
|
||||
HeaderIterable = Iterable[Tuple[str, Any]] # Values convertible to str
|
||||
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
|
||||
Options = Dict[str, Union[int, str]] # key=value fields in various headers
|
||||
OptionsIterable = Iterable[Tuple[str, str]] # May contain duplicate keys
|
||||
|
||||
@@ -173,10 +179,18 @@ def parse_host(host: str) -> Tuple[Optional[str], Optional[int]]:
|
||||
return host.lower(), int(port) if port is not None else None
|
||||
|
||||
|
||||
def format_http1(headers: HeaderIterable) -> bytes:
|
||||
"""Convert a headers iterable into HTTP/1 header format.
|
||||
_HTTP1_STATUSLINES = [
|
||||
b"HTTP/1.1 %d %b\r\n" % (status, STATUS_CODES.get(status, b"UNKNOWN"))
|
||||
for status in range(1000)
|
||||
]
|
||||
|
||||
- Outputs UTF-8 bytes where each header line ends with \\r\\n.
|
||||
- Values are converted into strings if necessary.
|
||||
"""
|
||||
return "".join(f"{name}: {val}\r\n" for name, val in headers).encode()
|
||||
|
||||
def format_http1_response(status: int, headers: HeaderBytesIterable) -> bytes:
|
||||
"""Format a HTTP/1.1 response header."""
|
||||
# Note: benchmarks show that here bytes concat is faster than bytearray,
|
||||
# b"".join() or %-formatting. %timeit any changes you make.
|
||||
ret = _HTTP1_STATUSLINES[status]
|
||||
for h in headers:
|
||||
ret += b"%b: %b\r\n" % h
|
||||
ret += b"\r\n"
|
||||
return ret
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
from importlib import import_module
|
||||
from inspect import ismodule
|
||||
from typing import Dict
|
||||
|
||||
|
||||
STATUS_CODES = {
|
||||
STATUS_CODES: Dict[int, bytes] = {
|
||||
100: b"Continue",
|
||||
101: b"Switching Protocols",
|
||||
102: b"Processing",
|
||||
|
||||
537
sanic/http.py
Normal file
537
sanic/http.py
Normal file
@@ -0,0 +1,537 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic.request import Request
|
||||
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,
|
||||
PayloadTooLarge,
|
||||
ServerError,
|
||||
ServiceUnavailable,
|
||||
)
|
||||
from sanic.headers import format_http1_response
|
||||
from sanic.helpers import has_message_body
|
||||
from sanic.log import access_logger, logger
|
||||
|
||||
|
||||
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:
|
||||
"""
|
||||
Internal helper for managing the HTTP request/response cycle
|
||||
|
||||
:raises ServerError:
|
||||
:raises PayloadTooLarge:
|
||||
:raises Exception:
|
||||
:raises InvalidUsage:
|
||||
:raises HeaderExpectationFailed:
|
||||
:raises RuntimeError:
|
||||
:raises ServerError:
|
||||
:raises ServerError:
|
||||
:raises InvalidUsage:
|
||||
:raises InvalidUsage:
|
||||
:raises InvalidUsage:
|
||||
:raises PayloadTooLarge:
|
||||
:raises RuntimeError:
|
||||
"""
|
||||
|
||||
__slots__ = [
|
||||
"_send",
|
||||
"_receive_more",
|
||||
"recv_buffer",
|
||||
"protocol",
|
||||
"expecting_continue",
|
||||
"stage",
|
||||
"keep_alive",
|
||||
"head_only",
|
||||
"request",
|
||||
"exception",
|
||||
"url",
|
||||
"request_body",
|
||||
"request_bytes",
|
||||
"request_bytes_left",
|
||||
"request_max_size",
|
||||
"response",
|
||||
"response_func",
|
||||
"response_bytes_left",
|
||||
"upgrade_websocket",
|
||||
]
|
||||
|
||||
def __init__(self, protocol):
|
||||
self._send = protocol.send
|
||||
self._receive_more = protocol.receive_more
|
||||
self.recv_buffer = protocol.recv_buffer
|
||||
self.protocol = protocol
|
||||
self.expecting_continue: bool = False
|
||||
self.stage: Stage = Stage.IDLE
|
||||
self.request_body = None
|
||||
self.request_bytes = None
|
||||
self.request_bytes_left = None
|
||||
self.request_max_size = protocol.request_max_size
|
||||
self.keep_alive = True
|
||||
self.head_only = None
|
||||
self.request: Request = None
|
||||
self.response: BaseHTTPResponse = None
|
||||
self.exception = None
|
||||
self.url = None
|
||||
self.upgrade_websocket = False
|
||||
|
||||
def __bool__(self):
|
||||
"""Test if request handling is in progress"""
|
||||
return self.stage in (Stage.HANDLER, Stage.RESPONSE)
|
||||
|
||||
async def http1(self):
|
||||
"""
|
||||
HTTP 1.1 connection handler
|
||||
"""
|
||||
while True: # As long as connection stays keep-alive
|
||||
try:
|
||||
# Receive and handle a request
|
||||
self.stage = Stage.REQUEST
|
||||
self.response_func = self.http1_response_header
|
||||
|
||||
await self.http1_request_header()
|
||||
|
||||
self.request.conn_info = self.protocol.conn_info
|
||||
await self.protocol.request_handler(self.request)
|
||||
|
||||
# Handler finished, response should've been sent
|
||||
if self.stage is Stage.HANDLER and not self.upgrade_websocket:
|
||||
raise ServerError("Handler produced no response")
|
||||
|
||||
if self.stage is Stage.RESPONSE:
|
||||
await self.response.send(end_stream=True)
|
||||
except CancelledError:
|
||||
# Write an appropriate response before exiting
|
||||
e = self.exception or ServiceUnavailable("Cancelled")
|
||||
self.exception = None
|
||||
self.keep_alive = False
|
||||
await self.error_response(e)
|
||||
except Exception as e:
|
||||
# Write an error response
|
||||
await self.error_response(e)
|
||||
|
||||
# Try to consume any remaining request body
|
||||
if self.request_body:
|
||||
if self.response and 200 <= self.response.status < 300:
|
||||
logger.error(f"{self.request} body not consumed.")
|
||||
|
||||
try:
|
||||
async for _ in self:
|
||||
pass
|
||||
except PayloadTooLarge:
|
||||
# We won't read the body and that may cause httpx and
|
||||
# tests to fail. This little delay allows clients to push
|
||||
# a small request into network buffers before we close the
|
||||
# socket, so that they are then able to read the response.
|
||||
await sleep(0.001)
|
||||
self.keep_alive = False
|
||||
|
||||
# Exit and disconnect if no more requests can be taken
|
||||
if self.stage is not Stage.IDLE or not self.keep_alive:
|
||||
break
|
||||
|
||||
# Wait for next request
|
||||
if not self.recv_buffer:
|
||||
await self._receive_more()
|
||||
|
||||
async def http1_request_header(self):
|
||||
"""
|
||||
Receive and parse request header into self.request.
|
||||
"""
|
||||
HEADER_MAX_SIZE = min(8192, self.request_max_size)
|
||||
# Receive until full header is in buffer
|
||||
buf = self.recv_buffer
|
||||
pos = 0
|
||||
|
||||
while True:
|
||||
pos = buf.find(b"\r\n\r\n", pos)
|
||||
if pos != -1:
|
||||
break
|
||||
|
||||
pos = max(0, len(buf) - 3)
|
||||
if pos >= HEADER_MAX_SIZE:
|
||||
break
|
||||
|
||||
await self._receive_more()
|
||||
|
||||
if pos >= HEADER_MAX_SIZE:
|
||||
raise PayloadTooLarge("Request header exceeds the size limit")
|
||||
|
||||
# Parse header content
|
||||
try:
|
||||
head = buf[:pos]
|
||||
raw_headers = head.decode(errors="surrogateescape")
|
||||
reqline, *split_headers = raw_headers.split("\r\n")
|
||||
method, self.url, protocol = reqline.split(" ")
|
||||
|
||||
if protocol == "HTTP/1.1":
|
||||
self.keep_alive = True
|
||||
elif protocol == "HTTP/1.0":
|
||||
self.keep_alive = False
|
||||
else:
|
||||
raise Exception # Raise a Bad Request on try-except
|
||||
|
||||
self.head_only = method.upper() == "HEAD"
|
||||
request_body = False
|
||||
headers = []
|
||||
|
||||
for name, value in (h.split(":", 1) for h in split_headers):
|
||||
name, value = h = name.lower(), value.lstrip()
|
||||
|
||||
if name in ("content-length", "transfer-encoding"):
|
||||
request_body = True
|
||||
elif name == "connection":
|
||||
self.keep_alive = value.lower() == "keep-alive"
|
||||
|
||||
headers.append(h)
|
||||
except Exception:
|
||||
raise InvalidUsage("Bad Request")
|
||||
|
||||
headers_instance = Header(headers)
|
||||
self.upgrade_websocket = headers_instance.get("upgrade") == "websocket"
|
||||
|
||||
# Prepare a Request object
|
||||
request = self.protocol.request_class(
|
||||
url_bytes=self.url.encode(),
|
||||
headers=headers_instance,
|
||||
head=bytes(head),
|
||||
version=protocol[5:],
|
||||
method=method,
|
||||
transport=self.protocol.transport,
|
||||
app=self.protocol.app,
|
||||
)
|
||||
|
||||
# Prepare for request body
|
||||
self.request_bytes_left = self.request_bytes = 0
|
||||
if request_body:
|
||||
headers = request.headers
|
||||
expect = headers.get("expect")
|
||||
|
||||
if expect is not None:
|
||||
if expect.lower() == "100-continue":
|
||||
self.expecting_continue = True
|
||||
else:
|
||||
raise HeaderExpectationFailed(f"Unknown Expect: {expect}")
|
||||
|
||||
if headers.get("transfer-encoding") == "chunked":
|
||||
self.request_body = "chunked"
|
||||
pos -= 2 # One CRLF stays in buffer
|
||||
else:
|
||||
self.request_body = True
|
||||
self.request_bytes_left = self.request_bytes = int(
|
||||
headers["content-length"]
|
||||
)
|
||||
|
||||
# Remove header and its trailing CRLF
|
||||
del buf[: pos + 4]
|
||||
self.stage = Stage.HANDLER
|
||||
self.request, request.stream = request, self
|
||||
self.protocol.state["requests_count"] += 1
|
||||
|
||||
async def http1_response_header(
|
||||
self, data: bytes, end_stream: bool
|
||||
) -> None:
|
||||
res = self.response
|
||||
|
||||
# Compatibility with simple response body
|
||||
if not data and getattr(res, "body", None):
|
||||
data, end_stream = res.body, True # type: ignore
|
||||
|
||||
size = len(data)
|
||||
headers = res.headers
|
||||
status = res.status
|
||||
|
||||
if not isinstance(status, int) or status < 200:
|
||||
raise RuntimeError(f"Invalid response status {status!r}")
|
||||
|
||||
if not has_message_body(status):
|
||||
# Header-only response status
|
||||
self.response_func = None
|
||||
if (
|
||||
data
|
||||
or not end_stream
|
||||
or "content-length" in headers
|
||||
or "transfer-encoding" in headers
|
||||
):
|
||||
data, size, end_stream = b"", 0, True
|
||||
headers.pop("content-length", None)
|
||||
headers.pop("transfer-encoding", None)
|
||||
logger.warning(
|
||||
f"Message body set in response on {self.request.path}. "
|
||||
f"A {status} response may only have headers, no body."
|
||||
)
|
||||
elif self.head_only and "content-length" in headers:
|
||||
self.response_func = None
|
||||
elif end_stream:
|
||||
# Non-streaming response (all in one block)
|
||||
headers["content-length"] = size
|
||||
self.response_func = None
|
||||
elif "content-length" in headers:
|
||||
# Streaming response with size known in advance
|
||||
self.response_bytes_left = int(headers["content-length"]) - size
|
||||
self.response_func = self.http1_response_normal
|
||||
else:
|
||||
# Length not known, use chunked encoding
|
||||
headers["transfer-encoding"] = "chunked"
|
||||
data = b"%x\r\n%b\r\n" % (size, data) if size else b""
|
||||
self.response_func = self.http1_response_chunked
|
||||
|
||||
if self.head_only:
|
||||
# Head request: don't send body
|
||||
data = b""
|
||||
self.response_func = self.head_response_ignored
|
||||
|
||||
headers["connection"] = "keep-alive" if self.keep_alive else "close"
|
||||
ret = format_http1_response(status, res.processed_headers)
|
||||
if data:
|
||||
ret += data
|
||||
|
||||
# Send a 100-continue if expected and not Expectation Failed
|
||||
if self.expecting_continue:
|
||||
self.expecting_continue = False
|
||||
if status != 417:
|
||||
ret = HTTP_CONTINUE + ret
|
||||
|
||||
# Send response
|
||||
if self.protocol.access_log:
|
||||
self.log_response()
|
||||
|
||||
await self._send(ret)
|
||||
self.stage = Stage.IDLE if end_stream else Stage.RESPONSE
|
||||
|
||||
def head_response_ignored(self, data: bytes, end_stream: bool) -> None:
|
||||
"""
|
||||
HEAD response: body data silently ignored.
|
||||
"""
|
||||
if end_stream:
|
||||
self.response_func = None
|
||||
self.stage = Stage.IDLE
|
||||
|
||||
async def http1_response_chunked(
|
||||
self, data: bytes, end_stream: bool
|
||||
) -> None:
|
||||
"""
|
||||
Format a part of response body in chunked encoding.
|
||||
"""
|
||||
# Chunked encoding
|
||||
size = len(data)
|
||||
if end_stream:
|
||||
await self._send(
|
||||
b"%x\r\n%b\r\n0\r\n\r\n" % (size, data)
|
||||
if size
|
||||
else b"0\r\n\r\n"
|
||||
)
|
||||
self.response_func = None
|
||||
self.stage = Stage.IDLE
|
||||
elif size:
|
||||
await self._send(b"%x\r\n%b\r\n" % (size, data))
|
||||
|
||||
async def http1_response_normal(
|
||||
self, data: bytes, end_stream: bool
|
||||
) -> None:
|
||||
"""
|
||||
Format / keep track of non-chunked response.
|
||||
"""
|
||||
bytes_left = self.response_bytes_left - len(data)
|
||||
if bytes_left <= 0:
|
||||
if bytes_left < 0:
|
||||
raise ServerError("Response was bigger than content-length")
|
||||
|
||||
await self._send(data)
|
||||
self.response_func = None
|
||||
self.stage = Stage.IDLE
|
||||
else:
|
||||
if end_stream:
|
||||
raise ServerError("Response was smaller than content-length")
|
||||
|
||||
await self._send(data)
|
||||
self.response_bytes_left = bytes_left
|
||||
|
||||
async def error_response(self, exception: Exception) -> None:
|
||||
"""
|
||||
Handle response when exception encountered
|
||||
"""
|
||||
# Disconnect after an error if in any other state than handler
|
||||
if self.stage is not Stage.HANDLER:
|
||||
self.keep_alive = False
|
||||
|
||||
# Request failure? Respond but then disconnect
|
||||
if self.stage is Stage.REQUEST:
|
||||
self.stage = Stage.HANDLER
|
||||
|
||||
# From request and handler states we can respond, otherwise be silent
|
||||
if self.stage is Stage.HANDLER:
|
||||
app = self.protocol.app
|
||||
|
||||
if self.request is None:
|
||||
self.create_empty_request()
|
||||
|
||||
await app.handle_exception(self.request, exception)
|
||||
|
||||
def create_empty_request(self) -> None:
|
||||
"""
|
||||
Current error handling code needs a request object that won't exist
|
||||
if an error occurred during before a request was received. Create a
|
||||
bogus response for error handling use.
|
||||
"""
|
||||
|
||||
# FIXME: Avoid this by refactoring error handling and response code
|
||||
self.request = self.protocol.request_class(
|
||||
url_bytes=self.url.encode() if self.url else b"*",
|
||||
headers=Header({}),
|
||||
version="1.1",
|
||||
method="NONE",
|
||||
transport=self.protocol.transport,
|
||||
app=self.protocol.app,
|
||||
)
|
||||
self.request.stream = self
|
||||
|
||||
def log_response(self) -> None:
|
||||
"""
|
||||
Helper method provided to enable the logging of responses in case if
|
||||
the :attr:`HttpProtocol.access_log` is enabled.
|
||||
"""
|
||||
req, res = self.request, self.response
|
||||
extra = {
|
||||
"status": getattr(res, "status", 0),
|
||||
"byte": getattr(self, "response_bytes_left", -1),
|
||||
"host": "UNKNOWN",
|
||||
"request": "nil",
|
||||
}
|
||||
if req is not None:
|
||||
if req.ip:
|
||||
extra["host"] = f"{req.ip}:{req.port}"
|
||||
extra["request"] = f"{req.method} {req.url}"
|
||||
access_logger.info("", extra=extra)
|
||||
|
||||
# Request methods
|
||||
|
||||
async def __aiter__(self):
|
||||
"""
|
||||
Async iterate over request body.
|
||||
"""
|
||||
while self.request_body:
|
||||
data = await self.read()
|
||||
|
||||
if data:
|
||||
yield data
|
||||
|
||||
async def read(self) -> Optional[bytes]:
|
||||
"""
|
||||
Read some bytes of request body.
|
||||
"""
|
||||
|
||||
# Send a 100-continue if needed
|
||||
if self.expecting_continue:
|
||||
self.expecting_continue = False
|
||||
await self._send(HTTP_CONTINUE)
|
||||
|
||||
# Receive request body chunk
|
||||
buf = self.recv_buffer
|
||||
if self.request_bytes_left == 0 and self.request_body == "chunked":
|
||||
# Process a chunk header: \r\n<size>[;<chunk extensions>]\r\n
|
||||
while True:
|
||||
pos = buf.find(b"\r\n", 3)
|
||||
|
||||
if pos != -1:
|
||||
break
|
||||
|
||||
if len(buf) > 64:
|
||||
self.keep_alive = False
|
||||
raise InvalidUsage("Bad chunked encoding")
|
||||
|
||||
await self._receive_more()
|
||||
|
||||
try:
|
||||
size = int(buf[2:pos].split(b";", 1)[0].decode(), 16)
|
||||
except Exception:
|
||||
self.keep_alive = False
|
||||
raise InvalidUsage("Bad chunked encoding")
|
||||
|
||||
del buf[: pos + 2]
|
||||
|
||||
if size <= 0:
|
||||
self.request_body = None
|
||||
|
||||
if size < 0:
|
||||
self.keep_alive = False
|
||||
raise InvalidUsage("Bad chunked encoding")
|
||||
|
||||
return None
|
||||
|
||||
self.request_bytes_left = size
|
||||
self.request_bytes += size
|
||||
|
||||
# Request size limit
|
||||
if self.request_bytes > self.request_max_size:
|
||||
self.keep_alive = False
|
||||
raise PayloadTooLarge("Request body exceeds the size limit")
|
||||
|
||||
# End of request body?
|
||||
if not self.request_bytes_left:
|
||||
self.request_body = None
|
||||
return None
|
||||
|
||||
# At this point we are good to read/return up to request_bytes_left
|
||||
if not buf:
|
||||
await self._receive_more()
|
||||
|
||||
data = bytes(buf[: self.request_bytes_left])
|
||||
size = len(data)
|
||||
|
||||
del buf[:size]
|
||||
|
||||
self.request_bytes_left -= size
|
||||
|
||||
return data
|
||||
|
||||
# Response methods
|
||||
|
||||
def respond(self, response: BaseHTTPResponse) -> BaseHTTPResponse:
|
||||
"""
|
||||
Initiate new streaming response.
|
||||
|
||||
Nothing is sent until the first send() call on the returned object, and
|
||||
calling this function multiple times will just alter the response to be
|
||||
given.
|
||||
"""
|
||||
if self.stage is not Stage.HANDLER:
|
||||
self.stage = Stage.FAILED
|
||||
raise RuntimeError("Response already started")
|
||||
|
||||
self.response, response.stream = response, self
|
||||
return response
|
||||
|
||||
@property
|
||||
def send(self):
|
||||
return self.response_func
|
||||
11
sanic/log.py
11
sanic/log.py
@@ -54,5 +54,16 @@ LOGGING_CONFIG_DEFAULTS = dict(
|
||||
|
||||
|
||||
logger = logging.getLogger("sanic.root")
|
||||
"""
|
||||
General Sanic logger
|
||||
"""
|
||||
|
||||
error_logger = logging.getLogger("sanic.error")
|
||||
"""
|
||||
Logger used by Sanic for error logging
|
||||
"""
|
||||
|
||||
access_logger = logging.getLogger("sanic.access")
|
||||
"""
|
||||
Logger used by Sanic for access logging
|
||||
"""
|
||||
|
||||
0
sanic/mixins/__init__.py
Normal file
0
sanic/mixins/__init__.py
Normal file
39
sanic/mixins/exceptions.py
Normal file
39
sanic/mixins/exceptions.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from typing import Set
|
||||
|
||||
from sanic.models.futures import FutureException
|
||||
|
||||
|
||||
class ExceptionMixin:
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_exceptions: Set[FutureException] = set()
|
||||
|
||||
def _apply_exception_handler(self, handler: FutureException):
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
def exception(self, *exceptions, apply=True):
|
||||
"""
|
||||
This method enables the process of creating a global exception
|
||||
handler for the current blueprint under question.
|
||||
|
||||
:param args: List of Python exceptions to be caught by the handler
|
||||
:param kwargs: Additional optional arguments to be passed to the
|
||||
exception handler
|
||||
|
||||
:return a decorated method to handle global exceptions for any
|
||||
route registered under this blueprint.
|
||||
"""
|
||||
|
||||
def decorator(handler):
|
||||
nonlocal apply
|
||||
nonlocal exceptions
|
||||
|
||||
if isinstance(exceptions[0], list):
|
||||
exceptions = tuple(*exceptions)
|
||||
|
||||
future_exception = FutureException(handler, exceptions)
|
||||
self._future_exceptions.add(future_exception)
|
||||
if apply:
|
||||
self._apply_exception_handler(future_exception)
|
||||
return handler
|
||||
|
||||
return decorator
|
||||
82
sanic/mixins/listeners.py
Normal file
82
sanic/mixins/listeners.py
Normal file
@@ -0,0 +1,82 @@
|
||||
from enum import Enum, auto
|
||||
from functools import partial
|
||||
from typing import Any, Callable, Coroutine, List, Optional, Union
|
||||
|
||||
from sanic.models.futures import FutureListener
|
||||
|
||||
|
||||
class ListenerEvent(str, Enum):
|
||||
def _generate_next_value_(name: str, *args) -> str: # type: ignore
|
||||
return name.lower()
|
||||
|
||||
BEFORE_SERVER_START = auto()
|
||||
AFTER_SERVER_START = auto()
|
||||
BEFORE_SERVER_STOP = auto()
|
||||
AFTER_SERVER_STOP = auto()
|
||||
MAIN_PROCESS_START = auto()
|
||||
MAIN_PROCESS_STOP = auto()
|
||||
|
||||
|
||||
class ListenerMixin:
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_listeners: List[FutureListener] = []
|
||||
|
||||
def _apply_listener(self, listener: FutureListener):
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
def listener(
|
||||
self,
|
||||
listener_or_event: Union[
|
||||
Callable[..., Coroutine[Any, Any, None]], str
|
||||
],
|
||||
event_or_none: Optional[str] = None,
|
||||
apply: bool = True,
|
||||
):
|
||||
"""
|
||||
Create a listener from a decorated function.
|
||||
|
||||
To be used as a deocrator:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@bp.listener("before_server_start")
|
||||
async def before_server_start(app, loop):
|
||||
...
|
||||
|
||||
`See user guide re: listeners
|
||||
<https://sanicframework.org/guide/basics/listeners.html#listeners>`__
|
||||
|
||||
:param event: event to listen to
|
||||
"""
|
||||
|
||||
def register_listener(listener, event):
|
||||
nonlocal apply
|
||||
|
||||
future_listener = FutureListener(listener, event)
|
||||
self._future_listeners.append(future_listener)
|
||||
if apply:
|
||||
self._apply_listener(future_listener)
|
||||
return listener
|
||||
|
||||
if callable(listener_or_event):
|
||||
return register_listener(listener_or_event, event_or_none)
|
||||
else:
|
||||
return partial(register_listener, event=listener_or_event)
|
||||
|
||||
def main_process_start(self, listener):
|
||||
return self.listener(listener, "main_process_start")
|
||||
|
||||
def main_process_stop(self, listener):
|
||||
return self.listener(listener, "main_process_stop")
|
||||
|
||||
def before_server_start(self, listener):
|
||||
return self.listener(listener, "before_server_start")
|
||||
|
||||
def after_server_start(self, listener):
|
||||
return self.listener(listener, "after_server_start")
|
||||
|
||||
def before_server_stop(self, listener):
|
||||
return self.listener(listener, "before_server_stop")
|
||||
|
||||
def after_server_stop(self, listener):
|
||||
return self.listener(listener, "after_server_stop")
|
||||
58
sanic/mixins/middleware.py
Normal file
58
sanic/mixins/middleware.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from functools import partial
|
||||
from typing import List
|
||||
|
||||
from sanic.models.futures import FutureMiddleware
|
||||
|
||||
|
||||
class MiddlewareMixin:
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_middleware: List[FutureMiddleware] = []
|
||||
|
||||
def _apply_middleware(self, middleware: FutureMiddleware):
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
def middleware(
|
||||
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')*
|
||||
|
||||
`See user guide re: middleware
|
||||
<https://sanicframework.org/guide/basics/middleware.html>`__
|
||||
|
||||
:param: middleware_or_request: Optional parameter to use for
|
||||
identifying which type of middleware is being registered.
|
||||
"""
|
||||
|
||||
def register_middleware(middleware, attach_to="request"):
|
||||
nonlocal apply
|
||||
|
||||
future_middleware = FutureMiddleware(middleware, attach_to)
|
||||
self._future_middleware.append(future_middleware)
|
||||
if apply:
|
||||
self._apply_middleware(future_middleware)
|
||||
return middleware
|
||||
|
||||
# Detect which way this was called, @middleware or @middleware('AT')
|
||||
if callable(middleware_or_request):
|
||||
return register_middleware(
|
||||
middleware_or_request, attach_to=attach_to
|
||||
)
|
||||
else:
|
||||
return partial(
|
||||
register_middleware, attach_to=middleware_or_request
|
||||
)
|
||||
|
||||
def on_request(self, middleware=None):
|
||||
if callable(middleware):
|
||||
return self.middleware(middleware, "request")
|
||||
else:
|
||||
return partial(self.middleware, attach_to="request")
|
||||
|
||||
def on_response(self, middleware=None):
|
||||
if callable(middleware):
|
||||
return self.middleware(middleware, "response")
|
||||
else:
|
||||
return partial(self.middleware, attach_to="response")
|
||||
805
sanic/mixins/routes.py
Normal file
805
sanic/mixins/routes.py
Normal file
@@ -0,0 +1,805 @@
|
||||
from functools import partial, wraps
|
||||
from inspect import signature
|
||||
from mimetypes import guess_type
|
||||
from os import path
|
||||
from pathlib import PurePath
|
||||
from re import sub
|
||||
from time import gmtime, strftime
|
||||
from typing import Iterable, List, Optional, Set, Union
|
||||
from urllib.parse import unquote
|
||||
|
||||
from sanic_routing.route import Route # type: ignore
|
||||
|
||||
from sanic.compat import stat_async
|
||||
from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS
|
||||
from sanic.exceptions import (
|
||||
ContentRangeError,
|
||||
FileNotFound,
|
||||
HeaderNotFound,
|
||||
InvalidUsage,
|
||||
)
|
||||
from sanic.handlers import ContentRangeHandler
|
||||
from sanic.log import error_logger
|
||||
from sanic.models.futures import FutureRoute, FutureStatic
|
||||
from sanic.response import HTTPResponse, file, file_stream
|
||||
from sanic.views import CompositionView
|
||||
|
||||
|
||||
class RouteMixin:
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_routes: Set[FutureRoute] = set()
|
||||
self._future_statics: Set[FutureStatic] = set()
|
||||
self.name = ""
|
||||
self.strict_slashes: Optional[bool] = False
|
||||
|
||||
def _apply_route(self, route: FutureRoute) -> List[Route]:
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
def _apply_static(self, static: FutureStatic) -> Route:
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
def route(
|
||||
self,
|
||||
uri: str,
|
||||
methods: Optional[Iterable[str]] = None,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
stream: bool = False,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
ignore_body: bool = False,
|
||||
apply: bool = True,
|
||||
subprotocols: Optional[List[str]] = None,
|
||||
websocket: bool = False,
|
||||
unquote: bool = False,
|
||||
static: bool = False,
|
||||
):
|
||||
"""
|
||||
Decorate a function to be registered as a route
|
||||
|
||||
:param uri: path of the URL
|
||||
:param methods: list or tuple of methods allowed
|
||||
:param host: the host, if required
|
||||
:param strict_slashes: whether to apply strict slashes to the route
|
||||
:param stream: whether to allow the request to stream its body
|
||||
:param version: route specific versioning
|
||||
:param name: user defined route name for url_for
|
||||
:param ignore_body: whether the handler should ignore request
|
||||
body (eg. GET requests)
|
||||
:return: tuple of routes, decorated function
|
||||
"""
|
||||
|
||||
# Fix case where the user did not prefix the URL with a /
|
||||
# and will probably get confused as to why it's not working
|
||||
if not uri.startswith("/"):
|
||||
uri = "/" + uri
|
||||
|
||||
if strict_slashes is None:
|
||||
strict_slashes = self.strict_slashes
|
||||
|
||||
if not methods and not websocket:
|
||||
methods = frozenset({"GET"})
|
||||
|
||||
def decorator(handler):
|
||||
nonlocal uri
|
||||
nonlocal methods
|
||||
nonlocal host
|
||||
nonlocal strict_slashes
|
||||
nonlocal stream
|
||||
nonlocal version
|
||||
nonlocal name
|
||||
nonlocal ignore_body
|
||||
nonlocal subprotocols
|
||||
nonlocal websocket
|
||||
nonlocal static
|
||||
|
||||
if isinstance(handler, tuple):
|
||||
# if a handler fn is already wrapped in a route, the handler
|
||||
# variable will be a tuple of (existing routes, handler fn)
|
||||
_, handler = handler
|
||||
|
||||
name = self._generate_name(name, handler)
|
||||
|
||||
if isinstance(host, str):
|
||||
host = frozenset([host])
|
||||
elif host and not isinstance(host, frozenset):
|
||||
try:
|
||||
host = frozenset(host)
|
||||
except TypeError:
|
||||
raise ValueError(
|
||||
"Expected either string or Iterable of host strings, "
|
||||
"not %s" % host
|
||||
)
|
||||
|
||||
if isinstance(subprotocols, (list, tuple, set)):
|
||||
subprotocols = frozenset(subprotocols)
|
||||
|
||||
route = FutureRoute(
|
||||
handler,
|
||||
uri,
|
||||
None if websocket else frozenset([x.upper() for x in methods]),
|
||||
host,
|
||||
strict_slashes,
|
||||
stream,
|
||||
version,
|
||||
name,
|
||||
ignore_body,
|
||||
websocket,
|
||||
subprotocols,
|
||||
unquote,
|
||||
static,
|
||||
)
|
||||
|
||||
self._future_routes.add(route)
|
||||
|
||||
args = list(signature(handler).parameters.keys())
|
||||
if websocket and len(args) < 2:
|
||||
handler_name = handler.__name__
|
||||
|
||||
raise ValueError(
|
||||
f"Required parameter `request` and/or `ws` missing "
|
||||
f"in the {handler_name}() route?"
|
||||
)
|
||||
elif not args:
|
||||
handler_name = handler.__name__
|
||||
|
||||
raise ValueError(
|
||||
f"Required parameter `request` missing "
|
||||
f"in the {handler_name}() route?"
|
||||
)
|
||||
|
||||
if not websocket and stream:
|
||||
handler.is_stream = stream
|
||||
|
||||
if apply:
|
||||
self._apply_route(route)
|
||||
|
||||
return route, handler
|
||||
|
||||
return decorator
|
||||
|
||||
def add_route(
|
||||
self,
|
||||
handler,
|
||||
uri: str,
|
||||
methods: Iterable[str] = frozenset({"GET"}),
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
"""A helper method to register class instance or
|
||||
functions as a handler to the application url
|
||||
routes.
|
||||
|
||||
:param handler: function or class instance
|
||||
:param uri: path of the URL
|
||||
:param methods: list or tuple of methods allowed, these are overridden
|
||||
if using a HTTPMethodView
|
||||
:param host:
|
||||
:param strict_slashes:
|
||||
:param version:
|
||||
:param name: user defined route name for url_for
|
||||
:param stream: boolean specifying if the handler is a stream handler
|
||||
:return: function or class instance
|
||||
"""
|
||||
# Handle HTTPMethodView differently
|
||||
if hasattr(handler, "view_class"):
|
||||
methods = set()
|
||||
|
||||
for method in HTTP_METHODS:
|
||||
_handler = getattr(handler.view_class, method.lower(), None)
|
||||
if _handler:
|
||||
methods.add(method)
|
||||
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
|
||||
|
||||
self.route(
|
||||
uri=uri,
|
||||
methods=methods,
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
stream=stream,
|
||||
version=version,
|
||||
name=name,
|
||||
)(handler)
|
||||
return handler
|
||||
|
||||
# Shorthand method decorators
|
||||
def get(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
ignore_body: bool = True,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **GET** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **GET** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def post(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
stream: bool = False,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **POST** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **POST** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def put(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
stream: bool = False,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **PUT** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **PUT** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def head(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
ignore_body: bool = True,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **HEAD** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **HEAD** method of *HTTP*
|
||||
:type uri: str
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:type host: Optional[str], optional
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:type strict_slashes: Optional[bool], optional
|
||||
:param version: API Version
|
||||
:type version: Optional[str], optional
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:type name: Optional[str], optional
|
||||
:param ignore_body: whether the handler should ignore request
|
||||
body (eg. GET requests), defaults to True
|
||||
:type ignore_body: bool, optional
|
||||
: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,
|
||||
)
|
||||
|
||||
def options(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
ignore_body: bool = True,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **OPTIONS** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **OPTIONS** method of *HTTP*
|
||||
:type uri: str
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:type host: Optional[str], optional
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:type strict_slashes: Optional[bool], optional
|
||||
:param version: API Version
|
||||
:type version: Optional[str], optional
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:type name: Optional[str], optional
|
||||
:param ignore_body: whether the handler should ignore request
|
||||
body (eg. GET requests), defaults to True
|
||||
:type ignore_body: bool, optional
|
||||
: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,
|
||||
)
|
||||
|
||||
def patch(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
stream=False,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **PATCH** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **PATCH** method of *HTTP*
|
||||
:type uri: str
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:type host: Optional[str], optional
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:type strict_slashes: Optional[bool], optional
|
||||
:param stream: whether to allow the request to stream its body
|
||||
:type stream: Optional[bool], optional
|
||||
:param version: API Version
|
||||
:type version: Optional[str], optional
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
:type name: Optional[str], optional
|
||||
:param ignore_body: whether the handler should ignore request
|
||||
body (eg. GET requests), defaults to True
|
||||
:type ignore_body: bool, optional
|
||||
: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,
|
||||
)
|
||||
|
||||
def delete(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
ignore_body: bool = True,
|
||||
):
|
||||
"""
|
||||
Add an API URL under the **DELETE** *HTTP* method
|
||||
|
||||
:param uri: URL to be tagged to **DELETE** method of *HTTP*
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:param version: API Version
|
||||
:param name: Unique name that can be used to identify the Route
|
||||
: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,
|
||||
)
|
||||
|
||||
def websocket(
|
||||
self,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
subprotocols: Optional[List[str]] = None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
apply: bool = True,
|
||||
):
|
||||
"""
|
||||
Decorate a function to be registered as a websocket route
|
||||
|
||||
:param uri: path of the URL
|
||||
:param host: Host IP or FQDN details
|
||||
:param strict_slashes: If the API endpoint needs to terminate
|
||||
with a "/" or not
|
||||
:param subprotocols: optional list of str with supported subprotocols
|
||||
:param name: A unique name assigned to the URL so that it can
|
||||
be used with :func:`url_for`
|
||||
:return: tuple of routes, decorated function
|
||||
"""
|
||||
return self.route(
|
||||
uri=uri,
|
||||
host=host,
|
||||
methods=None,
|
||||
strict_slashes=strict_slashes,
|
||||
version=version,
|
||||
name=name,
|
||||
apply=apply,
|
||||
subprotocols=subprotocols,
|
||||
websocket=True,
|
||||
)
|
||||
|
||||
def add_websocket_route(
|
||||
self,
|
||||
handler,
|
||||
uri: str,
|
||||
host: Optional[str] = None,
|
||||
strict_slashes: Optional[bool] = None,
|
||||
subprotocols=None,
|
||||
version: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
A helper method to register a function as a websocket route.
|
||||
|
||||
:param handler: a callable function or instance of a class
|
||||
that can handle the websocket request
|
||||
:param host: Host IP or FQDN details
|
||||
:param uri: URL path that will be mapped to the websocket
|
||||
handler
|
||||
handler
|
||||
:param strict_slashes: If the API endpoint needs to terminate
|
||||
with a "/" or not
|
||||
:param subprotocols: Subprotocols to be used with websocket
|
||||
handshake
|
||||
:param name: A unique name assigned to the URL so that it can
|
||||
be used with :func:`url_for`
|
||||
:return: Objected decorated by :func:`websocket`
|
||||
"""
|
||||
return self.websocket(
|
||||
uri=uri,
|
||||
host=host,
|
||||
strict_slashes=strict_slashes,
|
||||
subprotocols=subprotocols,
|
||||
version=version,
|
||||
name=name,
|
||||
)(handler)
|
||||
|
||||
def static(
|
||||
self,
|
||||
uri,
|
||||
file_or_directory: Union[str, bytes, PurePath],
|
||||
pattern=r"/?.+",
|
||||
use_modified_since=True,
|
||||
use_content_range=False,
|
||||
stream_large_files=False,
|
||||
name="static",
|
||||
host=None,
|
||||
strict_slashes=None,
|
||||
content_type=None,
|
||||
apply=True,
|
||||
):
|
||||
"""
|
||||
Register a root to serve files from. The input can either be a
|
||||
file or a directory. This method will enable an easy and simple way
|
||||
to setup the :class:`Route` necessary to serve the static files.
|
||||
|
||||
:param uri: URL path to be used for serving static content
|
||||
:param file_or_directory: Path for the Static file/directory with
|
||||
static files
|
||||
:param pattern: Regex Pattern identifying the valid static files
|
||||
:param use_modified_since: If true, send file modified time, and return
|
||||
not modified if the browser's matches the server's
|
||||
:param use_content_range: If true, process header for range requests
|
||||
and sends the file part that is requested
|
||||
:param stream_large_files: If true, use the
|
||||
:func:`StreamingHTTPResponse.file_stream` handler rather
|
||||
than the :func:`HTTPResponse.file` handler to send the file.
|
||||
If this is an integer, this represents the threshold size to
|
||||
switch to :func:`StreamingHTTPResponse.file_stream`
|
||||
:param name: user defined name used for url_for
|
||||
:param host: Host IP or FQDN for the service to use
|
||||
:param strict_slashes: Instruct :class:`Sanic` to check if the request
|
||||
URLs need to terminate with a */*
|
||||
:param content_type: user defined content type for header
|
||||
:return: routes registered on the router
|
||||
:rtype: List[sanic.router.Route]
|
||||
"""
|
||||
|
||||
name = self._generate_name(name)
|
||||
|
||||
if strict_slashes is None and self.strict_slashes is not None:
|
||||
strict_slashes = self.strict_slashes
|
||||
|
||||
if not isinstance(file_or_directory, (str, bytes, PurePath)):
|
||||
raise ValueError(
|
||||
f"Static route must be a valid path, not {file_or_directory}"
|
||||
)
|
||||
|
||||
static = FutureStatic(
|
||||
uri,
|
||||
file_or_directory,
|
||||
pattern,
|
||||
use_modified_since,
|
||||
use_content_range,
|
||||
stream_large_files,
|
||||
name,
|
||||
host,
|
||||
strict_slashes,
|
||||
content_type,
|
||||
)
|
||||
self._future_statics.add(static)
|
||||
|
||||
if apply:
|
||||
self._apply_static(static)
|
||||
|
||||
def _generate_name(self, *objects) -> str:
|
||||
name = None
|
||||
|
||||
for obj in objects:
|
||||
if obj:
|
||||
if isinstance(obj, str):
|
||||
name = obj
|
||||
break
|
||||
|
||||
try:
|
||||
name = obj.name
|
||||
except AttributeError:
|
||||
try:
|
||||
name = obj.__name__
|
||||
except AttributeError:
|
||||
continue
|
||||
else:
|
||||
break
|
||||
|
||||
if not name: # noqa
|
||||
raise ValueError("Could not generate a name for handler")
|
||||
|
||||
if not name.startswith(f"{self.name}."):
|
||||
name = f"{self.name}.{name}"
|
||||
|
||||
return name
|
||||
|
||||
async def _static_request_handler(
|
||||
self,
|
||||
file_or_directory,
|
||||
use_modified_since,
|
||||
use_content_range,
|
||||
stream_large_files,
|
||||
request,
|
||||
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__)
|
||||
)
|
||||
|
||||
# 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__,
|
||||
)
|
||||
try:
|
||||
headers = {}
|
||||
# Check if the client has been sent this file before
|
||||
# and it has not been modified since
|
||||
stats = None
|
||||
if use_modified_since:
|
||||
stats = await stat_async(file_path)
|
||||
modified_since = strftime(
|
||||
"%a, %d %b %Y %H:%M:%S GMT", gmtime(stats.st_mtime)
|
||||
)
|
||||
if request.headers.get("If-Modified-Since") == modified_since:
|
||||
return HTTPResponse(status=304)
|
||||
headers["Last-Modified"] = modified_since
|
||||
_range = None
|
||||
if use_content_range:
|
||||
_range = None
|
||||
if not stats:
|
||||
stats = await stat_async(file_path)
|
||||
headers["Accept-Ranges"] = "bytes"
|
||||
headers["Content-Length"] = str(stats.st_size)
|
||||
if request.method != "HEAD":
|
||||
try:
|
||||
_range = ContentRangeHandler(request, stats)
|
||||
except HeaderNotFound:
|
||||
pass
|
||||
else:
|
||||
del headers["Content-Length"]
|
||||
for key, value in _range.headers.items():
|
||||
headers[key] = value
|
||||
|
||||
if "content-type" not in headers:
|
||||
content_type = (
|
||||
content_type
|
||||
or guess_type(file_path)[0]
|
||||
or DEFAULT_HTTP_CONTENT_TYPE
|
||||
)
|
||||
|
||||
if "charset=" not in content_type and (
|
||||
content_type.startswith("text/")
|
||||
or content_type == "application/javascript"
|
||||
):
|
||||
content_type += "; charset=utf-8"
|
||||
|
||||
headers["Content-Type"] = content_type
|
||||
|
||||
if request.method == "HEAD":
|
||||
return HTTPResponse(headers=headers)
|
||||
else:
|
||||
if stream_large_files:
|
||||
if type(stream_large_files) == int:
|
||||
threshold = stream_large_files
|
||||
else:
|
||||
threshold = 1024 * 1024
|
||||
|
||||
if not stats:
|
||||
stats = await stat_async(file_path)
|
||||
if stats.st_size >= threshold:
|
||||
return await file_stream(
|
||||
file_path, headers=headers, _range=_range
|
||||
)
|
||||
return await file(file_path, headers=headers, _range=_range)
|
||||
except ContentRangeError:
|
||||
raise
|
||||
except Exception:
|
||||
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__,
|
||||
)
|
||||
|
||||
def _register_static(
|
||||
self,
|
||||
static: FutureStatic,
|
||||
):
|
||||
# TODO: Though sanic is not a file server, I feel like we should
|
||||
# at least make a good effort here. Modified-since is nice, but
|
||||
# we could also look into etags, expires, and caching
|
||||
"""
|
||||
Register a static directory handler with Sanic by adding a route to the
|
||||
router and registering a handler.
|
||||
|
||||
:param app: Sanic
|
||||
:param file_or_directory: File or directory path to serve from
|
||||
:type file_or_directory: Union[str,bytes,Path]
|
||||
:param uri: URL to serve from
|
||||
:type uri: str
|
||||
:param pattern: regular expression used to match files in the URL
|
||||
:param use_modified_since: If true, send file modified time, and return
|
||||
not modified if the browser's matches the
|
||||
server's
|
||||
:param use_content_range: If true, process header for range requests
|
||||
and sends the file part that is requested
|
||||
:param stream_large_files: If true, use the file_stream() handler
|
||||
rather than the file() handler to send the file
|
||||
If this is an integer, this represents the
|
||||
threshold size to switch to file_stream()
|
||||
:param name: user defined name used for url_for
|
||||
:type name: str
|
||||
:param content_type: user defined content type for header
|
||||
:return: registered static routes
|
||||
:rtype: List[sanic.router.Route]
|
||||
"""
|
||||
|
||||
if isinstance(static.file_or_directory, bytes):
|
||||
file_or_directory = static.file_or_directory.decode("utf-8")
|
||||
elif isinstance(static.file_or_directory, PurePath):
|
||||
file_or_directory = str(static.file_or_directory)
|
||||
elif not isinstance(static.file_or_directory, str):
|
||||
raise ValueError("Invalid file path string.")
|
||||
else:
|
||||
file_or_directory = static.file_or_directory
|
||||
|
||||
uri = static.uri
|
||||
name = static.name
|
||||
# If we're not trying to match a file directly,
|
||||
# serve from the folder
|
||||
if not path.isfile(file_or_directory):
|
||||
uri += "/<__file_uri__:path>"
|
||||
|
||||
# special prefix for static files
|
||||
# if not static.name.startswith("_static_"):
|
||||
# name = f"_static_{static.name}"
|
||||
|
||||
_handler = wraps(self._static_request_handler)(
|
||||
partial(
|
||||
self._static_request_handler,
|
||||
file_or_directory,
|
||||
static.use_modified_since,
|
||||
static.use_content_range,
|
||||
static.stream_large_files,
|
||||
content_type=static.content_type,
|
||||
)
|
||||
)
|
||||
|
||||
route, _ = self.route(
|
||||
uri=uri,
|
||||
methods=["GET", "HEAD"],
|
||||
name=name,
|
||||
host=static.host,
|
||||
strict_slashes=static.strict_slashes,
|
||||
static=True,
|
||||
)(_handler)
|
||||
|
||||
return route
|
||||
71
sanic/mixins/signals.py
Normal file
71
sanic/mixins/signals.py
Normal file
@@ -0,0 +1,71 @@
|
||||
from typing import Any, Callable, Dict, Set
|
||||
|
||||
from sanic.models.futures import FutureSignal
|
||||
from sanic.models.handler_types import SignalHandler
|
||||
from sanic.signals import Signal
|
||||
|
||||
|
||||
class HashableDict(dict):
|
||||
def __hash__(self):
|
||||
return hash(tuple(sorted(self.items())))
|
||||
|
||||
|
||||
class SignalMixin:
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self._future_signals: Set[FutureSignal] = set()
|
||||
|
||||
def _apply_signal(self, signal: FutureSignal) -> Signal:
|
||||
raise NotImplementedError # noqa
|
||||
|
||||
def signal(
|
||||
self,
|
||||
event: str,
|
||||
*,
|
||||
apply: bool = True,
|
||||
condition: Dict[str, Any] = None,
|
||||
) -> Callable[[SignalHandler], FutureSignal]:
|
||||
"""
|
||||
For creating a signal handler, used similar to a route handler:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.signal("foo.bar.<thing>")
|
||||
async def signal_handler(thing, **kwargs):
|
||||
print(f"[signal_handler] {thing=}", kwargs)
|
||||
|
||||
:param event: Representation of the event in ``one.two.three`` form
|
||||
:type event: str
|
||||
: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
|
||||
:type condition: Dict[str, Any], optional
|
||||
"""
|
||||
|
||||
def decorator(handler: SignalHandler):
|
||||
nonlocal event
|
||||
nonlocal apply
|
||||
|
||||
future_signal = FutureSignal(
|
||||
handler, event, HashableDict(condition or {})
|
||||
)
|
||||
self._future_signals.add(future_signal)
|
||||
|
||||
if apply:
|
||||
self._apply_signal(future_signal)
|
||||
|
||||
return future_signal
|
||||
|
||||
return decorator
|
||||
|
||||
def add_signal(
|
||||
self,
|
||||
handler,
|
||||
event: str,
|
||||
condition: Dict[str, Any] = None,
|
||||
):
|
||||
self.signal(event=event, condition=condition)(handler)
|
||||
return handler
|
||||
|
||||
def event(self, event: str):
|
||||
raise NotImplementedError
|
||||
0
sanic/models/__init__.py
Normal file
0
sanic/models/__init__.py
Normal file
95
sanic/models/asgi.py
Normal file
95
sanic/models/asgi.py
Normal file
@@ -0,0 +1,95 @@
|
||||
import asyncio
|
||||
|
||||
from typing import Any, Awaitable, Callable, MutableMapping, Optional, Union
|
||||
|
||||
from sanic.exceptions import InvalidUsage
|
||||
from sanic.websocket import WebSocketConnection
|
||||
|
||||
|
||||
ASGIScope = MutableMapping[str, Any]
|
||||
ASGIMessage = MutableMapping[str, Any]
|
||||
ASGISend = Callable[[ASGIMessage], Awaitable[None]]
|
||||
ASGIReceive = Callable[[], Awaitable[ASGIMessage]]
|
||||
|
||||
|
||||
class MockProtocol:
|
||||
def __init__(self, transport: "MockTransport", loop):
|
||||
self.transport = transport
|
||||
self._not_paused = asyncio.Event(loop=loop)
|
||||
self._not_paused.set()
|
||||
self._complete = asyncio.Event(loop=loop)
|
||||
|
||||
def pause_writing(self) -> None:
|
||||
self._not_paused.clear()
|
||||
|
||||
def resume_writing(self) -> None:
|
||||
self._not_paused.set()
|
||||
|
||||
async def complete(self) -> None:
|
||||
self._not_paused.set()
|
||||
await self.transport.send(
|
||||
{"type": "http.response.body", "body": b"", "more_body": False}
|
||||
)
|
||||
|
||||
@property
|
||||
def is_complete(self) -> bool:
|
||||
return self._complete.is_set()
|
||||
|
||||
async def push_data(self, data: bytes) -> None:
|
||||
if not self.is_complete:
|
||||
await self.transport.send(
|
||||
{"type": "http.response.body", "body": data, "more_body": True}
|
||||
)
|
||||
|
||||
async def drain(self) -> None:
|
||||
await self._not_paused.wait()
|
||||
|
||||
|
||||
class MockTransport:
|
||||
_protocol: Optional[MockProtocol]
|
||||
|
||||
def __init__(
|
||||
self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend
|
||||
) -> None:
|
||||
self.scope = scope
|
||||
self._receive = receive
|
||||
self._send = send
|
||||
self._protocol = None
|
||||
self.loop = None
|
||||
|
||||
def get_protocol(self) -> MockProtocol:
|
||||
if not self._protocol:
|
||||
self._protocol = MockProtocol(self, self.loop)
|
||||
return self._protocol
|
||||
|
||||
def get_extra_info(self, info: str) -> Union[str, bool, None]:
|
||||
if info == "peername":
|
||||
return self.scope.get("client")
|
||||
elif info == "sslcontext":
|
||||
return self.scope.get("scheme") in ["https", "wss"]
|
||||
return None
|
||||
|
||||
def get_websocket_connection(self) -> WebSocketConnection:
|
||||
try:
|
||||
return self._websocket_connection
|
||||
except AttributeError:
|
||||
raise InvalidUsage("Improper websocket connection.")
|
||||
|
||||
def create_websocket_connection(
|
||||
self, send: ASGISend, receive: ASGIReceive
|
||||
) -> WebSocketConnection:
|
||||
self._websocket_connection = WebSocketConnection(
|
||||
send, receive, self.scope.get("subprotocols", [])
|
||||
)
|
||||
return self._websocket_connection
|
||||
|
||||
def add_task(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
async def send(self, data) -> None:
|
||||
# TODO:
|
||||
# - Validation on data and that it is formatted properly and is valid
|
||||
await self._send(data)
|
||||
|
||||
async def receive(self) -> ASGIMessage:
|
||||
return await self._receive()
|
||||
59
sanic/models/futures.py
Normal file
59
sanic/models/futures.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from pathlib import PurePath
|
||||
from typing import Dict, Iterable, List, NamedTuple, Optional, Union
|
||||
|
||||
from sanic.models.handler_types import (
|
||||
ErrorMiddlewareType,
|
||||
ListenerType,
|
||||
MiddlewareType,
|
||||
SignalHandler,
|
||||
)
|
||||
|
||||
|
||||
class FutureRoute(NamedTuple):
|
||||
handler: str
|
||||
uri: str
|
||||
methods: Optional[Iterable[str]]
|
||||
host: str
|
||||
strict_slashes: bool
|
||||
stream: bool
|
||||
version: Optional[int]
|
||||
name: str
|
||||
ignore_body: bool
|
||||
websocket: bool
|
||||
subprotocols: Optional[List[str]]
|
||||
unquote: bool
|
||||
static: bool
|
||||
|
||||
|
||||
class FutureListener(NamedTuple):
|
||||
listener: ListenerType
|
||||
event: str
|
||||
|
||||
|
||||
class FutureMiddleware(NamedTuple):
|
||||
middleware: MiddlewareType
|
||||
attach_to: str
|
||||
|
||||
|
||||
class FutureException(NamedTuple):
|
||||
handler: ErrorMiddlewareType
|
||||
exceptions: List[BaseException]
|
||||
|
||||
|
||||
class FutureStatic(NamedTuple):
|
||||
uri: str
|
||||
file_or_directory: Union[str, bytes, PurePath]
|
||||
pattern: str
|
||||
use_modified_since: bool
|
||||
use_content_range: bool
|
||||
stream_large_files: bool
|
||||
name: str
|
||||
host: Optional[str]
|
||||
strict_slashes: Optional[bool]
|
||||
content_type: Optional[bool]
|
||||
|
||||
|
||||
class FutureSignal(NamedTuple):
|
||||
handler: SignalHandler
|
||||
event: str
|
||||
condition: Optional[Dict[str, str]]
|
||||
25
sanic/models/handler_types.py
Normal file
25
sanic/models/handler_types.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from asyncio.events import AbstractEventLoop
|
||||
from typing import Any, Callable, Coroutine, Optional, TypeVar, Union
|
||||
|
||||
from sanic.request import Request
|
||||
from sanic.response import BaseHTTPResponse, HTTPResponse
|
||||
|
||||
|
||||
Sanic = TypeVar("Sanic")
|
||||
|
||||
MiddlewareResponse = Union[
|
||||
Optional[HTTPResponse], Coroutine[Any, Any, Optional[HTTPResponse]]
|
||||
]
|
||||
RequestMiddlewareType = Callable[[Request], MiddlewareResponse]
|
||||
ResponseMiddlewareType = Callable[
|
||||
[Request, BaseHTTPResponse], MiddlewareResponse
|
||||
]
|
||||
ErrorMiddlewareType = Callable[
|
||||
[Request, BaseException], Optional[Coroutine[Any, Any, None]]
|
||||
]
|
||||
MiddlewareType = Union[RequestMiddlewareType, ResponseMiddlewareType]
|
||||
ListenerType = Callable[
|
||||
[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, None]]
|
||||
]
|
||||
RouteHandler = Callable[..., Coroutine[Any, Any, HTTPResponse]]
|
||||
SignalHandler = Callable[..., Coroutine[Any, Any, None]]
|
||||
44
sanic/models/protocol_types.py
Normal file
44
sanic/models/protocol_types.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import sys
|
||||
|
||||
from typing import Any, AnyStr, TypeVar, Union
|
||||
|
||||
|
||||
if sys.version_info < (3, 8):
|
||||
from asyncio import BaseTransport
|
||||
|
||||
# from sanic.models.asgi import MockTransport
|
||||
MockTransport = TypeVar("MockTransport")
|
||||
|
||||
TransportProtocol = Union[MockTransport, BaseTransport]
|
||||
Range = Any
|
||||
HTMLProtocol = Any
|
||||
else:
|
||||
# Protocol is a 3.8+ feature
|
||||
from typing import Protocol
|
||||
|
||||
class TransportProtocol(Protocol):
|
||||
def get_protocol(self):
|
||||
...
|
||||
|
||||
def get_extra_info(self, info: str) -> Union[str, bool, None]:
|
||||
...
|
||||
|
||||
class HTMLProtocol(Protocol):
|
||||
def __html__(self) -> AnyStr:
|
||||
...
|
||||
|
||||
def _repr_html_(self) -> AnyStr:
|
||||
...
|
||||
|
||||
class Range(Protocol):
|
||||
def start(self) -> int:
|
||||
...
|
||||
|
||||
def end(self) -> int:
|
||||
...
|
||||
|
||||
def size(self) -> int:
|
||||
...
|
||||
|
||||
def total(self) -> int:
|
||||
...
|
||||
0
sanic/py.typed
Normal file
0
sanic/py.typed
Normal file
@@ -3,7 +3,6 @@ import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from multiprocessing import Process
|
||||
from time import sleep
|
||||
|
||||
|
||||
@@ -35,101 +34,26 @@ def _iter_module_files():
|
||||
|
||||
def _get_args_for_reloading():
|
||||
"""Returns the executable."""
|
||||
rv = [sys.executable]
|
||||
main_module = sys.modules["__main__"]
|
||||
mod_spec = getattr(main_module, "__spec__", None)
|
||||
if sys.argv[0] in ("", "-c"):
|
||||
raise RuntimeError(
|
||||
f"Autoreloader cannot work with argv[0]={sys.argv[0]!r}"
|
||||
)
|
||||
if mod_spec:
|
||||
# Parent exe was launched as a module rather than a script
|
||||
rv.extend(["-m", mod_spec.name])
|
||||
if len(sys.argv) > 1:
|
||||
rv.extend(sys.argv[1:])
|
||||
else:
|
||||
rv.extend(sys.argv)
|
||||
return rv
|
||||
return [sys.executable, "-m", mod_spec.name] + sys.argv[1:]
|
||||
return [sys.executable] + sys.argv
|
||||
|
||||
|
||||
def restart_with_reloader():
|
||||
"""Create a new process and a subprocess in it with the same arguments as
|
||||
this one.
|
||||
"""
|
||||
cwd = os.getcwd()
|
||||
args = _get_args_for_reloading()
|
||||
new_environ = os.environ.copy()
|
||||
new_environ["SANIC_SERVER_RUNNING"] = "true"
|
||||
cmd = " ".join(args)
|
||||
worker_process = Process(
|
||||
target=subprocess.call,
|
||||
args=(cmd,),
|
||||
kwargs={"cwd": cwd, "shell": True, "env": new_environ},
|
||||
return subprocess.Popen(
|
||||
_get_args_for_reloading(),
|
||||
env={**os.environ, "SANIC_SERVER_RUNNING": "true"},
|
||||
)
|
||||
worker_process.start()
|
||||
return worker_process
|
||||
|
||||
|
||||
def kill_process_children_unix(pid):
|
||||
"""Find and kill child processes of a process (maximum two level).
|
||||
|
||||
:param pid: PID of parent process (process ID)
|
||||
:return: Nothing
|
||||
"""
|
||||
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
|
||||
if not os.path.isfile(root_process_path):
|
||||
return
|
||||
with open(root_process_path) as children_list_file:
|
||||
children_list_pid = children_list_file.read().split()
|
||||
|
||||
for child_pid in children_list_pid:
|
||||
children_proc_path = "/proc/%s/task/%s/children" % (
|
||||
child_pid,
|
||||
child_pid,
|
||||
)
|
||||
if not os.path.isfile(children_proc_path):
|
||||
continue
|
||||
with open(children_proc_path) as children_list_file_2:
|
||||
children_list_pid_2 = children_list_file_2.read().split()
|
||||
for _pid in children_list_pid_2:
|
||||
try:
|
||||
os.kill(int(_pid), signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
continue
|
||||
try:
|
||||
os.kill(int(child_pid), signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
continue
|
||||
|
||||
|
||||
def kill_process_children_osx(pid):
|
||||
"""Find and kill child processes of a process.
|
||||
|
||||
:param pid: PID of parent process (process ID)
|
||||
:return: Nothing
|
||||
"""
|
||||
subprocess.run(["pkill", "-P", str(pid)])
|
||||
|
||||
|
||||
def kill_process_children(pid):
|
||||
"""Find and kill child processes of a process.
|
||||
|
||||
:param pid: PID of parent process (process ID)
|
||||
:return: Nothing
|
||||
"""
|
||||
if sys.platform == "darwin":
|
||||
kill_process_children_osx(pid)
|
||||
elif sys.platform == "linux":
|
||||
kill_process_children_unix(pid)
|
||||
else:
|
||||
pass # should signal error here
|
||||
|
||||
|
||||
def kill_program_completly(proc):
|
||||
"""Kill worker and it's child processes and exit.
|
||||
|
||||
:param proc: worker process (process ID)
|
||||
:return: Nothing
|
||||
"""
|
||||
kill_process_children(proc.pid)
|
||||
proc.terminate()
|
||||
os._exit(0)
|
||||
|
||||
|
||||
def watchdog(sleep_interval):
|
||||
@@ -138,15 +62,21 @@ def watchdog(sleep_interval):
|
||||
:param sleep_interval: interval in second.
|
||||
:return: Nothing
|
||||
"""
|
||||
|
||||
def interrupt_self(*args):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
mtimes = {}
|
||||
signal.signal(signal.SIGTERM, interrupt_self)
|
||||
if os.name == "nt":
|
||||
signal.signal(signal.SIGBREAK, interrupt_self)
|
||||
|
||||
worker_process = restart_with_reloader()
|
||||
signal.signal(
|
||||
signal.SIGTERM, lambda *args: kill_program_completly(worker_process)
|
||||
)
|
||||
signal.signal(
|
||||
signal.SIGINT, lambda *args: kill_program_completly(worker_process)
|
||||
)
|
||||
|
||||
try:
|
||||
while True:
|
||||
need_reload = False
|
||||
|
||||
for filename in _iter_module_files():
|
||||
try:
|
||||
mtime = os.stat(filename).st_mtime
|
||||
@@ -156,12 +86,18 @@ def watchdog(sleep_interval):
|
||||
old_time = mtimes.get(filename)
|
||||
if old_time is None:
|
||||
mtimes[filename] = mtime
|
||||
continue
|
||||
elif mtime > old_time:
|
||||
kill_process_children(worker_process.pid)
|
||||
worker_process.terminate()
|
||||
worker_process = restart_with_reloader()
|
||||
mtimes[filename] = mtime
|
||||
break
|
||||
need_reload = True
|
||||
|
||||
if need_reload:
|
||||
worker_process.terminate()
|
||||
worker_process.wait()
|
||||
worker_process = restart_with_reloader()
|
||||
|
||||
sleep(sleep_interval)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
worker_process.terminate()
|
||||
worker_process.wait()
|
||||
|
||||
516
sanic/request.py
516
sanic/request.py
@@ -1,22 +1,48 @@
|
||||
import asyncio
|
||||
import email.utils
|
||||
import warnings
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict, namedtuple
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
DefaultDict,
|
||||
Dict,
|
||||
List,
|
||||
NamedTuple,
|
||||
Optional,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from sanic_routing.route import Route # type: ignore
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sanic.server import ConnInfo
|
||||
from sanic.app import Sanic
|
||||
from sanic.http import Http
|
||||
|
||||
import email.utils
|
||||
import uuid
|
||||
|
||||
from collections import defaultdict
|
||||
from http.cookies import SimpleCookie
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import parse_qs, parse_qsl, unquote, urlunparse
|
||||
|
||||
from httptools import parse_url # type: ignore
|
||||
|
||||
from sanic.compat import CancelledErrors, Header
|
||||
from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE
|
||||
from sanic.exceptions import InvalidUsage
|
||||
from sanic.headers import (
|
||||
Options,
|
||||
parse_content_header,
|
||||
parse_forwarded,
|
||||
parse_host,
|
||||
parse_xforwarded,
|
||||
)
|
||||
from sanic.log import error_logger, logger
|
||||
from sanic.models.protocol_types import TransportProtocol
|
||||
from sanic.response import BaseHTTPResponse, HTTPResponse
|
||||
|
||||
|
||||
try:
|
||||
@@ -24,64 +50,48 @@ try:
|
||||
except ImportError:
|
||||
from json import loads as json_loads # type: ignore
|
||||
|
||||
DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
|
||||
EXPECT_HEADER = "EXPECT"
|
||||
|
||||
# HTTP/1.1: https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
|
||||
# > If the media type remains unknown, the recipient SHOULD treat it
|
||||
# > as type "application/octet-stream"
|
||||
|
||||
|
||||
class RequestParameters(dict):
|
||||
"""Hosts a dict with lists as values where get returns the first
|
||||
"""
|
||||
Hosts a dict with lists as values where get returns the first
|
||||
value of the list and getlist returns the whole shebang
|
||||
"""
|
||||
|
||||
def get(self, name, default=None):
|
||||
def get(self, name: str, default: Optional[Any] = None) -> Optional[Any]:
|
||||
"""Return the first value, either the default or actual"""
|
||||
return super().get(name, [default])[0]
|
||||
|
||||
def getlist(self, name, default=None):
|
||||
"""Return the entire list"""
|
||||
def getlist(
|
||||
self, name: str, default: Optional[Any] = None
|
||||
) -> Optional[Any]:
|
||||
"""
|
||||
Return the entire list
|
||||
"""
|
||||
return super().get(name, default)
|
||||
|
||||
|
||||
class StreamBuffer:
|
||||
def __init__(self, buffer_size=100):
|
||||
self._queue = asyncio.Queue(buffer_size)
|
||||
|
||||
async def read(self):
|
||||
""" Stop reading when gets None """
|
||||
payload = await self._queue.get()
|
||||
self._queue.task_done()
|
||||
return payload
|
||||
|
||||
async def put(self, payload):
|
||||
await self._queue.put(payload)
|
||||
|
||||
def is_full(self):
|
||||
return self._queue.full()
|
||||
|
||||
@property
|
||||
def buffer_size(self):
|
||||
return self._queue.maxsize
|
||||
|
||||
|
||||
class Request:
|
||||
"""Properties of an HTTP request such as URL, headers, etc."""
|
||||
"""
|
||||
Properties of an HTTP request such as URL, headers, etc.
|
||||
"""
|
||||
|
||||
__slots__ = (
|
||||
"__weakref__",
|
||||
"_cookies",
|
||||
"_id",
|
||||
"_ip",
|
||||
"_parsed_url",
|
||||
"_port",
|
||||
"_protocol",
|
||||
"_remote_addr",
|
||||
"_socket",
|
||||
"_match_info",
|
||||
"_name",
|
||||
"app",
|
||||
"body",
|
||||
"conn_info",
|
||||
"ctx",
|
||||
"endpoint",
|
||||
"head",
|
||||
"headers",
|
||||
"method",
|
||||
"parsed_args",
|
||||
@@ -91,75 +101,183 @@ class Request:
|
||||
"parsed_json",
|
||||
"parsed_forwarded",
|
||||
"raw_url",
|
||||
"request_middleware_started",
|
||||
"route",
|
||||
"stream",
|
||||
"transport",
|
||||
"uri_template",
|
||||
"version",
|
||||
)
|
||||
|
||||
def __init__(self, url_bytes, headers, version, method, transport, app):
|
||||
def __init__(
|
||||
self,
|
||||
url_bytes: bytes,
|
||||
headers: Header,
|
||||
version: str,
|
||||
method: str,
|
||||
transport: TransportProtocol,
|
||||
app: Sanic,
|
||||
head: bytes = b"",
|
||||
):
|
||||
self.raw_url = url_bytes
|
||||
# TODO: Content-Encoding detection
|
||||
self._parsed_url = parse_url(url_bytes)
|
||||
self._id: Optional[Union[uuid.UUID, str, int]] = None
|
||||
self._name: Optional[str] = None
|
||||
self.app = app
|
||||
|
||||
self.headers = headers
|
||||
self.version = version
|
||||
self.method = method
|
||||
self.transport = transport
|
||||
self.head = head
|
||||
|
||||
# Init but do not inhale
|
||||
self.body_init()
|
||||
self.body = b""
|
||||
self.conn_info: Optional[ConnInfo] = None
|
||||
self.ctx = SimpleNamespace()
|
||||
self.parsed_forwarded = None
|
||||
self.parsed_forwarded: Optional[Options] = None
|
||||
self.parsed_json = None
|
||||
self.parsed_form = None
|
||||
self.parsed_files = None
|
||||
self.parsed_args = defaultdict(RequestParameters)
|
||||
self.parsed_not_grouped_args = defaultdict(list)
|
||||
self.uri_template = None
|
||||
self._cookies = None
|
||||
self.stream = None
|
||||
self.endpoint = None
|
||||
self.parsed_args: DefaultDict[
|
||||
Tuple[bool, bool, str, str], RequestParameters
|
||||
] = defaultdict(RequestParameters)
|
||||
self.parsed_not_grouped_args: DefaultDict[
|
||||
Tuple[bool, bool, str, str], List[Tuple[str, str]]
|
||||
] = defaultdict(list)
|
||||
self.request_middleware_started = False
|
||||
self._cookies: Optional[Dict[str, str]] = None
|
||||
self._match_info: Dict[str, Any] = {}
|
||||
self.stream: Optional[Http] = None
|
||||
self.route: Optional[Route] = None
|
||||
self._protocol = None
|
||||
|
||||
def __repr__(self):
|
||||
return "<{0}: {1} {2}>".format(
|
||||
self.__class__.__name__, self.method, self.path
|
||||
class_name = self.__class__.__name__
|
||||
return f"<{class_name}: {self.method} {self.path}>"
|
||||
|
||||
@classmethod
|
||||
def generate_id(*_):
|
||||
return uuid.uuid4()
|
||||
|
||||
async def respond(
|
||||
self,
|
||||
response: Optional[BaseHTTPResponse] = None,
|
||||
*,
|
||||
status: int = 200,
|
||||
headers: Optional[Union[Header, Dict[str, str]]] = None,
|
||||
content_type: Optional[str] = None,
|
||||
):
|
||||
# This logic of determining which response to use is subject to change
|
||||
if response is None:
|
||||
response = (self.stream and self.stream.response) or HTTPResponse(
|
||||
status=status,
|
||||
headers=headers,
|
||||
content_type=content_type,
|
||||
)
|
||||
# Connect the response
|
||||
if isinstance(response, BaseHTTPResponse) and self.stream:
|
||||
response = self.stream.respond(response)
|
||||
# Run response middleware
|
||||
try:
|
||||
response = await self.app._run_response_middleware(
|
||||
self, response, request_name=self.name
|
||||
)
|
||||
except CancelledErrors:
|
||||
raise
|
||||
except Exception:
|
||||
error_logger.exception(
|
||||
"Exception occurred in one of response middleware handlers"
|
||||
)
|
||||
return response
|
||||
|
||||
async def receive_body(self):
|
||||
"""Receive request.body, if not already received.
|
||||
|
||||
Streaming handlers may call this to receive the full body. Sanic calls
|
||||
this function before running any handlers of non-streaming routes.
|
||||
|
||||
Custom request classes can override this for custom handling of both
|
||||
streaming and non-streaming routes.
|
||||
"""
|
||||
if not self.body:
|
||||
self.body = b"".join([data async for data in self.stream])
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
if self._name:
|
||||
return self._name
|
||||
elif self.route:
|
||||
return self.route.name
|
||||
return None
|
||||
|
||||
@property
|
||||
def endpoint(self):
|
||||
return self.name
|
||||
|
||||
@property
|
||||
def uri_template(self):
|
||||
return f"/{self.route.path}"
|
||||
|
||||
@property
|
||||
def protocol(self):
|
||||
if not self._protocol:
|
||||
self._protocol = self.transport.get_protocol()
|
||||
return self._protocol
|
||||
|
||||
@property
|
||||
def raw_headers(self):
|
||||
_, headers = self.head.split(b"\r\n", 1)
|
||||
return bytes(headers)
|
||||
|
||||
@property
|
||||
def request_line(self):
|
||||
reqline, _ = self.head.split(b"\r\n", 1)
|
||||
return bytes(reqline)
|
||||
|
||||
@property
|
||||
def id(self) -> Optional[Union[uuid.UUID, str, int]]:
|
||||
"""
|
||||
A request ID passed from the client, or generated from the backend.
|
||||
|
||||
By default, this will look in a request header defined at:
|
||||
``self.app.config.REQUEST_ID_HEADER``. It defaults to
|
||||
``X-Request-ID``. Sanic will try to cast the ID into a ``UUID`` or an
|
||||
``int``. If there is not a UUID from the client, then Sanic will try
|
||||
to generate an ID by calling ``Request.generate_id()``. The default
|
||||
behavior is to generate a ``UUID``. You can customize this behavior
|
||||
by subclassing ``Request``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sanic import Request, Sanic
|
||||
from itertools import count
|
||||
|
||||
class IntRequest(Request):
|
||||
counter = count()
|
||||
|
||||
def generate_id(self):
|
||||
return next(self.counter)
|
||||
|
||||
app = Sanic("MyApp", request_class=IntRequest)
|
||||
"""
|
||||
if not self._id:
|
||||
self._id = self.headers.get(
|
||||
self.app.config.REQUEST_ID_HEADER,
|
||||
self.__class__.generate_id(self), # type: ignore
|
||||
)
|
||||
|
||||
def get(self, key, default=None):
|
||||
""".. deprecated:: 19.9
|
||||
Custom context is now stored in `request.custom_context.yourkey`"""
|
||||
return self.ctx.__dict__.get(key, default)
|
||||
# Try casting to a UUID or an integer
|
||||
if isinstance(self._id, str):
|
||||
try:
|
||||
self._id = uuid.UUID(self._id)
|
||||
except ValueError:
|
||||
try:
|
||||
self._id = int(self._id) # type: ignore
|
||||
except ValueError:
|
||||
...
|
||||
|
||||
def __contains__(self, key):
|
||||
""".. deprecated:: 19.9
|
||||
Custom context is now stored in `request.custom_context.yourkey`"""
|
||||
return key in self.ctx.__dict__
|
||||
|
||||
def __getitem__(self, key):
|
||||
""".. deprecated:: 19.9
|
||||
Custom context is now stored in `request.custom_context.yourkey`"""
|
||||
return self.ctx.__dict__[key]
|
||||
|
||||
def __delitem__(self, key):
|
||||
""".. deprecated:: 19.9
|
||||
Custom context is now stored in `request.custom_context.yourkey`"""
|
||||
del self.ctx.__dict__[key]
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
""".. deprecated:: 19.9
|
||||
Custom context is now stored in `request.custom_context.yourkey`"""
|
||||
setattr(self.ctx, key, value)
|
||||
|
||||
def body_init(self):
|
||||
self.body = []
|
||||
|
||||
def body_push(self, data):
|
||||
self.body.append(data)
|
||||
|
||||
def body_finish(self):
|
||||
self.body = b"".join(self.body)
|
||||
return self._id # type: ignore
|
||||
|
||||
@property
|
||||
def json(self):
|
||||
@@ -282,18 +400,6 @@ class Request:
|
||||
|
||||
args = property(get_args)
|
||||
|
||||
@property
|
||||
def raw_args(self) -> dict:
|
||||
if self.app.debug: # pragma: no cover
|
||||
warnings.simplefilter("default")
|
||||
warnings.warn(
|
||||
"Use of raw_args will be deprecated in "
|
||||
"the future versions. Please use args or query_args "
|
||||
"properties instead",
|
||||
DeprecationWarning,
|
||||
)
|
||||
return {k: v[0] for k, v in self.args.items()}
|
||||
|
||||
def get_query_args(
|
||||
self,
|
||||
keep_blank_values: bool = False,
|
||||
@@ -346,13 +452,22 @@ class Request:
|
||||
]
|
||||
|
||||
query_args = property(get_query_args)
|
||||
"""
|
||||
Convenience property to access :meth:`Request.get_query_args` with
|
||||
default values.
|
||||
"""
|
||||
|
||||
@property
|
||||
def cookies(self):
|
||||
def cookies(self) -> Dict[str, str]:
|
||||
"""
|
||||
:return: Incoming cookies on the request
|
||||
:rtype: Dict[str, str]
|
||||
"""
|
||||
|
||||
if self._cookies is None:
|
||||
cookie = self.headers.get("Cookie")
|
||||
if cookie is not None:
|
||||
cookies = SimpleCookie()
|
||||
cookies: SimpleCookie = SimpleCookie()
|
||||
cookies.load(cookie)
|
||||
self._cookies = {
|
||||
name: cookie.value for name, cookie in cookies.items()
|
||||
@@ -362,55 +477,68 @@ class Request:
|
||||
return self._cookies
|
||||
|
||||
@property
|
||||
def ip(self):
|
||||
def content_type(self) -> str:
|
||||
"""
|
||||
:return: peer ip of the socket
|
||||
:return: Content-Type header form the request
|
||||
:rtype: str
|
||||
"""
|
||||
if not hasattr(self, "_socket"):
|
||||
self._get_address()
|
||||
return self._ip
|
||||
return self.headers.get("Content-Type", DEFAULT_HTTP_CONTENT_TYPE)
|
||||
|
||||
@property
|
||||
def port(self):
|
||||
def match_info(self):
|
||||
"""
|
||||
:return: matched info after resolving route
|
||||
"""
|
||||
return self._match_info
|
||||
|
||||
# Transport properties (obtained from local interface only)
|
||||
|
||||
@property
|
||||
def ip(self) -> str:
|
||||
"""
|
||||
:return: peer ip of the socket
|
||||
:rtype: str
|
||||
"""
|
||||
return self.conn_info.client if self.conn_info else ""
|
||||
|
||||
@property
|
||||
def port(self) -> int:
|
||||
"""
|
||||
:return: peer port of the socket
|
||||
:rtype: int
|
||||
"""
|
||||
if not hasattr(self, "_socket"):
|
||||
self._get_address()
|
||||
return self._port
|
||||
return self.conn_info.client_port if self.conn_info else 0
|
||||
|
||||
@property
|
||||
def socket(self):
|
||||
if not hasattr(self, "_socket"):
|
||||
self._get_address()
|
||||
return self._socket
|
||||
|
||||
def _get_address(self):
|
||||
self._socket = self.transport.get_extra_info("peername") or (
|
||||
None,
|
||||
None,
|
||||
)
|
||||
self._ip = self._socket[0]
|
||||
self._port = self._socket[1]
|
||||
return self.conn_info.peername if self.conn_info else (None, None)
|
||||
|
||||
@property
|
||||
def server_name(self):
|
||||
def path(self) -> str:
|
||||
"""
|
||||
Attempt to get the server's external hostname in this order:
|
||||
`config.SERVER_NAME`, proxied or direct Host headers
|
||||
:func:`Request.host`
|
||||
|
||||
:return: the server name without port number
|
||||
:return: path of the local HTTP request
|
||||
:rtype: str
|
||||
"""
|
||||
server_name = self.app.config.get("SERVER_NAME")
|
||||
if server_name:
|
||||
host = server_name.split("//", 1)[-1].split("/", 1)[0]
|
||||
return parse_host(host)[0]
|
||||
return parse_host(self.host)[0]
|
||||
return self._parsed_url.path.decode("utf-8")
|
||||
|
||||
# Proxy properties (using SERVER_NAME/forwarded/request/transport info)
|
||||
|
||||
@property
|
||||
def forwarded(self):
|
||||
def forwarded(self) -> Options:
|
||||
"""
|
||||
Active proxy information obtained from request headers, as specified in
|
||||
Sanic configuration.
|
||||
|
||||
Field names by, for, proto, host, port and path are normalized.
|
||||
- for and by IPv6 addresses are bracketed
|
||||
- port (int) is only set by port headers, not from host.
|
||||
- path is url-unencoded
|
||||
|
||||
Additional values may be available from new style Forwarded headers.
|
||||
|
||||
:return: forwarded address info
|
||||
:rtype: Dict[str, str]
|
||||
"""
|
||||
if self.parsed_forwarded is None:
|
||||
self.parsed_forwarded = (
|
||||
parse_forwarded(self.headers, self.app.config)
|
||||
@@ -420,50 +548,36 @@ class Request:
|
||||
return self.parsed_forwarded
|
||||
|
||||
@property
|
||||
def server_port(self):
|
||||
def remote_addr(self) -> str:
|
||||
"""
|
||||
Attempt to get the server's external port number in this order:
|
||||
`config.SERVER_NAME`, proxied or direct Host headers
|
||||
:func:`Request.host`,
|
||||
actual port used by the transport layer socket.
|
||||
:return: server port
|
||||
:rtype: int
|
||||
"""
|
||||
if self.forwarded:
|
||||
return self.forwarded.get("port") or (
|
||||
80 if self.scheme in ("http", "ws") else 443
|
||||
)
|
||||
return (
|
||||
parse_host(self.host)[1]
|
||||
or self.transport.get_extra_info("sockname")[1]
|
||||
)
|
||||
Client IP address, if available.
|
||||
1. proxied remote address `self.forwarded['for']`
|
||||
2. local remote address `self.ip`
|
||||
|
||||
@property
|
||||
def remote_addr(self):
|
||||
"""Attempt to return the original client ip based on `forwarded`,
|
||||
`x-forwarded-for` or `x-real-ip`. If HTTP headers are unavailable or
|
||||
untrusted, returns an empty string.
|
||||
|
||||
:return: original client ip.
|
||||
:return: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
|
||||
:rtype: str
|
||||
"""
|
||||
if not hasattr(self, "_remote_addr"):
|
||||
self._remote_addr = self.forwarded.get("for", "")
|
||||
self._remote_addr = str(
|
||||
self.forwarded.get("for", "")
|
||||
) # or self.ip
|
||||
return self._remote_addr
|
||||
|
||||
@property
|
||||
def scheme(self):
|
||||
def scheme(self) -> str:
|
||||
"""
|
||||
Attempt to get the request scheme.
|
||||
Seeking the value in this order:
|
||||
`forwarded` header, `x-forwarded-proto` header,
|
||||
`x-scheme` header, the sanic app itself.
|
||||
Determine request scheme.
|
||||
1. `config.SERVER_NAME` if in full URL format
|
||||
2. proxied proto/scheme
|
||||
3. local connection protocol
|
||||
|
||||
:return: http|https|ws|wss or arbitrary value given by the headers.
|
||||
:rtype: str
|
||||
"""
|
||||
forwarded_proto = self.forwarded.get("proto")
|
||||
if forwarded_proto:
|
||||
return forwarded_proto
|
||||
if "//" in self.app.config.get("SERVER_NAME", ""):
|
||||
return self.app.config.SERVER_NAME.split("//")[0]
|
||||
if "proto" in self.forwarded:
|
||||
return str(self.forwarded["proto"])
|
||||
|
||||
if (
|
||||
self.app.websocket_enabled
|
||||
@@ -479,40 +593,75 @@ class Request:
|
||||
return scheme
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
def host(self) -> str:
|
||||
"""
|
||||
:return: proxied or direct Host header. Hostname and port number may be
|
||||
separated by sanic.headers.parse_host(request.host).
|
||||
The currently effective server 'host' (hostname or hostname:port).
|
||||
1. `config.SERVER_NAME` overrides any client headers
|
||||
2. proxied host of original request
|
||||
3. request host header
|
||||
hostname and port may be separated by
|
||||
`sanic.headers.parse_host(request.host)`.
|
||||
|
||||
:return: the first matching host found, or empty string
|
||||
:rtype: str
|
||||
"""
|
||||
return self.forwarded.get("host", self.headers.get("Host", ""))
|
||||
server_name = self.app.config.get("SERVER_NAME")
|
||||
if server_name:
|
||||
return server_name.split("//", 1)[-1].split("/", 1)[0]
|
||||
return str(self.forwarded.get("host") or self.headers.get("host", ""))
|
||||
|
||||
@property
|
||||
def content_type(self):
|
||||
return self.headers.get("Content-Type", DEFAULT_HTTP_CONTENT_TYPE)
|
||||
def server_name(self) -> str:
|
||||
"""
|
||||
:return: hostname the client connected to, by ``request.host``
|
||||
:rtype: str
|
||||
"""
|
||||
return parse_host(self.host)[0] or ""
|
||||
|
||||
@property
|
||||
def match_info(self):
|
||||
"""return matched info after resolving route"""
|
||||
return self.app.router.get(self)[2]
|
||||
def server_port(self) -> int:
|
||||
"""
|
||||
The port the client connected to, by forwarded ``port`` or
|
||||
``request.host``.
|
||||
|
||||
Default port is returned as 80 and 443 based on ``request.scheme``.
|
||||
|
||||
:return: port number
|
||||
:rtype: int
|
||||
"""
|
||||
port = self.forwarded.get("port") or parse_host(self.host)[1]
|
||||
return int(port or (80 if self.scheme in ("http", "ws") else 443))
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
return self._parsed_url.path.decode("utf-8")
|
||||
def server_path(self) -> str:
|
||||
"""
|
||||
:return: full path of current URL; uses proxied or local path
|
||||
:rtype: str
|
||||
"""
|
||||
return str(self.forwarded.get("path") or self.path)
|
||||
|
||||
@property
|
||||
def query_string(self):
|
||||
def query_string(self) -> str:
|
||||
"""
|
||||
:return: representation of the requested query
|
||||
:rtype: str
|
||||
"""
|
||||
if self._parsed_url.query:
|
||||
return self._parsed_url.query.decode("utf-8")
|
||||
else:
|
||||
return ""
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
def url(self) -> str:
|
||||
"""
|
||||
:return: the URL
|
||||
:rtype: str
|
||||
"""
|
||||
return urlunparse(
|
||||
(self.scheme, self.host, self.path, None, self.query_string, None)
|
||||
)
|
||||
|
||||
def url_for(self, view_name, **kwargs):
|
||||
def url_for(self, view_name: str, **kwargs) -> str:
|
||||
"""
|
||||
Same as :func:`sanic.Sanic.url_for`, but automatically determine
|
||||
`scheme` and `netloc` base on the request. Since this method is aiming
|
||||
@@ -538,18 +687,31 @@ class Request:
|
||||
):
|
||||
netloc = host
|
||||
else:
|
||||
netloc = "{}:{}".format(host, port)
|
||||
netloc = f"{host}:{port}"
|
||||
|
||||
return self.app.url_for(
|
||||
view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs
|
||||
)
|
||||
|
||||
|
||||
File = namedtuple("File", ["type", "body", "name"])
|
||||
class File(NamedTuple):
|
||||
"""
|
||||
Model for defining a file. It is a ``namedtuple``, therefore you can
|
||||
iterate over the object, or access the parameters by name.
|
||||
|
||||
:param type: The mimetype, defaults to text/plain
|
||||
:param body: Bytes of the file
|
||||
:param name: The filename
|
||||
"""
|
||||
|
||||
type: str
|
||||
body: bytes
|
||||
name: str
|
||||
|
||||
|
||||
def parse_multipart_form(body, boundary):
|
||||
"""Parse a request body and returns fields and files
|
||||
"""
|
||||
Parse a request body and returns fields and files
|
||||
|
||||
:param body: bytes request body
|
||||
:param boundary: bytes multipart boundary
|
||||
|
||||
@@ -1,227 +1,261 @@
|
||||
from functools import partial
|
||||
from mimetypes import guess_type
|
||||
from os import path
|
||||
from pathlib import PurePath
|
||||
from typing import (
|
||||
Any,
|
||||
AnyStr,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Iterator,
|
||||
Optional,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
from urllib.parse import quote_plus
|
||||
from warnings import warn
|
||||
|
||||
from aiofiles import open as open_async # type: ignore
|
||||
|
||||
from sanic.compat import Header
|
||||
from sanic.compat import Header, open_async
|
||||
from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE
|
||||
from sanic.cookies import CookieJar
|
||||
from sanic.headers import format_http1
|
||||
from sanic.helpers import STATUS_CODES, has_message_body, remove_entity_headers
|
||||
from sanic.helpers import has_message_body, remove_entity_headers
|
||||
from sanic.http import Http
|
||||
from sanic.models.protocol_types import HTMLProtocol, Range
|
||||
|
||||
|
||||
try:
|
||||
from ujson import dumps as json_dumps
|
||||
except ImportError:
|
||||
from json import dumps
|
||||
|
||||
# This is done in order to ensure that the JSON response is
|
||||
# kept consistent across both ujson and inbuilt json usage.
|
||||
from json import dumps
|
||||
|
||||
json_dumps = partial(dumps, separators=(",", ":"))
|
||||
|
||||
|
||||
class BaseHTTPResponse:
|
||||
def _encode_body(self, data):
|
||||
try:
|
||||
# Try to encode it regularly
|
||||
return data.encode()
|
||||
except AttributeError:
|
||||
# Convert it to a str if you can't
|
||||
return str(data).encode()
|
||||
"""
|
||||
The base class for all HTTP Responses
|
||||
"""
|
||||
|
||||
def _parse_headers(self):
|
||||
return format_http1(self.headers.items())
|
||||
_dumps = json_dumps
|
||||
|
||||
def __init__(self):
|
||||
self.asgi: bool = False
|
||||
self.body: Optional[bytes] = None
|
||||
self.content_type: Optional[str] = None
|
||||
self.stream: Http = None
|
||||
self.status: int = None
|
||||
self.headers = Header({})
|
||||
self._cookies: Optional[CookieJar] = None
|
||||
|
||||
def _encode_body(self, data: Optional[AnyStr]):
|
||||
if data is None:
|
||||
return b""
|
||||
return (
|
||||
data.encode() if hasattr(data, "encode") else data # type: ignore
|
||||
)
|
||||
|
||||
@property
|
||||
def cookies(self):
|
||||
def cookies(self) -> CookieJar:
|
||||
"""
|
||||
The response cookies. Cookies should be set and written as follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
response.cookies["test"] = "It worked!"
|
||||
response.cookies["test"]["domain"] = ".yummy-yummy-cookie.com"
|
||||
response.cookies["test"]["httponly"] = True
|
||||
|
||||
`See user guide re: cookies
|
||||
<https://sanicframework.org/guide/basics/cookies.html>`__
|
||||
|
||||
:return: the cookie jar
|
||||
:rtype: CookieJar
|
||||
"""
|
||||
if self._cookies is None:
|
||||
self._cookies = CookieJar(self.headers)
|
||||
return self._cookies
|
||||
|
||||
@property
|
||||
def processed_headers(self) -> Iterator[Tuple[bytes, bytes]]:
|
||||
"""
|
||||
Obtain a list of header tuples encoded in bytes for sending.
|
||||
|
||||
Add and remove headers based on status and content_type.
|
||||
|
||||
:return: response headers
|
||||
:rtype: Tuple[Tuple[bytes, bytes], ...]
|
||||
"""
|
||||
# TODO: Make a blacklist set of header names and then filter with that
|
||||
if self.status in (304, 412): # Not Modified, Precondition Failed
|
||||
self.headers = remove_entity_headers(self.headers)
|
||||
if has_message_body(self.status):
|
||||
self.headers.setdefault("content-type", self.content_type)
|
||||
# Encode headers into bytes
|
||||
return (
|
||||
(name.encode("ascii"), f"{value}".encode(errors="surrogateescape"))
|
||||
for name, value in self.headers.items()
|
||||
)
|
||||
|
||||
async def send(
|
||||
self,
|
||||
data: Optional[Union[AnyStr]] = None,
|
||||
end_stream: Optional[bool] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Send any pending response headers and the given data as body.
|
||||
|
||||
:param data: str or bytes to be written
|
||||
:param end_stream: whether to close the stream after this block
|
||||
"""
|
||||
if data is None and end_stream is None:
|
||||
end_stream = True
|
||||
if end_stream and not data and self.stream.send is None:
|
||||
return
|
||||
data = (
|
||||
data.encode() # type: ignore
|
||||
if hasattr(data, "encode")
|
||||
else data or b""
|
||||
)
|
||||
await self.stream.send(data, end_stream=end_stream)
|
||||
|
||||
|
||||
StreamingFunction = Callable[[BaseHTTPResponse], Coroutine[Any, Any, None]]
|
||||
|
||||
|
||||
class StreamingHTTPResponse(BaseHTTPResponse):
|
||||
"""
|
||||
Old style streaming response where you pass a streaming function:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def sample_streaming_fn(response):
|
||||
await response.write("foo")
|
||||
await asyncio.sleep(1)
|
||||
await response.write("bar")
|
||||
await asyncio.sleep(1)
|
||||
|
||||
@app.post("/")
|
||||
async def test(request):
|
||||
return stream(sample_streaming_fn)
|
||||
|
||||
.. warning::
|
||||
|
||||
**Deprecated** and set for removal in v21.6. You can now achieve the
|
||||
same functionality without a callback.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@app.post("/")
|
||||
async def test(request):
|
||||
response = await request.respond()
|
||||
await response.send("foo", False)
|
||||
await asyncio.sleep(1)
|
||||
await response.send("bar", False)
|
||||
await asyncio.sleep(1)
|
||||
await response.send("", True)
|
||||
return response
|
||||
|
||||
"""
|
||||
|
||||
__slots__ = (
|
||||
"protocol",
|
||||
"streaming_fn",
|
||||
"status",
|
||||
"content_type",
|
||||
"headers",
|
||||
"chunked",
|
||||
"_cookies",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
streaming_fn,
|
||||
status=200,
|
||||
headers=None,
|
||||
content_type="text/plain",
|
||||
chunked=True,
|
||||
streaming_fn: StreamingFunction,
|
||||
status: int = 200,
|
||||
headers: Optional[Union[Header, Dict[str, str]]] = None,
|
||||
content_type: str = "text/plain; charset=utf-8",
|
||||
chunked="deprecated",
|
||||
):
|
||||
if chunked != "deprecated":
|
||||
warn(
|
||||
"The chunked argument has been deprecated and will be "
|
||||
"removed in v21.6"
|
||||
)
|
||||
|
||||
super().__init__()
|
||||
|
||||
self.content_type = content_type
|
||||
self.streaming_fn = streaming_fn
|
||||
self.status = status
|
||||
self.headers = Header(headers or {})
|
||||
self.chunked = chunked
|
||||
self._cookies = None
|
||||
|
||||
async def write(self, data):
|
||||
"""Writes a chunk of data to the streaming response.
|
||||
|
||||
:param data: bytes-ish data to be written.
|
||||
:param data: str or bytes-ish data to be written.
|
||||
"""
|
||||
if type(data) != bytes:
|
||||
data = self._encode_body(data)
|
||||
await super().send(self._encode_body(data))
|
||||
|
||||
if self.chunked:
|
||||
await self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
|
||||
else:
|
||||
await self.protocol.push_data(data)
|
||||
await self.protocol.drain()
|
||||
|
||||
async def stream(
|
||||
self, version="1.1", keep_alive=False, keep_alive_timeout=None
|
||||
):
|
||||
"""Streams headers, runs the `streaming_fn` callback that writes
|
||||
content to the response body, then finalizes the response body.
|
||||
"""
|
||||
if version != "1.1":
|
||||
self.chunked = False
|
||||
headers = self.get_headers(
|
||||
version,
|
||||
keep_alive=keep_alive,
|
||||
keep_alive_timeout=keep_alive_timeout,
|
||||
)
|
||||
await self.protocol.push_data(headers)
|
||||
await self.protocol.drain()
|
||||
async def send(self, *args, **kwargs):
|
||||
if self.streaming_fn is not None:
|
||||
await self.streaming_fn(self)
|
||||
if self.chunked:
|
||||
await self.protocol.push_data(b"0\r\n\r\n")
|
||||
# no need to await drain here after this write, because it is the
|
||||
# very last thing we write and nothing needs to wait for it.
|
||||
|
||||
def get_headers(
|
||||
self, version="1.1", keep_alive=False, keep_alive_timeout=None
|
||||
):
|
||||
# This is all returned in a kind-of funky way
|
||||
# We tried to make this as fast as possible in pure python
|
||||
timeout_header = b""
|
||||
if keep_alive and keep_alive_timeout is not None:
|
||||
timeout_header = b"Keep-Alive: %d\r\n" % keep_alive_timeout
|
||||
|
||||
if self.chunked and version == "1.1":
|
||||
self.headers["Transfer-Encoding"] = "chunked"
|
||||
self.headers.pop("Content-Length", None)
|
||||
self.headers["Content-Type"] = self.headers.get(
|
||||
"Content-Type", self.content_type
|
||||
)
|
||||
|
||||
headers = self._parse_headers()
|
||||
|
||||
if self.status == 200:
|
||||
status = b"OK"
|
||||
else:
|
||||
status = STATUS_CODES.get(self.status)
|
||||
|
||||
return (b"HTTP/%b %d %b\r\n" b"%b" b"%b\r\n") % (
|
||||
version.encode(),
|
||||
self.status,
|
||||
status,
|
||||
timeout_header,
|
||||
headers,
|
||||
)
|
||||
self.streaming_fn = None
|
||||
await super().send(*args, **kwargs)
|
||||
|
||||
|
||||
class HTTPResponse(BaseHTTPResponse):
|
||||
"""
|
||||
HTTP response to be sent back to the client.
|
||||
|
||||
:param body: the body content to be returned
|
||||
:type body: Optional[bytes]
|
||||
:param status: HTTP response number. **Default=200**
|
||||
:type status: int
|
||||
:param headers: headers to be returned
|
||||
:type headers: Optional;
|
||||
:param content_type: content type to be returned (as a header)
|
||||
:type content_type: Optional[str]
|
||||
"""
|
||||
|
||||
__slots__ = ("body", "status", "content_type", "headers", "_cookies")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
body=None,
|
||||
status=200,
|
||||
headers=None,
|
||||
content_type=None,
|
||||
body_bytes=b"",
|
||||
body: Optional[AnyStr] = None,
|
||||
status: int = 200,
|
||||
headers: Optional[Union[Header, Dict[str, str]]] = None,
|
||||
content_type: Optional[str] = None,
|
||||
):
|
||||
self.content_type = content_type
|
||||
super().__init__()
|
||||
|
||||
if body is not None:
|
||||
self.content_type: Optional[str] = content_type
|
||||
self.body = self._encode_body(body)
|
||||
else:
|
||||
self.body = body_bytes
|
||||
|
||||
self.status = status
|
||||
self.headers = Header(headers or {})
|
||||
self._cookies = None
|
||||
|
||||
def output(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
|
||||
# This is all returned in a kind-of funky way
|
||||
# We tried to make this as fast as possible in pure python
|
||||
timeout_header = b""
|
||||
if keep_alive and keep_alive_timeout is not None:
|
||||
timeout_header = b"Keep-Alive: %d\r\n" % keep_alive_timeout
|
||||
|
||||
body = b""
|
||||
if has_message_body(self.status):
|
||||
body = self.body
|
||||
self.headers["Content-Length"] = self.headers.get(
|
||||
"Content-Length", len(self.body)
|
||||
)
|
||||
|
||||
# self.headers get priority over content_type
|
||||
if self.content_type and "Content-Type" not in self.headers:
|
||||
self.headers["Content-Type"] = self.content_type
|
||||
|
||||
if self.status in (304, 412):
|
||||
self.headers = remove_entity_headers(self.headers)
|
||||
|
||||
headers = self._parse_headers()
|
||||
|
||||
if self.status == 200:
|
||||
status = b"OK"
|
||||
else:
|
||||
status = STATUS_CODES.get(self.status, b"UNKNOWN RESPONSE")
|
||||
|
||||
return (
|
||||
b"HTTP/%b %d %b\r\n" b"Connection: %b\r\n" b"%b" b"%b\r\n" b"%b"
|
||||
) % (
|
||||
version.encode(),
|
||||
self.status,
|
||||
status,
|
||||
b"keep-alive" if keep_alive else b"close",
|
||||
timeout_header,
|
||||
headers,
|
||||
body,
|
||||
)
|
||||
|
||||
@property
|
||||
def cookies(self):
|
||||
if self._cookies is None:
|
||||
self._cookies = CookieJar(self.headers)
|
||||
return self._cookies
|
||||
|
||||
|
||||
def empty(
|
||||
status=204, headers=None,
|
||||
):
|
||||
status=204, headers: Optional[Dict[str, str]] = None
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Returns an empty response to the client.
|
||||
|
||||
:param status Response code.
|
||||
:param headers Custom Headers.
|
||||
"""
|
||||
return HTTPResponse(body_bytes=b"", status=status, headers=headers,)
|
||||
return HTTPResponse(body=b"", status=status, headers=headers)
|
||||
|
||||
|
||||
def json(
|
||||
body,
|
||||
status=200,
|
||||
headers=None,
|
||||
content_type="application/json",
|
||||
dumps=json_dumps,
|
||||
**kwargs
|
||||
):
|
||||
body: Any,
|
||||
status: int = 200,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
content_type: str = "application/json",
|
||||
dumps: Optional[Callable[..., str]] = None,
|
||||
**kwargs,
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Returns response object with body in json format.
|
||||
|
||||
@@ -230,6 +264,8 @@ def json(
|
||||
:param headers: Custom Headers.
|
||||
:param kwargs: Remaining arguments that are passed to the json encoder.
|
||||
"""
|
||||
if not dumps:
|
||||
dumps = BaseHTTPResponse._dumps
|
||||
return HTTPResponse(
|
||||
dumps(body, **kwargs),
|
||||
headers=headers,
|
||||
@@ -239,8 +275,11 @@ def json(
|
||||
|
||||
|
||||
def text(
|
||||
body, status=200, headers=None, content_type="text/plain; charset=utf-8"
|
||||
):
|
||||
body: str,
|
||||
status: int = 200,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
content_type: str = "text/plain; charset=utf-8",
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Returns response object with body in text format.
|
||||
|
||||
@@ -249,14 +288,22 @@ def text(
|
||||
:param headers: Custom Headers.
|
||||
:param content_type: the content type (string) of the response
|
||||
"""
|
||||
if not isinstance(body, str):
|
||||
raise TypeError(
|
||||
f"Bad body type. Expected str, got {type(body).__name__})"
|
||||
)
|
||||
|
||||
return HTTPResponse(
|
||||
body, status=status, headers=headers, content_type=content_type
|
||||
)
|
||||
|
||||
|
||||
def raw(
|
||||
body, status=200, headers=None, content_type="application/octet-stream"
|
||||
):
|
||||
body: Optional[AnyStr],
|
||||
status: int = 200,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
content_type: str = DEFAULT_HTTP_CONTENT_TYPE,
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Returns response object without encoding the body.
|
||||
|
||||
@@ -266,22 +313,32 @@ def raw(
|
||||
:param content_type: the content type (string) of the response.
|
||||
"""
|
||||
return HTTPResponse(
|
||||
body_bytes=body,
|
||||
body=body,
|
||||
status=status,
|
||||
headers=headers,
|
||||
content_type=content_type,
|
||||
)
|
||||
|
||||
|
||||
def html(body, status=200, headers=None):
|
||||
def html(
|
||||
body: Union[str, bytes, HTMLProtocol],
|
||||
status: int = 200,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Returns response object with body in html format.
|
||||
|
||||
:param body: Response data to be encoded.
|
||||
:param body: str or bytes-ish, or an object with __html__ or _repr_html_.
|
||||
:param status: Response code.
|
||||
:param headers: Custom Headers.
|
||||
"""
|
||||
return HTTPResponse(
|
||||
if not isinstance(body, (str, bytes)):
|
||||
if hasattr(body, "__html__"):
|
||||
body = body.__html__()
|
||||
elif hasattr(body, "_repr_html_"):
|
||||
body = body._repr_html_()
|
||||
|
||||
return HTTPResponse( # type: ignore
|
||||
body,
|
||||
status=status,
|
||||
headers=headers,
|
||||
@@ -290,13 +347,13 @@ def html(body, status=200, headers=None):
|
||||
|
||||
|
||||
async def file(
|
||||
location,
|
||||
status=200,
|
||||
mime_type=None,
|
||||
headers=None,
|
||||
filename=None,
|
||||
_range=None,
|
||||
):
|
||||
location: Union[str, PurePath],
|
||||
status: int = 200,
|
||||
mime_type: Optional[str] = None,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
filename: Optional[str] = None,
|
||||
_range: Optional[Range] = None,
|
||||
) -> HTTPResponse:
|
||||
"""Return a response object with file data.
|
||||
|
||||
:param location: Location of file on system.
|
||||
@@ -308,42 +365,40 @@ async def file(
|
||||
headers = headers or {}
|
||||
if filename:
|
||||
headers.setdefault(
|
||||
"Content-Disposition", 'attachment; filename="{}"'.format(filename)
|
||||
"Content-Disposition", f'attachment; filename="{filename}"'
|
||||
)
|
||||
filename = filename or path.split(location)[-1]
|
||||
|
||||
async with open_async(location, mode="rb") as _file:
|
||||
async with await open_async(location, mode="rb") as f:
|
||||
if _range:
|
||||
await _file.seek(_range.start)
|
||||
out_stream = await _file.read(_range.size)
|
||||
headers["Content-Range"] = "bytes %s-%s/%s" % (
|
||||
_range.start,
|
||||
_range.end,
|
||||
_range.total,
|
||||
)
|
||||
await f.seek(_range.start)
|
||||
out_stream = await f.read(_range.size)
|
||||
headers[
|
||||
"Content-Range"
|
||||
] = f"bytes {_range.start}-{_range.end}/{_range.total}"
|
||||
status = 206
|
||||
else:
|
||||
out_stream = await _file.read()
|
||||
out_stream = await f.read()
|
||||
|
||||
mime_type = mime_type or guess_type(filename)[0] or "text/plain"
|
||||
return HTTPResponse(
|
||||
body=out_stream,
|
||||
status=status,
|
||||
headers=headers,
|
||||
content_type=mime_type,
|
||||
body_bytes=out_stream,
|
||||
)
|
||||
|
||||
|
||||
async def file_stream(
|
||||
location,
|
||||
status=200,
|
||||
chunk_size=4096,
|
||||
mime_type=None,
|
||||
headers=None,
|
||||
filename=None,
|
||||
chunked=True,
|
||||
_range=None,
|
||||
):
|
||||
location: Union[str, PurePath],
|
||||
status: int = 200,
|
||||
chunk_size: int = 4096,
|
||||
mime_type: Optional[str] = None,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
filename: Optional[str] = None,
|
||||
chunked="deprecated",
|
||||
_range: Optional[Range] = None,
|
||||
) -> StreamingHTTPResponse:
|
||||
"""Return a streaming response object with file data.
|
||||
|
||||
:param location: Location of file on system.
|
||||
@@ -351,64 +406,62 @@ async def file_stream(
|
||||
:param mime_type: Specific mime_type.
|
||||
:param headers: Custom Headers.
|
||||
:param filename: Override filename.
|
||||
:param chunked: Enable or disable chunked transfer-encoding
|
||||
:param chunked: Deprecated
|
||||
:param _range:
|
||||
"""
|
||||
if chunked != "deprecated":
|
||||
warn(
|
||||
"The chunked argument has been deprecated and will be "
|
||||
"removed in v21.6"
|
||||
)
|
||||
|
||||
headers = headers or {}
|
||||
if filename:
|
||||
headers.setdefault(
|
||||
"Content-Disposition", 'attachment; filename="{}"'.format(filename)
|
||||
"Content-Disposition", f'attachment; filename="{filename}"'
|
||||
)
|
||||
filename = filename or path.split(location)[-1]
|
||||
mime_type = mime_type or guess_type(filename)[0] or "text/plain"
|
||||
if _range:
|
||||
start = _range.start
|
||||
end = _range.end
|
||||
total = _range.total
|
||||
|
||||
_file = await open_async(location, mode="rb")
|
||||
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
|
||||
status = 206
|
||||
|
||||
async def _streaming_fn(response):
|
||||
nonlocal _file, chunk_size
|
||||
try:
|
||||
async with await open_async(location, mode="rb") as f:
|
||||
if _range:
|
||||
chunk_size = min((_range.size, chunk_size))
|
||||
await _file.seek(_range.start)
|
||||
await f.seek(_range.start)
|
||||
to_send = _range.size
|
||||
while to_send > 0:
|
||||
content = await _file.read(chunk_size)
|
||||
content = await f.read(min((_range.size, chunk_size)))
|
||||
if len(content) < 1:
|
||||
break
|
||||
to_send -= len(content)
|
||||
await response.write(content)
|
||||
else:
|
||||
while True:
|
||||
content = await _file.read(chunk_size)
|
||||
content = await f.read(chunk_size)
|
||||
if len(content) < 1:
|
||||
break
|
||||
await response.write(content)
|
||||
finally:
|
||||
await _file.close()
|
||||
return # Returning from this fn closes the stream
|
||||
|
||||
mime_type = mime_type or guess_type(filename)[0] or "text/plain"
|
||||
if _range:
|
||||
headers["Content-Range"] = "bytes %s-%s/%s" % (
|
||||
_range.start,
|
||||
_range.end,
|
||||
_range.total,
|
||||
)
|
||||
status = 206
|
||||
return StreamingHTTPResponse(
|
||||
streaming_fn=_streaming_fn,
|
||||
status=status,
|
||||
headers=headers,
|
||||
content_type=mime_type,
|
||||
chunked=chunked,
|
||||
)
|
||||
|
||||
|
||||
def stream(
|
||||
streaming_fn,
|
||||
status=200,
|
||||
headers=None,
|
||||
content_type="text/plain; charset=utf-8",
|
||||
chunked=True,
|
||||
streaming_fn: StreamingFunction,
|
||||
status: int = 200,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
content_type: str = "text/plain; charset=utf-8",
|
||||
chunked="deprecated",
|
||||
):
|
||||
"""Accepts an coroutine `streaming_fn` which can be used to
|
||||
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
|
||||
@@ -427,27 +480,36 @@ def stream(
|
||||
writes content to that response.
|
||||
:param mime_type: Specific mime_type.
|
||||
:param headers: Custom Headers.
|
||||
:param chunked: Enable or disable chunked transfer-encoding
|
||||
:param chunked: Deprecated
|
||||
"""
|
||||
if chunked != "deprecated":
|
||||
warn(
|
||||
"The chunked argument has been deprecated and will be "
|
||||
"removed in v21.6"
|
||||
)
|
||||
|
||||
return StreamingHTTPResponse(
|
||||
streaming_fn,
|
||||
headers=headers,
|
||||
content_type=content_type,
|
||||
status=status,
|
||||
chunked=chunked,
|
||||
)
|
||||
|
||||
|
||||
def redirect(
|
||||
to, headers=None, status=302, content_type="text/html; charset=utf-8"
|
||||
):
|
||||
"""Abort execution and cause a 302 redirect (by default).
|
||||
to: str,
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
status: int = 302,
|
||||
content_type: str = "text/html; charset=utf-8",
|
||||
) -> HTTPResponse:
|
||||
"""
|
||||
Abort execution and cause a 302 redirect (by default) by setting a
|
||||
Location header.
|
||||
|
||||
:param to: path or fully qualified URL to redirect to
|
||||
:param headers: optional dict of headers to include in the new request
|
||||
:param status: status code (int) of the new request, defaults to 302
|
||||
:param content_type: the content type (string) of the response
|
||||
:returns: the redirecting Response
|
||||
"""
|
||||
headers = headers or {}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user