Compare commits

..

949 Commits

Author SHA1 Message Date
freddiewanah
a5a9658896
Refactor test cases to improve unit test quality (#2796)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-09-07 15:26:56 +03:00
Adam Hopkins
91d7e6a77d
Add PAAS files for webhook deployment 2023-09-07 10:20:10 +03:00
Theodore Ni
eb3d78f687
Fix test_fast when there's only one CPU (#2801)
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-09-06 21:26:28 +03:00
Adam Hopkins
d255d1aae1
Conversion of User Guide to the SHH stack (#2781) 2023-09-06 15:44:00 +03:00
Néstor Pérez
47215d4635
Run tests on push as well (#2814) 2023-08-30 20:03:22 +03:00
Adam Hopkins
38ff9069f3
Suppress task cancel traceback (#2812) 2023-08-30 09:05:37 +03:00
Néstor Pérez
4dde4572ec
Refactor GitHub Actions (#2808) 2023-08-29 21:47:40 +03:00
Néstor Pérez
31d14704cb
Update README (#2810) 2023-08-27 18:42:43 +03:00
Néstor Pérez
6a89f4b2fe
Add constraint for autodocsumm (#2807) 2023-08-23 20:47:23 +03:00
Adam Hopkins
16256522f6
Disable Test PyPI dist 2023-07-25 16:13:47 +03:00
Adam Hopkins
205795d1e8
Prepare for v23.6 release (#2797) 2023-07-25 15:57:29 +03:00
Adam Hopkins
9cbe1fb8ad
Add convenience method for exception reporting (#2792) 2023-07-18 00:21:55 +03:00
L. Kärkkäinen
31d7ba8f8c
Add request.client_ip (#2790)
Co-authored-by: L. Kärkkäinen <Tronic@users.noreply.github.com>
2023-07-13 23:01:02 +03:00
Adam Hopkins
dc3c4d1393
Add custom typing to config and ctx (#2785) 2023-07-12 23:47:58 +03:00
Adam Hopkins
929d270569
Update bug-report.yml (#2788) 2023-07-12 19:00:28 +03:00
Adam Hopkins
93714df051
Update bug-report.yml (#2787) 2023-07-12 18:53:14 +03:00
L. Kärkkäinen
6e61eab872
Increase KEEP_ALIVE_TIMEOUT default to 120 seconds (#2670)
Co-authored-by: L. Kärkkäinen <Tronic@users.noreply.github.com>
2023-07-12 08:45:30 +03:00
Adam Hopkins
6848ff24d8
Run keep alive tests in loop to get available port (#2779) 2023-07-09 22:58:17 +03:00
Adam Hopkins
666371bb92
Set multiprocessing start method early (#2776) 2023-07-09 22:34:15 +03:00
Adam Hopkins
4a2b82e42e
Remove Python3.7 support (#2777) 2023-07-09 22:00:14 +03:00
Moshe Nahmias
5dd1623192
Alow Blueprint routes to explicitly define error_format (#2773)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-09 14:47:59 +03:00
Adam Hopkins
976da69e79
Add a new exception signal for ALL exceptions raised anywhere in application (#2724) 2023-07-09 10:53:36 +03:00
Liam Coatman
11a0b15194
Handle case when headers argument of ResponseStream constructor is None (#2729)
* Handle case when headers is None

* Add test for response stream with default headers

* Move test

---------

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-09 10:34:40 +03:00
Adam Hopkins
c21999a248
Resolve headers on different renderers - Issue 2749 (#2774)
* Resolve headers on different renderers - Issue 2749

* Make pretty
2023-07-09 09:57:22 +03:00
guacs
c17230ef94
Update request type on middleware types (#2754)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-09 09:35:24 +03:00
Adam Hopkins
049983cb70
Fix traversals for intended results (#2728) 2023-07-09 09:21:39 +03:00
Zhiwei
e374409567
Adding allow route overwrite option in blueprint (#2716)
* Adding allow route overwrite option

* Add test case for route overwriting after bp copy

* Fix test

* Fix

* Add test case `test_bp_allow_override`

* Remove conflicted future routes when overwriting is allowed

* Improved test test_bp_copy_with_route_overwriting

* Fix type

* Fix type 2

* Add `test_bp_copy_without_route_overwriting` case

* make `allow_route_overwrite` flag to be internal

* Remove unwanted test case

---------

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-07 14:56:42 +03:00
Adam Hopkins
4068a0d83d
Add name prefixing to BP groups (#2727) 2023-07-05 19:31:25 +03:00
Benjamin
70da5e9879
Fix Inner bug: TypeError: __init__() got an unexpected keyword argument 'escape_forward_slashes' #2740 (#2772) 2023-07-05 15:30:38 +03:00
Moshe Nahmias
f48506d620
fix #2757 - Improved error messaging on startup time application induced import error (#2770)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-05 14:38:15 +03:00
Mohammad Almoghrabi
f2cc83c1ba
fix examples for freeze_support() issue on windows (#2741)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-05 13:45:08 +03:00
Mohammad Almoghrabi
273825dab6
Sanic on pypy (#2682)
Co-authored-by: L. Kärkkäinen <98187+Tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-07-05 12:14:47 +03:00
Zhiwei
9a7dafd531
Unpin setuptools version (#2766) 2023-07-05 11:06:43 +03:00
Thirumalaisamy K
50117d174c
Fix issue in getting current request through classmethod when served through a different ASGI server (#2760) 2023-06-14 22:03:43 +03:00
Néstor Pérez
af67801062
Fix JSONResponse default content type (#2737) 2023-04-09 22:23:21 +03:00
Adam Hopkins
6eaab2a7e5
Release 23.3 (#2723) 2023-03-26 22:54:28 +03:00
Adam Hopkins
d680af3709
v23.3 Deprecation Removal (#2717) 2023-03-26 15:24:08 +03:00
Adam Hopkins
a8c2d77c91
Sync state tolerance (#2725) 2023-03-26 08:39:59 +03:00
Adam Hopkins
6e1c787e5d
Simpler CLI targets (#2700)
Co-authored-by: L. Kärkkäinen <98187+Tronic@users.noreply.github.com>
2023-03-21 20:50:25 +02:00
L. Kärkkäinen
932088e37e
Stricter charset handling and escaping of request URLs (#2710)
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
2023-03-21 19:55:21 +02:00
Adam Hopkins
1a63b9bec0
Add convenience methods for cookie creation and deletion (#2706)
* Add convenience methods for cookie creation and deletion

* Restore del

* Backwards compat, forward thinking

* Add delitem deprecation notice

* Add get full deprecation notice

* Add deprecation docstring

* Better deprecation docstring

* Add has_cookie

* Same defaults

* Better deprecation message

* Accessor annotations

* make pretty

* parse cookies

* Revert quote translator

* make pretty

* make pretty

* Add unit tests

* Make pretty

* Fix unit tests

* Directly include unquote

* Add some more unit tests

* Move modules into their own dir

* make pretty

* cleanup test imports

* Add test for cookie accessor

* Make test consistent

* Remove file

* Remove additional escaping

* Add header style getattr for hyphens

* Add test for cookie accessor with hyphens

* Add new translator

* Parametrize test_request_with_duplicate_cookie_key

* make pretty

* Add deprecation of direct cookie encoding

* Speedup Cookie creation

* Implement prefixes on delete_cookie

* typing changes

* Add passthru functions on response objects for setting cookies

* Add test for passthru

---------

Co-authored-by: L. Kärkkäinen <98187+Tronic@users.noreply.github.com>
2023-03-21 11:25:35 +02:00
Zhiwei
61aa16f6ac
Decode headers as UTF-8 also in ASGI (#2606)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-03-20 15:39:57 +02:00
Adam Hopkins
71cd53b64e
Standardize init of exceptions (#2545) 2023-03-20 14:50:50 +02:00
Adam Hopkins
89188f5fc6
Add CertLoader as application option (#2722) 2023-03-20 14:05:21 +02:00
Adam Hopkins
a245ab3773
Change logging format to %s (#2721) 2023-03-20 13:25:06 +02:00
Adam Hopkins
ac1f56118a
Skip middleware on RequestCancelled (#2720) 2023-03-20 13:00:34 +02:00
Adam Hopkins
53820bc241
Allow password to be passed to TLS context (#2719) 2023-03-20 12:34:36 +02:00
stricaud
009954003c
Fix comparison from wrong formats with datetime objects (#2697)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-03-20 12:12:09 +02:00
Adam Hopkins
8f265b8169
Add convenience for dynamic changes to routing (#2704) 2023-03-19 15:40:58 +02:00
Adam Hopkins
5ee36fd933
Separate ASGI request and lifespan callables (#2646) 2023-03-17 09:05:33 +02:00
Matt Bendiksen
08a81c81be
scheme arg to create the redirect should be 'https' (#2712) 2023-03-16 12:13:17 +02:00
Adam Hopkins
5a0ed75171
Consume body on DELETE by default (#2711) 2023-03-15 18:42:45 +02:00
Adam Hopkins
d62a92fac9
API to define a number of workers (#2701) 2023-03-15 16:02:17 +02:00
Adam Hopkins
88c918e72f
Update rfc.yml 2023-03-09 10:10:22 +02:00
Adam Hopkins
c8aab8fb3d
Update rfc.yml 2023-03-09 10:09:30 +02:00
Adam Hopkins
ecacfd396b
Rename rfc to rfc.yml 2023-03-09 10:06:42 +02:00
Adam Hopkins
3c361e9852
Create rfc 2023-03-09 10:05:06 +02:00
L. Kärkkäinen
a5d7d03413
Nicer traceback formatting (#2667)
Co-authored-by: L. Kärkkäinen <98187+Tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
Co-authored-by: SML <smlbiobot@gmail.com>
2023-03-06 21:24:12 +02:00
L. Kärkkäinen
259e458847
Simplified parse_content_header escaping (#2707) 2023-03-06 06:39:16 +02:00
Adam Hopkins
cb49c2b26d
Add header accessors (#2696) 2023-02-28 00:26:53 +02:00
L. Kärkkäinen
dfc0704831
Error page rendering format selection (#2668)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
2023-02-26 08:25:10 +02:00
Adam Hopkins
d238995f1b
Refresh Request.accept functionality (#2687) 2023-02-21 08:22:51 +02:00
Mohammad Almoghrabi
6f5303e080
check the status of socket before shutting down (#2680)
* check the status of socket before shutting down

* remove socket status checking & ignore OSError exception
2023-02-14 22:59:41 +02:00
Ryu Juheon
5e7f6998bd
fix(websocket): ASGI websocket must pass thru bytes as is (#2651) 2023-02-05 16:41:54 +02:00
L. Kärkkäinen
c7a71cd00c
Use FALLBACK_ERROR_FORMAT for handlers that return empty() (#2659)
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2023-02-05 15:29:01 +02:00
Adam Hopkins
9cb9e88678
Establish basic file browser and index fallback (#2662)
Co-authored-by: L. Kärkkäinen <98187+Tronic@users.noreply.github.com>
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
2023-02-05 15:09:04 +02:00
Rodolfo Olivieri
30c53b6857
Remove deprecated property in blueprint (#2666)
Fixes https://github.com/sanic-org/sanic/issues/2442
2023-01-30 09:26:55 +02:00
Adam Hopkins
4ad8168bb0
Version 22.12 release notes (#2637) 2022-12-27 16:50:36 +02:00
Adam Hopkins
28f5b3c301
Add better inspector arg parsing (#2642) 2022-12-26 12:27:40 +02:00
Adam Hopkins
c573019e7f
ASGI websocket recv text or bytes (#2640) 2022-12-25 13:52:07 +02:00
Adam Hopkins
029f564032
Pass unquote thru add_route (#2639) 2022-12-21 10:45:23 +02:00
Adam Hopkins
2abe66b670
Add priority to register_middleware method (#2636) 2022-12-19 19:14:46 +02:00
Adam Hopkins
911485d52e
Fix Windows sock share (#2635) 2022-12-18 15:04:10 +02:00
Adam Hopkins
4744a89c33
Fix double ctrl-c kill (#2634) 2022-12-18 14:40:38 +02:00
Adam Hopkins
f7040ccec8
Implement restart ordering (#2632) 2022-12-18 14:09:17 +02:00
Adam Hopkins
518152d97e
Reload interval on class variable (#2633) 2022-12-18 13:36:54 +02:00
Adam Hopkins
0e44e9cacb
Move to HTTP Inspector (#2626) 2022-12-18 10:29:58 +02:00
Adam Hopkins
bfb54b0969
Test for 3.11 support (#2612)
Co-authored-by: Zhiwei <zhi.wei.liang@outlook.com>
2022-12-17 23:46:22 +02:00
Zhiwei
154863d6c6
Method Signal Handler Test (#2630) 2022-12-17 20:38:46 +02:00
Adam Hopkins
a3ff0c13b7
ASGI lifespan failure on exception (#2627) 2022-12-16 08:56:07 +02:00
Mary
95ee518aec
Replace deprecated distutils.strtobool (#2628) 2022-12-16 07:48:41 +02:00
Zhiwei
71d3d87bcc
Deprecate Conditions and Triggers Saved in handler Callable; Save Condition in signal.extra Instead (#2608) 2022-12-15 12:32:07 +02:00
Adam Hopkins
b276b91c21
Allow fork in limited cases (#2624) 2022-12-15 11:49:26 +02:00
Adam Hopkins
064168f3c8
Add a SIGKILL to second ctrl+c (#2621) 2022-12-14 23:51:11 +02:00
Adam Hopkins
db39e127bf
Scale workers (#2617) 2022-12-13 09:28:23 +02:00
L. Kärkkäinen
13e9ab7ba9
Filename normalisation of form-data/multipart file uploads (umlauts on Apple clients) (#2625)
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
2022-12-13 08:36:21 +02:00
Adam Hopkins
92e7463721
Add a restart mechanism to all workers in the multiplexer (#2622) 2022-12-11 11:33:42 +02:00
Néstor Pérez
8e720365c2
Add JSONResponse class (#2569)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-12-11 10:37:45 +02:00
Adam Hopkins
d4041161c7
Ensure middleware executes once per request timeout (#2615) 2022-12-07 23:07:17 +02:00
Adam Hopkins
f32437bf13
Kill server early on worker error (#2610) 2022-12-07 14:42:17 +02:00
LiraNuna
0909e94527
Corrected Colors enum under Python 3.11 (#2590)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Fixes https://github.com/sanic-org/sanic/issues/2589
2022-11-29 12:17:48 +02:00
Adam Hopkins
aef2673c38
Force socket shutdown before close (#2607)
Co-authored-by: Zhiwei <zhi.wei.liang@outlook.com>
2022-11-29 12:04:22 +02:00
Aymeric Augustin
4c14910d5b
Add compatibility with websockets 11.0. (#2609)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-11-29 11:45:18 +02:00
Adam Hopkins
beae35f921
Ignore recent failures on bad TLS tests (#2611) 2022-11-29 10:51:51 +02:00
Zhiwei
ad4e526c77
Require uvloop >= 0.15.0 (#2598) 2022-11-13 15:32:04 +02:00
Adam Hopkins
4422d0c34d
Mergeback from current-release 2022-10-31 13:24:47 +02:00
Adam Hopkins
ad9183d21d
Merge branch 'main' of github.com:sanic-org/sanic into current-release 2022-10-31 13:22:47 +02:00
Adam Hopkins
d70636ba2e
Add GenericCreator for loading SSL certs in processes (#2578) 2022-10-31 13:22:30 +02:00
Adam Hopkins
da23f85675
Set version 2022-10-31 13:20:17 +02:00
Adam Hopkins
3f4663b9f8
Resolve edge case in nested BP Groups (#2592) 2022-10-31 12:58:41 +02:00
Adam Hopkins
65d7447cf6
Add interval sleep in reloader (#2595) 2022-10-31 12:34:01 +02:00
Adam Hopkins
5369291c27
22.9 Docs (#2556) 2022-10-31 11:47:23 +02:00
Ryu Juheon
1c4925edf7
fix: sideeffects created by changing fork to spawn (#2591) 2022-10-27 20:39:17 +03:00
Santi Cardozo
6b9edfd05c
improve error message if no apps found in registry (#2585) 2022-10-25 16:54:44 +03:00
Adam Hopkins
97f33f42df
Update SECURITY.md 2022-10-25 13:05:13 +03:00
Adam Hopkins
15a588a90c
Upgrade markdown templates to issue forms (#2588) 2022-10-25 13:04:11 +03:00
Ryu Juheon
82421e7efc
docs: sanic now supports windows. (#2582) 2022-10-21 14:31:22 +03:00
Adam Hopkins
f891995b48
Start v22.12 2022-09-29 13:04:46 +03:00
Adam Hopkins
5052321801
Remove deprecated items (#2555) 2022-09-29 01:07:09 +03:00
Adam Hopkins
23ce4eaaa4
Merge branch 'main' of github.com:sanic-org/sanic 2022-09-23 00:16:27 +03:00
Adam Hopkins
23a430c4ad
Set version properly 2022-09-23 00:16:10 +03:00
Adam Hopkins
ec158ffa69
Additional logger and support for multiprocess manager (#2551) 2022-09-23 00:01:33 +03:00
Adam Hopkins
6e32270036
Begin middleware revamp (#2550) 2022-09-22 00:43:42 +03:00
Zhiwei
43ba381e7b
Refactor _static_request_handler (#2533)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-09-21 00:45:03 +03:00
Zhiwei
16503319e5
Make WebsocketImplProtocol async iterable (#2490) 2022-09-21 00:20:32 +03:00
Adam Hopkins
389363ab71
Better request cancel handling (#2513) 2022-09-19 16:04:09 +03:00
Adam Hopkins
7f894c45b3
Add deprecation warning filter (#2546) 2022-09-18 18:54:35 +03:00
Adam Hopkins
4726cf1910
Sanic Server WorkerManager refactor (#2499)
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
2022-09-18 17:17:23 +03:00
Adam Hopkins
d352a4155e
Add signals before and after handler execution (#2540) 2022-09-15 15:49:21 +03:00
Adam Hopkins
e5010286b4
Raise warning and deprecation notice on violations (#2537) 2022-09-15 15:24:46 +03:00
Adam Hopkins
358498db96
Do not apply double slash to Blueprint and static dirs (#2515) 2022-09-15 14:43:20 +03:00
monosans
e4999401ab
Improve and fix some type annotations (#2536) 2022-09-13 08:53:48 +03:00
Néstor Pérez
c8df0aa2cb
Fix easter egg through CLI (#2542) 2022-09-12 01:44:21 +03:00
Adam Hopkins
5fb207176b
Update bug_report.md 2022-08-29 12:47:01 +03:00
Adam Hopkins
a12b560478
Update feature_request.md 2022-08-29 12:46:39 +03:00
Zhiwei
753ee992a6
Validate File When Requested (#2526)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-08-18 12:05:05 +03:00
Hunt Zhan
09089b1bd3
Resolve issue 2529 (#2530) 2022-08-18 08:58:07 +03:00
Adam Hopkins
7ddbe5e844
Update config.yml 2022-08-17 10:44:02 +03:00
Adam Hopkins
ab5a7038af
Update SECURITY.md 2022-08-17 10:42:22 +03:00
Adam Hopkins
4f3c780dc3
Update feature_request.md 2022-08-17 10:38:15 +03:00
Adam Hopkins
71f7765a4c
Update bug_report.md 2022-08-17 10:37:35 +03:00
Adam Hopkins
0392d1dcfc
Always show server location in ASGI (#2522)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Zhiwei Liang <zhi.wei.liang@outlook.com>
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
2022-08-11 10:00:35 +03:00
Adam Hopkins
7827b1b41d
Add Request properties for HTTP method info (#2516) 2022-08-10 21:12:09 +03:00
Adam Hopkins
8e9342e188
Warn on duplicate route names (#2525) 2022-08-10 20:36:47 +03:00
Adam Hopkins
2f6f2bfa76
Rename code of conduct 2022-08-02 13:56:53 +03:00
Ryu Juheon
dee09d7fff
style: add some type hints (#2517) 2022-08-02 08:47:59 +03:00
Adam Hopkins
9cf38a0a83
MERGEBACK (#2495) (#2512)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Zhiwei Liang <zhi.wei.liang@outlook.com>
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
2022-07-31 15:50:46 +03:00
Adam Hopkins
3def3d3569
Use path.parts instead of match (#2508) 2022-07-31 12:54:42 +03:00
Adam Hopkins
e100a14fd4
Use pathlib for path resolution (#2506) 2022-07-31 08:49:02 +03:00
Adam Hopkins
2fa28f1711
Fix dotted test 2022-07-28 10:07:30 +03:00
Néstor Pérez
9d415e4ec6
Prevent directory traversion with static files (#2495)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Zhiwei Liang <zhi.wei.liang@outlook.com>
2022-07-28 09:45:45 +03:00
Tim Gates
312ab298fd
docs: Fix a few typos (#2502)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-07-24 22:47:39 +03:00
Zhiwei
2fc21ad576
Replace Unsupported Python Version Number from the Contributing Doc (#2505)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-07-24 22:33:05 +03:00
Zhiwei
8f6c87c3d6
Fix Test Cases: test_http for Py3.9+, test_json_response_json for ujson 5.4.0+, and test_zero_downtime; Test Case Type Annotations (#2504) 2022-07-24 22:07:54 +03:00
Adam Hopkins
4429e76532
Add to changelog 2022-06-30 12:52:27 +03:00
Michael Azimov
e4be70bae8
Add custom loads function (#2445)
Co-authored-by: Zhiwei <chihwei.public@outlook.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-06-29 23:39:21 +03:00
Adam Hopkins
13d5a44278
Release 22.6 (#2487) 2022-06-28 15:25:46 +03:00
Adam Hopkins
aba333bfb6
Improve API docs (#2488) 2022-06-28 10:53:03 +03:00
Adam Hopkins
b59da498cc
HTTP/3 Support (#2378) 2022-06-27 11:19:26 +03:00
Zhiwei
70382f21ba
Fix and improve file cache control header calculation (#2486) 2022-06-26 23:11:48 +03:00
Néstor Pérez
0e1bf89fad
Add missing spaces in CLI error message (#2485) 2022-06-26 10:38:35 +03:00
Aidan Timson
6c48c8b3ba
Fix for running in pythonw (#2448)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-06-19 14:48:06 +03:00
Zhiwei
d1c5e8003b
Fix test_cli and test_cookies (#2479) 2022-06-19 04:43:12 +03:00
Adam Hopkins
ce926a34f2
Add Request contextvars (#2475)
* Add Request contextvars

* Add missing contextvar setter

* Move location of context setter
2022-06-16 22:57:02 +03:00
Zhiwei
a744041e38
File Cache Control Headers Support (#2447)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-06-16 16:24:39 +03:00
Mary
2f90a85df1
feat(type): extend (#2466)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-06-16 15:38:13 +03:00
Adam Hopkins
a411bc06e3
Resolve typing of stacked route definitions (#2455) 2022-06-16 15:15:20 +03:00
Adam Hopkins
1668e1532f
Move verbosity filtering to logger (#2453) 2022-06-16 12:35:49 +03:00
Vetési Zoltán
b87982769f
Trigger http.lifecycle.request signal in ASGI mode (#2451)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-06-16 11:55:50 +03:00
Ryu Juheon
65b53a5f3f
style: add msg in `task.cancel` (#2416)
* style: add msg in ``task.cancel``

* style: apply isort

* fix: use else statement

* fix: use tuple

* fix: rollback for test

* fix: rollback like previous change

* fix: add ``=``

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-06-16 10:55:20 +03:00
Zhiwei
49789b7841
Clean Up Black and Isort Config (#2449)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-05-26 12:48:32 +03:00
Amitay
c249004c30
fixed manual to match current Sanic app name policy (#2461)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-05-26 10:16:24 +03:00
Ashley Sommer
4ee2e57ec8
Properly catch websocket CancelledError in websocket handler in Python 3.7 (#2463) 2022-05-23 22:47:05 +03:00
Néstor Pérez
86ae5f981c
refactor: consistent exception naming (#2420)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-05-12 20:39:35 +03:00
Adam Hopkins
2bfa65e0de
Current release mergeback (#2454) 2022-05-11 09:37:33 +03:00
Adam Hopkins
293278bb08
Resolve warning issue with error handler mismatch warning (#2452) 2022-05-11 09:36:05 +03:00
Michael Azimov
5d683c6ea4
Expose scope parameter in request object (#2432)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-04-26 17:25:29 +03:00
Stephen Sadowski
78b6723149
Preserve blank form values for urlencoded forms (option) (#2439)
* task(request.form): Add tests for blank values

* fix(request): abstract form property to implement get_form(), allow for preserving of blanks

* fix(request): hinting for parsed_form

* fix(request): typing for parsed_files

* fix(request): ignore type assumption

* fix(request): mypy typechecking caused E501 when type set to ignore

* fix(request): mypy is too stupid to parse continuations

* fix(request): formatting

* fix(request): fix annotation and return for get_form()

* fix(request): linting, hinting
2022-04-24 23:01:35 +03:00
Ryu juheon
3a6cc7389c
feat: easier websocket interface annotation (#2438) 2022-04-24 13:32:13 +03:00
Adam Hopkins
cc97287f8e
Add fall back for Windows even loop fetching (#2421) 2022-04-17 12:25:41 +03:00
Adam Hopkins
00218aa9f2
22.3 Internal version bumps (#2419) 2022-03-31 14:30:30 +03:00
Adam Hopkins
874718db94
Bump version and 22.3 changelog (#2418) 2022-03-30 15:09:45 +03:00
Javier Marcet
bb4474897f
Fix "DeprecationWarning: There is no current event loop" (#2390)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-30 09:40:30 +03:00
Adam Hopkins
0cb342aef4
Better exception for bad URL parse (#2415) 2022-03-25 00:22:12 +02:00
Ashley Sommer
030987480c
Add config option to skip Touchup step, for debugging purposes (#2361)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-24 13:52:05 +02:00
Robert Schütz
f6fdc80b40
allow multidict version 6 (#2396)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-24 00:38:45 +02:00
Jonathan Vargas
361c242473
remove error_logger on websockets (#2373)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-23 16:25:19 +02:00
André Ericson
32962d1e1c
Fixing typing for ListenerMixin.listener (#2376)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-23 15:34:33 +02:00
Adam Hopkins
6e0a6871b5
Upgrade tests for sanic-routing changes (#2405) 2022-03-23 13:43:36 +02:00
Adam Hopkins
0030425c8c
Conditionally inject CLI arguments into factory (#2402) 2022-03-23 12:00:41 +02:00
Adam Hopkins
c9dbc8ed26
Remove loop as required listener arg (#2414) 2022-03-23 11:02:39 +02:00
Callum
44b108b564
Changes to CLI (#2401)
Co-authored-by: Callum Fleming <howzitcal@zohomail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-23 10:30:41 +02:00
Adam Hopkins
2a8e91052f
Add two new events on the reloader process (#2413) 2022-03-22 23:29:39 +02:00
Bluenix
0c9df02e66
Add a docstring to Request.respond() (#2409)
Co-authored-by: Ryu juheon <saidbysolo@gmail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2022-03-14 13:10:49 +02:00
Arie Bovenberg
7523e87937
remove overlapping slots from app.Sanic, fix broken slots inherit of HTTPResponse (#2387) 2022-02-24 17:45:23 +02:00
Bluenix
d4fb44e986
Document middleware on_request and on_response (#2398) 2022-02-13 21:08:08 +02:00
Ryu juheon
68b654d981
fix(tasks): newly assigned `None` in registry (#2381) 2022-02-08 08:33:09 +02:00
Adam Hopkins
88bc6d8966
Upgrade black and isort changes (#2397) 2022-02-02 10:41:55 +02:00
Adam Hopkins
ac388d644b
Downgrade warnings to backwater debug messages (#2382) 2022-01-19 14:26:45 +02:00
Ryu juheon
bb517ddcca
fix: deprecation warning in `asyncio.wait` (#2383) 2022-01-19 08:09:17 +02:00
Adam Hopkins
b8d991420b
Sanic multi-application server (#2347) 2022-01-16 09:03:04 +02:00
Adam Hopkins
4a416e177a
Updates to CLI help messaging (#2372) 2022-01-14 00:54:51 +02:00
Adam Hopkins
8dfa49b648
22.3 Deprecations and changes (#2362) 2022-01-12 16:28:43 +02:00
Adam Hopkins
8b0eaa097c
Change back to codecov (#2363) 2022-01-09 12:22:09 +02:00
Sergey Rybakov
101151b419
Add credentials property to Request objects (#2357) 2022-01-06 19:14:52 +02:00
Adam Hopkins
4669036f45
Mergeback of 21.12.1 (#2358)
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
Co-authored-by: Ryu juheon <saidbysolo@gmail.com>
2022-01-06 12:40:52 +02:00
raphaelauv
9bf9067c99
[FIX] README ASGI link (#2350) 2022-01-04 06:39:59 +02:00
Adam Hopkins
a7bc8b56ba
Set dev version 2021-12-26 22:19:39 +02:00
Zhiwei
371985d129
deprecation warning for not catch lowercase env var (#2344) 2021-12-26 21:47:15 +02:00
Adam Hopkins
3eae00898d
Set setuptools version for RTD 2021-12-26 14:25:09 +02:00
Adam Hopkins
dc3ccba527
Auto extend with Sanic Extensions (#2308) 2021-12-25 22:20:06 +02:00
Adam Hopkins
b91ffed010
Change signal routing for increased consistency (#2277) 2021-12-24 01:27:54 +02:00
Adam Hopkins
8c07e388cd
LTS v21.12 Deprecations (#2306)
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
2021-12-24 00:30:27 +02:00
Néstor Pérez
98ce4bdeb2
Optional uvloop use (#2264)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-12-23 11:57:33 +02:00
Adam Hopkins
4659069350
Add route context (#2302) 2021-12-21 22:56:12 +02:00
Adam Hopkins
080d41627a
Env custom type casting (#2330) 2021-12-21 00:50:45 +02:00
Adam Hopkins
d799c5f03c
Add named tasks (#2304) 2021-12-20 23:50:04 +02:00
Adam Hopkins
abe062b371
Remove app instance from Config for error handler setting (#2320) 2021-12-18 18:58:14 +02:00
Zhiwei
b5a00ac1ca
Add Py310 Tests Badge to README (#2341) 2021-12-15 13:09:13 +02:00
Adam Hopkins
f282865362
Cleanup ports on tests (#2338) 2021-12-13 19:48:30 +02:00
Adam Hopkins
377c2ada38
Remove paths from coverage checks (#2336) 2021-12-13 15:03:51 +02:00
Adam Hopkins
264453459e
Add runtime checking to create_server to verify that startup has been run (#2328) 2021-12-13 09:36:41 +02:00
Adam Hopkins
3d383d7b97
Update README.rst 2021-12-12 13:58:34 +02:00
Adam Hopkins
c0cc26021b
Allow underscore to start instance names (#2335) 2021-12-10 00:04:34 +02:00
Zhiwei
96c027bad5
Prevent sending multiple or mixed responses on a single request (#2327)
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-12-09 12:00:18 +02:00
Adam Hopkins
b2a1bc69f5
Make warnings for DeprecationWarning consistent (#2332) 2021-12-08 21:01:28 +02:00
Zhiwei
426742b3e2
Fix Sanic.handle_exception Method's Type Doc (#2333)
* Fix type doc

* Remove explicit type defines in docstring
2021-12-07 12:10:04 +02:00
Kian Meng Ang
ab35121864
Fix typos (#2329)
* Fix typos

* Downgrade mistune version

* Fix blueprint host param

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-12-06 09:17:01 +02:00
Zhiwei
cf3c205fa5
Fixed: CI Runs on Ready PRs Only (#2324)
* Revert "Update tests to not run all the time (#2311)"

This reverts commit 2c03eee329.

* Make CI only runs on PRs that are ready

* Remove CI Tasks on Push
2021-12-06 00:05:07 +02:00
Adam Hopkins
19f6544923
Resolve potential bug in MOTD in Docker (#2331)
* Resolve potential bug in MOTD in Docker
2021-12-03 13:27:16 +02:00
Clay Sweetser
f641830d26
Refactor environment variable hydration logic. (#2321)
- Refactor environment variable hydration logic to be less nested. This allows possible future extension of the hydration logic.
- Fix a spelling mistake in `load_environment_vars` docstring.

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-12-03 00:01:20 +02:00
Zhiwei
a8d55e180c
Fix Type Hint (#2322)
* Fix Type Hint

Union is not necessary here? My IDE pops an error for it.

* Rerun workflows

* empty commit
2021-12-02 23:17:22 +02:00
Adam Hopkins
55c36e0240
Fix examples to work as expected (#2305)
* Fix examples to work as expected

* Clean up examples

* Update worker test

* Merge in from main and cleanup example
2021-11-23 23:00:25 +02:00
Adam Hopkins
2c03eee329
Update tests to not run all the time (#2311) 2021-11-23 15:53:46 +02:00
Adam Hopkins
65e28b8c22
Mergeback (#2319)
* Mergeback
2021-11-21 15:13:34 +02:00
Adam Hopkins
dfd33dd63d
Update README.rst 2021-11-21 10:27:23 +02:00
Hussein Mohamed
722a6db8d9
Dispatch http.lifecyle.response from exception handler (#2299) 2021-11-19 08:50:02 +02:00
Xavier Petit
9c576c74db
Fix typehints in route shorthand methods (#2317)
* Fix typehints in route shorthand methods

Change typehint of the version variable in RouteMixin  to allow int string and float types values
Resolves #2314

* fix lint error in version variable
2021-11-19 08:28:05 +02:00
Adam Hopkins
523db190a7
Add contextual exceptions (#2290) 2021-11-18 17:47:27 +02:00
Adam Hopkins
95631b9686
Coffee please (#2316)
* Coffee please

* Add unit tests
2021-11-18 14:53:06 +02:00
Adam Hopkins
0860bfe1f1
Merge release 21.9.2 (#2313) 2021-11-17 19:36:36 +02:00
Adam Hopkins
85e7b712b9
Allow early Blueprint registrations to still apply later added objects (#2260) 2021-11-17 17:29:41 +02:00
L. Kärkkäinen
b731a6b48c
Make HTTP connections start in IDLE stage, avoiding delays and error messages (#2268)
* Make all new connections start in IDLE stage, and switch to REQUEST stage only once any bytes are received from client. This makes new connections without any request obey keepalive timeout rather than request timeout like they currently do.

* Revert typo

* Remove request timeout endpoint test which is no longer working (still tested by mocking). Fix mock timeout test setup.

Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
2021-11-16 23:03:27 +02:00
Adam Hopkins
cde02b5936
More consistent config setting with post-FALLBACK_ERROR_FORMAT apply (#2310)
* Update unit testing and add more consistent config

* Change init and app values to private

* Cleanup line lengths
2021-11-16 13:07:33 +02:00
Adam Hopkins
abeb8d0bc0
Provide list of reloaded files (#2307)
* Allow access to reloaded files

* Return to simple boolean values

* Resolve before adding to changed files
2021-11-16 10:16:32 +02:00
Adam Hopkins
9a9f72ad64
Move builtin signals to enum (#2309)
* Move builtin signals to enum

* Fix annotations
2021-11-14 23:21:14 +02:00
Adam Hopkins
392a497366
Restructure of CLI and application state (#2295)
* Initial work on restructure of application state

* Updated MOTD with more flexible input and add basic version

* Remove unnecessary type ignores

* Add wrapping and smarter output per process type

* Add support for ASGI MOTD

* Add Windows color support ernable

* Refactor __main__ into submodule

* Renest arguments

* Passing unit tests

* Passing unit tests

* Typing

* Fix num worker test

* Add context to assert failure

* Add some type annotations

* Some linting

* Line aware searching in test

* Test abstractions

* Fix some flappy tests

* Bump up timeout on CLI tests

* Change test for no access logs on gunicornworker

* Add some basic test converage

* Some new tests, and disallow workers and fast on app.run
2021-11-07 21:39:03 +02:00
Adam Hopkins
36e6a6c506
Increase join concat performance (#2291) 2021-10-29 12:55:09 +03:00
Stephen Sadowski
a361b345ad
Py310 loop fixup (#2294)
* Fixup for 3.8+; Sanic still supports 3.7 where loop is required

* Added branching statement to hanle asyncio.Event() loop parameter removal in 3.10, and optional supply in 3.9
2021-10-28 17:16:23 -05:00
Adam Hopkins
f5bd6e3b2f
Add Python 3.10 testing (and support) (#2257)
Administratively merging because @vltr and @ahopkins are the release managers, and @ahopkins is originator of the PR

* Add Python 3.10 testing (and support)

* fixed py310 tox environment for windows, quoted '3.10' in python-310 tests to avoid numeric compression

* updated tox.ini for py310

* quoted the rest of the bare 3.10 references in the workflows

* Issue with pytest requires version bump to 6.2.5 for python 3.10

Co-authored-by: Stephen Sadowski <stephen.sadowski@sjsadowski.com>
2021-10-28 13:41:57 -05:00
L. Kärkkäinen
6c7df68c7c
Vhost support using multiple TLS certificates (#2270)
* Initial support for using multiple SSL certificates.

* Also list IP address subjectAltNames on log.

* Use Python 3.7+ way of specifying TLSv1.2 as the minimum version. Linter fixes.

* isort

* Cleanup, store server name for later use. Add RSA ciphers. Log rejected SNIs.

* Cleanup, linter.

* Alter the order of initial log messages and handling. In particular, enable debug mode early so that debug messages during init can be shown.

* Store server name (SNI) to conn_info.

* Update test with new error message.

* Refactor for readability.

* Cleanup

* Replace old expired test cert with new ones and a script for regenerating them as needed.

* Refactor TLS tests to a separate file.

* Add cryptography to dev deps for rebuilding TLS certs.

* Minor adjustment to messages.

* Tests added for new TLS code.

* Find the correct log row before testing for message. The order was different on CI.

* More log message order fixup. The tests do not account for the logo being printed first.

* Another attempt at log message indexing fixup.

* Major TLS refactoring.

CertSelector now allows dicts and SSLContext within its list.
Server names are stored even when no list is used.
SSLContext.sanic now contains a dict with any setting passed and information extracted from cert.
That information is available on request.conn_info.cert.
Type annotations added.
More tests incl. a handler for faking hostname in tests.

* Remove a problematic logger test that apparently was not adding any coverage or value to anything.

* Revert accidental commit of uvloop disable.

* Typing fixes / refactoring.

* Additional test for cert selection. Certs recreated without DNS:localhost on sanic.example cert.

* Add tests for single certificate path shorthand and SNI information.

* Move TLS dict processing to CertSimple, make the names field optional and use names from the cert if absent.

* Sanic CLI options --tls and --tls-strict-host to use the new features.

* SSL argument typing updated

* Use ValueError for internal message passing to avoid CertificateError's odd message formatting.

* Linter

* Test CLI TLS options.

* Maybe the right codeclimate option now...

* Improved TLS argument help, removed support for combining --cert/--key with --tls.

* Removed support for strict checking without any certs, black forced fscked up formatting.

* Update CLI tests for stricter TLS options.

Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-10-28 16:50:05 +03:00
Meysam
5b82884f8b
ci: fail on error 👷 (#2292)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-10-27 11:55:34 +03:00
Néstor Pérez
f0f81ec458
Add ability to log all exceptions (#2262)
* Add ability to log all exceptions

* Fix linting 🙄

* Remove shorthand

* Make `ErrorHandler.log` backwards-compat

* Ignore mypy error

* Don't store `noisy_exceptions` attribute in app

* Added tests

* Store noisy exceptions setting in config

* Default to not-noisy if config key not available

* Add CLI tests for `noisy-exceptions`

* Remove debugging line I left in 😅

* Fix tests

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-10-27 10:43:58 +03:00
Cyril Nicodème
71cc30e5cd
Replacing assignation by typing for websocket_handshake (#2273)
* Replacing assignation by typing for `websocket_handshake`

Related to #2272

* Fix some type hinting issues

* Cleanup websocket handchake response concat

* Optimize concat encoding

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-10-27 10:00:04 +03:00
L. Kärkkäinen
645310cff6
Change codeclimate complexity threshold from 5 to 10. (#2286)
Co-authored-by: L. Karkkainen <tronic@users.noreply.github.com>
Co-authored-by: Stephen Sadowski <stephen.sadowski@sjsadowski.com>
2021-10-24 22:30:35 +03:00
Stephen Sadowski
2f30b5748a
Update host test function names so they are not overwritten (#2287)
Fix function name reuse in cli tests
2021-10-24 12:29:16 -05:00
Stephen Sadowski
5e1ef96934
fix ipv6 display in startup info log (#2285)
* fix ipv6 display in startup info log

* refactored to oneliner by request

* Added test for passing ipv4 host

* Added test for passing ipv6 any host

* Added test for passing ipv6 loopback host
2021-10-24 11:14:00 -05:00
Ryu juheon
57e98b62b3
style: add some type hints (#2279)
* style: add some type hints

* fix: *args is a tuple, but overridden as a list

* fix: if touch this, it will be a maybe breaking change

* fix: remove unused import

* style(app): more correct type
2021-10-20 15:15:39 +03:00
Néstor Pérez
3262878ebd
Fix docs error (#2269) 2021-10-10 22:41:45 +03:00
Adam Hopkins
5e12edbc38
Allow non-conforming ErrorHandlers (#2259)
* Allow non-conforming ErrorHandlers

* Rename to legacy lookup

* Updated depnotice

* Bump version

* Fix formatting

* Remove unused import

* Fix error messages
2021-10-03 01:02:56 +03:00
Adam Hopkins
50a606adee
Merge pull request #2256 from sanic-org/current-release
Mergeback
2021-10-02 22:21:34 +03:00
Adam Hopkins
f995612073 Merge branch 'main' of github.com:sanic-org/sanic into current-release 2021-10-02 21:57:58 +03:00
Adam Hopkins
bc08383acd
Merge in main to current-release (#2254)
* Remove unnecessary import in test_constants.py, which also fixes an error on win (#2180)

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>

* Manually reset the buffer when streaming request body (#2183)

* Remove Duplicated Dependencies and PEP 517 Support (#2173)

* Remove duplicated dependencies

* Specify setuptools as the tool for generating distribution (PEP 517)

* Add `isort` to `dev_require`

* manage all dependencies in setup.py

* Execute `make pretty`

* Set usedevelop to true (revert previous change)

* Fix the handling of the end of a chunked request. (#2188)

* Fix the handling of the end of a chunked request.

* Avoid hardcoding final chunk header size.

* Add some unit tests for pipeline body reading

* Decode bytes for json serialization

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Resolve regressions in exceptions (#2181)

* Update sanic-routing to fix path issues plus lookahead / lookbehind support (#2178)

* Update sanic-routing to fix path issues plus lookahead / lookbehind support

* Update setup.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>

* style(app,blueprints): add some type hints (#2196)

* style(app,blueprints): add some type hints

* style(app): option is Any

* style(blueprints): url prefix default value is ``""``

* style(app): backward compatible

* style(app): backward compatible

* style(blueprints): defult is None

* style(app): apply code style (black)

* Update some CC config (#2199)

* Update README.rst

* raise exception for `_static_request_handler` unknown exception; add test with custom error (#2195)

Co-authored-by: n.feofanov <n.feofanov@visionlabs.ru>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>

* Change dumps to AnyStr (#2193)

* HTTP tests (#2194)

* Fix issues with after request handling in HTTP pipelining (#2201)

* Clean up after a request is complete, before the next pipelined request.

* Limit the size of request body consumed after handler has finished.

* Linter error.

* Add unit test re: bad headers

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update CHANGELOG

* Log remote address if available (#2207)

* Log remote address if available

* Add tests

* Fix testing version

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Fixed for handling exceptions of asgi app call. (#2211)

@cansarigol3megawatt Thanks for looking into this and getting the quick turnaround on this. I will 🍒 pick this into the 21.6 branch and get it out a little later tonight.

* Signals Integration (#2160)

* Update some tests

* Resolve #2122 route decorator returning tuple

* Use rc sanic-routing version

* Update unit tests to <:str>

* Minimal working version with some signals implemented

* Add more http signals

* Update ASGI and change listeners to signals

* Allow for dynamic ODE signals

* Allow signals to be stacked

* Begin tests

* Prioritize match_info on keyword argument injection

* WIP on tests

* Compat with signals

* Work through some test coverage

* Passing tests

* Post linting

* Setup proper resets

* coverage reporting

* Fixes from vltr comments

* clear delayed tasks

* Fix bad test

* rm pycache

* uncomment windows tests (#2214)

* Add convenience methods to BP groups (#2209)

* Fix bug where ws exceptions not being logged (#2213)

* Fix bug where ws exceptions not being logged

* Fix t\est

* Style: add type hints (#2217)

* style(routes): add_route argument, return typing

* style(listeners): typing

* style(views): typing as_view

* style(routes): change type hint

* style(listeners): change type hint

* style(routes): change type hint

* add some more types

* Change as_view typing

* Add some cleaner type annotations

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Add default messages to SanicExceptions (#2216)

* Add default messages to SanicExceptions

* Cleaner exception message setting

* Copy Blueprints Implementation (#2184)

* Accept header parsing (#2200)

* Add some tests

* docstring

* Add accept matching

* Add some more tests on matching

* Add matching flags for wildcards

* Add mathing controls to accept

* Limit uvicorn 14 in testing

* Add convenience for annotated handlers (#2225)

* Split HttpProtocol parts into base SanicProtocol and HTTPProtocol subclass (#2229)

* Split HttpProtocol parts into base SanicProtocol and HTTPProtocol subclass.

* lint fixes

* re-black server.py

* Move server.py into its own module (#2230)

* Move server.py into its own module

* Change monkeypatch path on test_logging.py

* Blueprint specific exception handlers (#2208)

* Call abort() on sockets after close() to prevent dangling sockets (#2231)

* Add ability to return Falsey but not-None from handlers (#2236)

* Adds Blueprint Group exception decorator (#2238)

* Add exception decorator

* Added tests

* Fix line too long

* Static DIR and FILE resource types (#2244)

* Explicit static directive for serving file or dir


Co-authored-by: anbuhckr <36891836+anbuhckr@users.noreply.github.com>
Co-authored-by: anbuhckr <miki.suhendra@gmail.com>

* Close HTTP loop when connection task cancelled (#2245)

* Terminate loop when no transport exists

* Add log when closing HTTP loop because of shutdown

* Add unit test

* New websockets (#2158)

* First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work.

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* wip, update websockets code to new Sans/IO API

* Refactored new websockets impl into own modules
Incorporated other suggestions made by team

* Another round of work on the new websockets impl
* Added websocket_timeout support (matching previous/legacy support)
* Lots more comments
* Incorporated suggested changes from previous round of review
* Changed RuntimeError usage to ServerError
* Changed SanicException usage to ServerError
* Removed some redundant asserts
* Change remaining asserts to ServerErrors
* Fixed some timeout handling issues
* Fixed websocket.close() handling, and made it more robust
* Made auto_close task smarter and more error-resilient
* Made fail_connection routine smarter and more error-resilient

* Further new websockets impl fixes
* Update compatibility with Websockets v10
* Track server connection state in a more precise way
* Try to handle the shutdown process more gracefully
* Add a new end_connection() helper, to use as an alterative to close() or fail_connection()
* Kill the auto-close task and keepalive-timeout task when sanic is shutdown
* Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation.

* Change a warning message to debug level
Remove default values for deprecated websocket parameters

* Fix flake8 errors

* Fix a couple of missed failing tests

* remove websocket bench from examples

* Integrate suggestions from code reviews
Use Optional[T] instead of union[T,None]
Fix mypy type logic errors
change "is not None" to truthy checks where appropriate
change "is None" to falsy checks were appropriate
Add more debug logging when debug mode is on
Change to using sanic.logger for debug logging rather than error_logger.

* Fix long line lengths of debug messages
Add some new debug messages when websocket IO is paused and unpaused for flow control
Fix websocket example to use app.static()

* remove unused import in websocket example app

* re-run isort after Flake8 fixes

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>

* Account for BP with exception handler but no routes (#2246)

* Don't log "enabled" if auto-reload disabled (#2247)

Fixes #2240

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>

* Smarter auto fallback (#2162)

* Smarter auto fallback

* remove config from blueprints

* Add tests for error formatting

* Add check for proper format

* Fix some tests

* Add some tests

* docstring

* Add accept matching

* Add some more tests on matching

* Fix contains bug, earlier return on MediaType eq

* Add matching flags for wildcards

* Add mathing controls to accept

* Cleanup dev cruft

* Add cleanup and resolve OSError relating to test implementation

* Fix test

* Fix some typos

* Some fixes to the new Websockets impl (#2248)

* First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work.

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* wip, update websockets code to new Sans/IO API

* Refactored new websockets impl into own modules
Incorporated other suggestions made by team

* Another round of work on the new websockets impl
* Added websocket_timeout support (matching previous/legacy support)
* Lots more comments
* Incorporated suggested changes from previous round of review
* Changed RuntimeError usage to ServerError
* Changed SanicException usage to ServerError
* Removed some redundant asserts
* Change remaining asserts to ServerErrors
* Fixed some timeout handling issues
* Fixed websocket.close() handling, and made it more robust
* Made auto_close task smarter and more error-resilient
* Made fail_connection routine smarter and more error-resilient

* Further new websockets impl fixes
* Update compatibility with Websockets v10
* Track server connection state in a more precise way
* Try to handle the shutdown process more gracefully
* Add a new end_connection() helper, to use as an alterative to close() or fail_connection()
* Kill the auto-close task and keepalive-timeout task when sanic is shutdown
* Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation.

* Change a warning message to debug level
Remove default values for deprecated websocket parameters

* Fix flake8 errors

* Fix a couple of missed failing tests

* remove websocket bench from examples

* Integrate suggestions from code reviews
Use Optional[T] instead of union[T,None]
Fix mypy type logic errors
change "is not None" to truthy checks where appropriate
change "is None" to falsy checks were appropriate
Add more debug logging when debug mode is on
Change to using sanic.logger for debug logging rather than error_logger.

* Fix long line lengths of debug messages
Add some new debug messages when websocket IO is paused and unpaused for flow control
Fix websocket example to use app.static()

* remove unused import in websocket example app

* re-run isort after Flake8 fixes

* Some fixes to the new Websockets impl
Will throw WebsocketClosed exception instead of ServerException now when attempting to read or write to closed websocket, this makes it easier to catch
The various ws.recv() methods now have the ability to raise CancelledError into your websocket handler
Fix a niche close-socket negotiation bug
Fix bug where http protocol thought the websocket never sent any response.
Allow data to still send in some cases after websocket enters CLOSING state.
Fix some badly formatted and badly placed comments

* allow eof_received to send back data too, if the connection is in CLOSING state

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>

* 21.9 release docs (#2218)

* Beging 21.9 release docs

* Add PRs to changelog

* Change deprecation version

* Update logging tests

* Bump version

* Update changelog

* Change dev install command (#2251)

Co-authored-by: Zhiwei <zhi.wei.liang@outlook.com>
Co-authored-by: L. Kärkkäinen <98187+Tronic@users.noreply.github.com>
Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Robert Palmer <robd003@users.noreply.github.com>
Co-authored-by: Ryu JuHeon <saidbysolo@gmail.com>
Co-authored-by: gluhar2006 <49654448+gluhar2006@users.noreply.github.com>
Co-authored-by: n.feofanov <n.feofanov@visionlabs.ru>
Co-authored-by: Néstor Pérez <25409753+prryplatypus@users.noreply.github.com>
Co-authored-by: Can Sarigol <56863826+cansarigol3megawatt@users.noreply.github.com>
Co-authored-by: Zhiwei <chihwei.public@outlook.com>
Co-authored-by: YongChan Cho <h3236516@gmail.com>
Co-authored-by: Zhiwei <zhiwei@sinatra.ai>
Co-authored-by: Ashley Sommer <ashleysommer@gmail.com>
Co-authored-by: anbuhckr <36891836+anbuhckr@users.noreply.github.com>
Co-authored-by: anbuhckr <miki.suhendra@gmail.com>
2021-10-02 21:55:23 +03:00
L. Kärkkäinen
b83a1a184c
Change dev install command (#2251) 2021-10-02 19:57:02 +03:00
Adam Hopkins
59dd6814f8
21.9 release docs (#2218)
* Beging 21.9 release docs

* Add PRs to changelog

* Change deprecation version

* Update logging tests

* Bump version

* Update changelog
2021-09-30 22:36:34 +03:00
Ashley Sommer
f7abf3db1b
Some fixes to the new Websockets impl (#2248)
* First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work.

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* wip, update websockets code to new Sans/IO API

* Refactored new websockets impl into own modules
Incorporated other suggestions made by team

* Another round of work on the new websockets impl
* Added websocket_timeout support (matching previous/legacy support)
* Lots more comments
* Incorporated suggested changes from previous round of review
* Changed RuntimeError usage to ServerError
* Changed SanicException usage to ServerError
* Removed some redundant asserts
* Change remaining asserts to ServerErrors
* Fixed some timeout handling issues
* Fixed websocket.close() handling, and made it more robust
* Made auto_close task smarter and more error-resilient
* Made fail_connection routine smarter and more error-resilient

* Further new websockets impl fixes
* Update compatibility with Websockets v10
* Track server connection state in a more precise way
* Try to handle the shutdown process more gracefully
* Add a new end_connection() helper, to use as an alterative to close() or fail_connection()
* Kill the auto-close task and keepalive-timeout task when sanic is shutdown
* Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation.

* Change a warning message to debug level
Remove default values for deprecated websocket parameters

* Fix flake8 errors

* Fix a couple of missed failing tests

* remove websocket bench from examples

* Integrate suggestions from code reviews
Use Optional[T] instead of union[T,None]
Fix mypy type logic errors
change "is not None" to truthy checks where appropriate
change "is None" to falsy checks were appropriate
Add more debug logging when debug mode is on
Change to using sanic.logger for debug logging rather than error_logger.

* Fix long line lengths of debug messages
Add some new debug messages when websocket IO is paused and unpaused for flow control
Fix websocket example to use app.static()

* remove unused import in websocket example app

* re-run isort after Flake8 fixes

* Some fixes to the new Websockets impl
Will throw WebsocketClosed exception instead of ServerException now when attempting to read or write to closed websocket, this makes it easier to catch
The various ws.recv() methods now have the ability to raise CancelledError into your websocket handler
Fix a niche close-socket negotiation bug
Fix bug where http protocol thought the websocket never sent any response.
Allow data to still send in some cases after websocket enters CLOSING state.
Fix some badly formatted and badly placed comments

* allow eof_received to send back data too, if the connection is in CLOSING state

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-09-30 22:20:57 +03:00
Adam Hopkins
cf1d2148ac
Smarter auto fallback (#2162)
* Smarter auto fallback

* remove config from blueprints

* Add tests for error formatting

* Add check for proper format

* Fix some tests

* Add some tests

* docstring

* Add accept matching

* Add some more tests on matching

* Fix contains bug, earlier return on MediaType eq

* Add matching flags for wildcards

* Add mathing controls to accept

* Cleanup dev cruft

* Add cleanup and resolve OSError relating to test implementation

* Fix test

* Fix some typos
2021-09-29 23:53:49 +03:00
Ashley Sommer
b5f2bd9b0e
Don't log "enabled" if auto-reload disabled (#2247)
Fixes #2240

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-09-29 14:08:46 +03:00
Adam Hopkins
ba2670e99c
Account for BP with exception handler but no routes (#2246) 2021-09-29 13:47:31 +03:00
Ashley Sommer
6ffc4d9756
New websockets (#2158)
* First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work.

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* Update sanic/websocket.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>

* wip, update websockets code to new Sans/IO API

* Refactored new websockets impl into own modules
Incorporated other suggestions made by team

* Another round of work on the new websockets impl
* Added websocket_timeout support (matching previous/legacy support)
* Lots more comments
* Incorporated suggested changes from previous round of review
* Changed RuntimeError usage to ServerError
* Changed SanicException usage to ServerError
* Removed some redundant asserts
* Change remaining asserts to ServerErrors
* Fixed some timeout handling issues
* Fixed websocket.close() handling, and made it more robust
* Made auto_close task smarter and more error-resilient
* Made fail_connection routine smarter and more error-resilient

* Further new websockets impl fixes
* Update compatibility with Websockets v10
* Track server connection state in a more precise way
* Try to handle the shutdown process more gracefully
* Add a new end_connection() helper, to use as an alterative to close() or fail_connection()
* Kill the auto-close task and keepalive-timeout task when sanic is shutdown
* Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation.

* Change a warning message to debug level
Remove default values for deprecated websocket parameters

* Fix flake8 errors

* Fix a couple of missed failing tests

* remove websocket bench from examples

* Integrate suggestions from code reviews
Use Optional[T] instead of union[T,None]
Fix mypy type logic errors
change "is not None" to truthy checks where appropriate
change "is None" to falsy checks were appropriate
Add more debug logging when debug mode is on
Change to using sanic.logger for debug logging rather than error_logger.

* Fix long line lengths of debug messages
Add some new debug messages when websocket IO is paused and unpaused for flow control
Fix websocket example to use app.static()

* remove unused import in websocket example app

* re-run isort after Flake8 fixes

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-09-29 13:09:23 +03:00
Adam Hopkins
595d2c76ac
Close HTTP loop when connection task cancelled (#2245)
* Terminate loop when no transport exists

* Add log when closing HTTP loop because of shutdown

* Add unit test
2021-09-27 10:22:30 +03:00
Adam Hopkins
d9796e9b1e
Static DIR and FILE resource types (#2244)
* Explicit static directive for serving file or dir


Co-authored-by: anbuhckr <36891836+anbuhckr@users.noreply.github.com>
Co-authored-by: anbuhckr <miki.suhendra@gmail.com>
2021-09-26 01:01:23 +03:00
Néstor Pérez
404c5f9f9e
Adds Blueprint Group exception decorator (#2238)
* Add exception decorator

* Added tests

* Fix line too long
2021-09-12 22:02:59 +03:00
Adam Hopkins
a937e08ef0
Add ability to return Falsey but not-None from handlers (#2236) 2021-09-12 07:19:26 +03:00
Ashley Sommer
ef4f058a6c
Call abort() on sockets after close() to prevent dangling sockets (#2231) 2021-09-01 08:14:11 +03:00
Adam Hopkins
69c5dde9bf
Blueprint specific exception handlers (#2208) 2021-08-31 12:32:51 +03:00
Adam Hopkins
945885d501
Move server.py into its own module (#2230)
* Move server.py into its own module

* Change monkeypatch path on test_logging.py
2021-08-31 11:51:32 +03:00
Ashley Sommer
9d0b54c90d
Split HttpProtocol parts into base SanicProtocol and HTTPProtocol subclass (#2229)
* Split HttpProtocol parts into base SanicProtocol and HTTPProtocol subclass.

* lint fixes

* re-black server.py
2021-08-31 10:49:58 +03:00
Adam Hopkins
2e5c288fea
Add convenience for annotated handlers (#2225) 2021-08-30 20:04:44 +03:00
Adam Hopkins
f32ef20b74
Accept header parsing (#2200)
* Add some tests

* docstring

* Add accept matching

* Add some more tests on matching

* Add matching flags for wildcards

* Add mathing controls to accept

* Limit uvicorn 14 in testing
2021-08-19 21:09:40 +03:00
Zhiwei
e2eefaac55
Copy Blueprints Implementation (#2184) 2021-08-10 01:07:04 +03:00
Adam Hopkins
e1cfbf0fd9
Add default messages to SanicExceptions (#2216)
* Add default messages to SanicExceptions

* Cleaner exception message setting
2021-08-09 21:14:15 +03:00
YongChan Cho
08c5689441
Style: add type hints (#2217)
* style(routes): add_route argument, return typing

* style(listeners): typing

* style(views): typing as_view

* style(routes): change type hint

* style(listeners): change type hint

* style(routes): change type hint

* add some more types

* Change as_view typing

* Add some cleaner type annotations

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-08-08 21:37:34 +03:00
Adam Hopkins
8dbda247d6
Fix bug where ws exceptions not being logged (#2213)
* Fix bug where ws exceptions not being logged

* Fix t\est
2021-08-07 23:24:48 +03:00
Adam Hopkins
71a631237d
Add convenience methods to BP groups (#2209) 2021-08-07 23:06:11 +03:00
Zhiwei
e22ff3828b
uncomment windows tests (#2214) 2021-08-06 11:52:38 +03:00
Adam Hopkins
b1b12e004e
Signals Integration (#2160)
* Update some tests

* Resolve #2122 route decorator returning tuple

* Use rc sanic-routing version

* Update unit tests to <:str>

* Minimal working version with some signals implemented

* Add more http signals

* Update ASGI and change listeners to signals

* Allow for dynamic ODE signals

* Allow signals to be stacked

* Begin tests

* Prioritize match_info on keyword argument injection

* WIP on tests

* Compat with signals

* Work through some test coverage

* Passing tests

* Post linting

* Setup proper resets

* coverage reporting

* Fixes from vltr comments

* clear delayed tasks

* Fix bad test

* rm pycache
2021-08-05 22:55:42 +03:00
Can Sarigol
5308fec354
Fixed for handling exceptions of asgi app call. (#2211)
@cansarigol3megawatt Thanks for looking into this and getting the quick turnaround on this. I will 🍒 pick this into the 21.6 branch and get it out a little later tonight.
2021-08-02 21:05:44 +03:00
Can Sarigol
0ba57d4701
Fixed for handling exceptions of asgi app call. (#2211)
@cansarigol3megawatt Thanks for looking into this and getting the quick turnaround on this. I will 🍒 pick this into the 21.6 branch and get it out a little later tonight.
2021-08-02 19:12:12 +03:00
Néstor Pérez
54ca6a6178
Log remote address if available (#2207)
* Log remote address if available

* Add tests

* Fix testing version

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-08-02 12:41:47 +03:00
Adam Hopkins
7dd4a78cf2
Update CHANGELOG 2021-07-28 12:12:30 +03:00
Adam Hopkins
52ff49512a
Merge branch 'current-release' of github.com:sanic-org/sanic 2021-07-28 12:10:47 +03:00
Adam Hopkins
5a48b94089
Bump version 21.6.1 2021-07-28 11:41:26 +03:00
L. Kärkkäinen
ba1c73d947
Fix issues with after request handling in HTTP pipelining (#2201)
* Clean up after a request is complete, before the next pipelined request.

* Limit the size of request body consumed after handler has finished.

* Linter error.

* Add unit test re: bad headers

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-07-28 11:40:34 +03:00
L. Kärkkäinen
4732b6bdfa
Fix issues with after request handling in HTTP pipelining (#2201)
* Clean up after a request is complete, before the next pipelined request.

* Limit the size of request body consumed after handler has finished.

* Linter error.

* Add unit test re: bad headers

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-07-28 11:38:28 +03:00
Adam Hopkins
a6e78b70ab
Resolve regressions in exceptions (#2181) 2021-07-28 11:37:24 +03:00
L. Kärkkäinen
bb1174afc5
Fix the handling of the end of a chunked request. (#2188)
* Fix the handling of the end of a chunked request.

* Avoid hardcoding final chunk header size.

* Add some unit tests for pipeline body reading

* Decode bytes for json serialization

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-07-28 11:36:56 +03:00
Adam Hopkins
df8abe9cfd
Manually reset the buffer when streaming request body (#2183) 2021-07-28 11:34:57 +03:00
Robert Palmer
c3bca97ee1
Update sanic-routing to fix path issues plus lookahead / lookbehind support (#2178)
* Update sanic-routing to fix path issues plus lookahead / lookbehind support

* Update setup.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-07-28 11:33:53 +03:00
Adam Hopkins
c3b6fa1bba
HTTP tests (#2194) 2021-07-19 16:52:33 +03:00
Adam Hopkins
94d496afe1
Change dumps to AnyStr (#2193) 2021-07-19 16:25:36 +03:00
gluhar2006
7b7a572f9b
raise exception for _static_request_handler unknown exception; add test with custom error (#2195)
Co-authored-by: n.feofanov <n.feofanov@visionlabs.ru>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-07-19 09:23:02 +03:00
Adam Hopkins
1b8cb742f9
Update README.rst 2021-07-18 23:22:19 +03:00
Adam Hopkins
3492d180a8
Update some CC config (#2199) 2021-07-18 12:32:35 +03:00
Ryu JuHeon
021da38373
style(app,blueprints): add some type hints (#2196)
* style(app,blueprints): add some type hints

* style(app): option is Any

* style(blueprints): url prefix default value is ``""``

* style(app): backward compatible

* style(app): backward compatible

* style(blueprints): defult is None

* style(app): apply code style (black)
2021-07-13 10:32:54 +03:00
Robert Palmer
ac784759d5
Update sanic-routing to fix path issues plus lookahead / lookbehind support (#2178)
* Update sanic-routing to fix path issues plus lookahead / lookbehind support

* Update setup.py

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-07-12 08:22:53 +03:00
Adam Hopkins
36eda2cd62
Resolve regressions in exceptions (#2181) 2021-07-12 00:35:27 +03:00
L. Kärkkäinen
08a4b3013f
Fix the handling of the end of a chunked request. (#2188)
* Fix the handling of the end of a chunked request.

* Avoid hardcoding final chunk header size.

* Add some unit tests for pipeline body reading

* Decode bytes for json serialization

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
2021-07-11 13:44:40 +03:00
Zhiwei
1dd0332e8b
Remove Duplicated Dependencies and PEP 517 Support (#2173)
* Remove duplicated dependencies

* Specify setuptools as the tool for generating distribution (PEP 517)

* Add `isort` to `dev_require`

* manage all dependencies in setup.py

* Execute `make pretty`

* Set usedevelop to true (revert previous change)
2021-07-08 09:12:56 +03:00
Adam Hopkins
a90877ac31
Manually reset the buffer when streaming request body (#2183) 2021-07-06 08:24:20 +03:00
Zhiwei
8b7ea27a48
Remove unnecessary import in test_constants.py, which also fixes an error on win (#2180)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-07-05 11:51:36 +03:00
Adam Hopkins
8df80e276b
sanic-routing==0.7.0 2021-06-27 23:01:47 +03:00
Adam Hopkins
30572c972d
21.6 Changelog, release version, and deprecations (#2172)
* Changelog and version

* Rearrange API docs for easier navigation

* Version 21.6 docs

* Change release workflow

* Disable Windows tests
2021-06-27 22:52:56 +03:00
Adam Hopkins
53da4dd091
Allow blueprints and groups to be infinitely reusable (#2150)
* Allow blueprints and groups to be infinitely reusable
2021-06-21 18:41:04 +03:00
Adam Hopkins
108a4a99c7
v2 AST router (#2133)
* Update some tests

* Update some tests

* Resolve #2122 route decorator returning tuple

* Use rc sanic-routing version

* Update unit tests to <:str>
2021-06-21 15:10:26 +03:00
Adam Hopkins
7c180376d6
Add Simple Server and Coverage action (#2168)
* Add Simple Server and CodeCov action

* Remove token

* Codecov to tox.ini

* fix tox

* Set coverage location

* Add ignore to codecov

* Try glob ignore

* Setup CodeClimate

* Allow coverage check to run

* Change coverage check

* Add codeclimate exclusions
2021-06-21 14:53:09 +03:00
Adam Hopkins
f39b8b32f7
Make sure ASGI ws subprotocols is a list (#2127)
* Ensure protocols is a list for ASGI

* Subprotocol updates
2021-06-21 14:39:06 +03:00
Adam Hopkins
c543d19f8a
CBV alternate attach; CompositionView deprecate (#2170)
* Deprecate composition view and add alternate methods to attach CBV

* Add args to CBV attaching
2021-06-21 14:26:42 +03:00
Adam Hopkins
80fca9aef7
Better exception handling (#2128)
* WIP for better exception handling

* Note about removal

* resolve conditional to reduce lookups

* Cleanup logic
2021-06-21 14:14:07 +03:00
Adam Hopkins
5bb9aa0c2c
Add reloading on addtional directories (#2167) 2021-06-18 11:39:09 +03:00
Stephen Sadowski
83c746ee57
Added new client_ip accessor (#2114)
* Added new client_ip accessor for ConnInfo class, updated request to use client_ip instead of client to be more representative of what will be returned (actual ipv6 ip instead of bracket wrapped ip)

* Fix ConnInfo init

* add ipv6 test - maybe will work?

* fixed silly indentation error

* Bump testing client

* Extend testing

* Fix text

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-06-16 22:34:52 +03:00
Aymeric Augustin
aff6604636
Upgrade websockets dependency. (#2154)
* Upgrade websockets dependency.

Fix #2142.

* Bumpt sanic-testing version

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-06-16 21:49:50 +03:00
sanjeevanahilan
2c80571a8a
Update listeners.py (#2164)
fix typo

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-06-16 16:00:29 +03:00
Adam Hopkins
d964b552af
HTTPMethod enum (#2165)
* Add HTTP enum constants

* Tests

* Add some more string compat
2021-06-16 15:13:55 +03:00
Thomas Grainger
48f8b37b74
support app factory patten in CLI (#2157)
* support app factory patten in CLI

* Update sanic/__main__.py

* fix mypy errors

* Update mypy further

* Update sanic/utils.py

* Update sanic/utils.py

* support hypercorn/gunicorn style 'asgi.app:create_app()'

* add test for app factory
2021-06-09 12:05:56 +03:00
Adam Hopkins
141be0028d
Allow 8192 header max to be breached (#2155)
* Allow 8192 header max to be breached

* Add REQUEST_MAX_HEADER_SIZE as config value

* remove queue size
2021-06-04 13:56:29 +03:00
L. Kärkkäinen
a140c47195
Remove config.REQUEST_BUFFER_QUEUE_SIZE which was not being used since 21.03. (#2156)
Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2021-06-03 11:26:32 +03:00
Adam Hopkins
0c3a8392f2
Event autoregister (#2140)
* Add event autoregistration

* Setup tests

* Cleanup IDE added imports

* Remove unused imports
2021-06-01 10:44:07 +03:00
Adam Hopkins
16875b1f41
Disable MacOS Tests (#2151)
* Update pr-python37.yml

* Update workflows
2021-06-01 10:23:52 +03:00
Adam Hopkins
b1f31f2eeb
Alternatate classes on instantiation for Config and Sanic.ctx (#2119) 2021-06-01 00:21:31 +03:00
Adam Hopkins
d16b9e5a02
Cleanup conftest and fix warning message (#2147) 2021-05-31 22:41:41 +03:00
Adam Hopkins
680484bdc8
Update README.rst 2021-05-31 22:10:15 +03:00
Adam Hopkins
05cd44b5dd
Remove travis from repo (#2149)
* Remove travis from repo

* Use PR branch for Windows tests to add --user to pip args
2021-05-31 21:56:51 +03:00
Adam Hopkins
ba374139f4
Require stricter object names (#2146) 2021-05-30 15:37:44 +03:00
Adam Hopkins
72a745bfd5
Small improvements to CLI experience (#2136)
* Small improvements to CLI experience

* Add tests

* Add test server for cli testing

* Add LOGO logging to reloader and some additional context to logging debug

* Cleanup tests
2021-05-20 15:35:19 +03:00
Adam Hopkins
3a6fac7d59
Version prefix (#2137)
* Add version prefixing

* Versioning tests

* Testing BP group properties
2021-05-19 13:32:40 +03:00
Adam Hopkins
28ba8e53df
Implement 0.6 routing and some cleanup (#2117)
* Implement 0.6 routing and some cleanup

* Additional tests and annotation cleanup

* Resolve sorting

* cleanup test with encoding
2021-04-20 00:53:42 +03:00
Ajay Gupta
9b26358e63
add eof method to close stream (#2094)
* add eof method to close stream

* Add eof test

Co-authored-by: Ajay Gupta <ajay.gupta@1mg.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-04-18 02:46:34 +03:00
Johnathan Raymond
e21521f45c
Fix type hinting for load_env (#2107)
* Deprecate `load_env` in favor of `env_prefix`

`load_env` both enabled/disabled environment variable parsing, while
also letting the user modify the env prefix. Deprecate the ability to
disable environment parsing, and add a new config variable to track the
user's desired prefix for environment-based configuration.

Resolves: #2102

* Add a few common .gitignore patterns
2021-04-12 21:31:35 +03:00
Stephen Sadowski
30479765cb
Fix request.args.pop removes parameters inconsistently (#2110)
* Fix https://github.com/sanic-org/sanic/issues/2106

* style

* also apply fix to request.query_args

* add test

Co-authored-by: Arthur Goldberg <arthur.c.goldberg@gmail.com>
Co-authored-by: artcg <arthurgoldbergfwd@gmail.com>
2021-04-11 01:04:33 +03:00
ENT8R
53a571ec6c
Consistent use of error loggers (#2109)
* Consistent use of error loggers

* Fix tests
2021-04-10 21:35:53 +03:00
ENT8R
ad97cac313
Explicit usage of CIMultiDict getters (#2104) 2021-04-08 13:30:12 +03:00
Harsha Narayana
1a352ddf55
GIT-2023: Enable GitHub Actions support (#2050)
* GIT-2023: Enable GitHub Actions support

* GIT-2023: fix tox runtime trigger

* GIT-2023: add top level action name

* GIT-2023: rename tox step name

* GIT-2023: rename build task names

* GIT-2023: remove macos and windows + nightly versions

* GIT-2023: add macos and windows back to os matrix

* GIT-2023: expermiental flag to conditionally skip failure

* GIT-2023: enable using custom actions

* GIT-2023: fix matrix config rendering type

* GIT-2023: fix naming issue with os label

* GIT-2023: enable type-checking env for tox

* GIT-2023: enable pypy3.7 support

* GIT-2023: enable pypy experimental flag

* GIT-2023: add pypy tox env config

* add max timeout of 5 min for pypy tests

* GIT-2023: add timeout for each actions

* GIT-2023: fix codeQL workflow actions

* GIT-2023: limit test matrix to ubuntu and support on demand

* GIT-2023: enable docker image publish on release

* GIT-2023: fix on-demand pypy action

* GIT-2023: enable pypi publish workflow

* GIT-2023: enable verbose logs for py3.9

* GIT-2023: reduce py3.9 verbosity

* GIT-2023: enable docs linter

* GIT-2023: extend test matrix to include macos + windows

* GIT-2023: move windows based workflow to standalone task

* GIT-2023: fix windows test matrix

* GIT-2023: mark py39-no-ext as flaky test

* GIT-2023: mark flaky test

* GIT-2023: make timeout internal to steps for ease of management

* GIT-2023: rename image publish step name

* GIT-2023: mark keep alive client timeout for linux only

* GIT-2023: enable retries on test failure

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-04-06 23:32:01 +03:00
Lu
5ba43decf2
FIX UserWarning when using ASGI mode (#2091)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-04-06 22:36:50 +03:00
Frederik Gelder
8f06d035cb
fixing static request handler logging exception on 404 (#2099)
* fixing static request handler logging exception when not necessary, adding test to verify exception is gone on 404

* Fixup tests

* Fix tests

* resolve test failure

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-04-06 22:20:25 +03:00
Kyle Verhoog
b716f48c84
Update outdated handle_request docstring (#2100) 2021-04-06 13:41:18 +03:00
Arthur Goldberg
42b1e7143e
deprecate abort (#2077) 2021-04-05 18:01:48 +03:00
ENT8R
eba7821a6d
Allow case-insensitive HTTP Upgrade header (#2097)
* Allow case-insensitive HTTP Upgrade header

* Allow case-insensitive Upgrade header when checking the scheme

* Fix reference to headers

* Add None check

* Simplify HTTP Upgrade checks

* Fix newlines at end of file

* Run make pretty
2021-04-05 14:15:45 +03:00
Adam Hopkins
93a0246c03 Bump version: 2021-03-23 02:31:17 +02:00
Adam Hopkins
dfd1787a49
Make sure that blueprints with no slash is maintained when applied (#2085)
* Make sure that blueprints with no slash is maintained when applied

* Remove unneeded import
2021-03-23 02:28:42 +02:00
Adam Hopkins
4998fd54c0
Disable response timeout on websocket connections (#2081)
* Disable response timeout on websocket connections

* Add response timeout ignore test to websockets

* add logging assertion

* Move test items inside test context
2021-03-23 01:20:17 +02:00
Adam Hopkins
7be5f0ed3d CHANGELOG for 21.3.1 2021-03-21 15:04:27 +02:00
Adam Hopkins
938d2b5923
Static dir 2075 (#2076)
* Add support for nested static directories

* Add support for nested static directories

* Bump version 21.3.1
2021-03-21 15:03:54 +02:00
Adam Hopkins
13630a79ad Update sanic-org URL on setup.py 2021-03-21 12:00:32 +02:00
Adam Hopkins
2586989eb7
Prepare for 21.3 release (#2057)
* Prepare for release

* Add to changelog recent PRs

* add missing changelog items and update contributing docs

* Add 2061

* add 2060 to changelog

* Add 20.12.3 to changelog

* Add #2064 to changelog

* Do not show host and port in README

* Add some documentation PRs to changelog

* add new decorators to changelog

* Add 2063

* Add some PRs to misc
2021-03-21 10:43:18 +02:00
Arthur Goldberg
6763e2bb0a
fix?: recursion error on Sanic subclass initialisation (#2072)
* fix?: recursion error on Sanic subclass init

* tests: add test case for sanic subclass initialisation

* Remove BaseSanic metaclass

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-03-21 10:09:31 +02:00
Adam Hopkins
15a8b5c894
Perf improv (#2074)
* handler improvements for performance

* Resovle tests

* Linting

* Add tests
2021-03-21 09:47:21 +02:00
Adam Hopkins
8a2ea626c6
RFC/1684 Context objects (#2063)
* Initial setup

* connection context

* Add tests

* move ctx to conn_info

* Move __setattr__ for __fake_slots__ check into base calss
2021-03-17 20:55:52 +02:00
Adam Hopkins
01f238de79
Update CODEOWNERS 2021-03-16 11:24:53 +02:00
Adam Hopkins
7bed5a5c3c
Add convenience decorators for new listeners (#2064) 2021-03-16 11:21:05 +02:00
Adam Hopkins
2fea954dcf
Add signal reservations (#2060)
* Add signal reservations

* Simplify reservations
2021-03-14 15:21:59 +02:00
Adam Hopkins
d4660d0ca7
Add add_signal method (#2061) 2021-03-14 14:06:27 +02:00
Adam Hopkins
824f41d6e0
RFC/1630 Signals (#2042)
* Temp working version of initial signal api

* fix signals router finalizing

* Additional tests

* Add event test

* finalize test

* remove old comment

* Add some missing annotations

* multiple apps per BP support

* deepsource?

* rtemove deepsource

* nominal change

* fix blueprints test

* trivial change to trigger build

* signal docstring

* squash

* squash

* Add a couple new tests

* Add some suggestions from review

* Remove inaccessible code

* Change where to condition
2021-03-14 10:09:07 +02:00
Andrea Stagi
1165663ec1
Add name to Sanic instance in Hello World Example (#2058) 2021-03-12 15:23:13 +02:00
Adam Hopkins
b1a57a8b62
JSON encoder change via app (#2055) 2021-03-11 17:09:18 +02:00
Adam Hopkins
d76925cf35
Make get_app name optional (#2053) 2021-03-11 16:27:56 +02:00
Adam Hopkins
400f54c7ec
Update README.rst 2021-03-10 18:14:48 +02:00
Adam Hopkins
ec7e4390e8
Fix some examples and docs (#2052) 2021-03-10 11:19:38 +02:00
Adam Hopkins
5ca8bb85cd
Update CODEOWNERS 2021-03-08 20:01:07 +02:00
elis-k
5c624f8b76
Find packages (#2049)
Error when installing from master because some packages ('models' & 'mixins') are not being included.
2021-03-07 16:51:14 +02:00
Harsha Narayana
2c25af8cf5
GIT-2045: enable versioning and strict slash on BlueprintGroup (#2047)
* GIT-2045: enable versioning and strict slash on BlueprintGroup

* GIT-2045: convert named tuple into typed format + unit tests

* GIT-2045: add example code for versioned bpg

* GIT-2045: None value for strict slashes check

* GIT-2045: refactor handler types and add benchmark for urlparse

* GIT-2045: reduce urlparse benchmark iterations

* GIT-2045: add unit test and url merge behavior

* GIT-2045: cleanup example code and remove print

* GIT-2045: add test for slash duplication avoidence

* GIT-2045: fix issue with tailing / getting appended

* GIT-2045: use Optional instead of Union for Typing

* GIT-2045: use string for version arg

* GIT-2045: combine optional with union
2021-03-07 14:54:45 +02:00
Adam Hopkins
be905e0009
Create CODEOWNERS 2021-03-05 10:47:39 +02:00
Aksh Gupta
0d2d62eae5
chore: refactor code quality issues (#2044) 2021-03-05 10:26:03 +02:00
Adam Hopkins
00a1ee0cb6
Update conf.py 2021-03-04 14:14:48 +02:00
Adam Hopkins
f0d44822bc
Update README.rst 2021-03-04 14:12:40 +02:00
Adam Hopkins
e771e4e019
Update README.rst 2021-03-04 14:12:24 +02:00
Adam Hopkins
82e5f57edd
Update README.rst 2021-03-04 14:05:48 +02:00
Adam Hopkins
93a697f6ea
Add __str__ and __repr__ to Sanic and Bluepring (#2043) 2021-03-03 16:58:18 +02:00
Adam Hopkins
a733d32715
Add raw header info to request object (#2032) 2021-03-03 16:33:34 +02:00
Adam Hopkins
c41d7136e8 Change order of Docs index 2021-03-03 09:26:22 +02:00
Adam Hopkins
bb65dda277 Docs changes for RTD 2021-03-03 09:21:44 +02:00
Adam Hopkins
e1e9a7cf20 Update Sphinx docs to use README 2021-03-01 23:08:11 +02:00
Adam Hopkins
27f64ddae2
Router tweaks (#2031)
* Add trailing slash when defined and strict_slashes

* Add partial matching, and fix some issues with url_for

* Cover additional edge cases

* cleanup tests
2021-03-01 15:30:52 +02:00
Adam Hopkins
4b968dc611
Listeners for main server process (#2018)
* Initial POC

* Add test case

* Resolve create_server and Gunicorn serve)

* add testr coverage
2021-03-01 15:03:26 +02:00
Adam Hopkins
170177feb0
Update README.rst 2021-03-01 01:03:42 +02:00
Adam Hopkins
eef44ae179
Merge pull request #2006 from sanic-org/docs-annotations
API Docs & Annotations
2021-02-28 19:59:02 +02:00
Adam Hopkins
161efc67a3
Merge branch 'master' into docs-annotations 2021-02-25 09:23:01 +02:00
Adam Hopkins
dbfc11f4c5
Update codecov.yml 2021-02-24 21:09:27 +02:00
Adam Hopkins
e5ea4f5019
Update README.rst 2021-02-24 09:52:47 +02:00
Adam Hopkins
62d0b05309
Update README.rst 2021-02-24 09:50:21 +02:00
Adam Hopkins
aae8f13d9a
Update README.rst 2021-02-23 22:05:53 +02:00
Adam Hopkins
eac900d363
Update README.rst 2021-02-23 12:07:30 +02:00
Adam Hopkins
cd0c3d3eea
Merge branch 'master' into docs-annotations 2021-02-22 22:32:04 +02:00
Adam Hopkins
b461cc338c
Merge pull request #2038 from sanic-org/codecov
Codecov
2021-02-22 22:31:37 +02:00
Adam Hopkins
7c34b57e92 squash 2021-02-22 15:21:43 +02:00
Adam Hopkins
c35a53fe24 squash 2021-02-22 15:19:15 +02:00
Adam Hopkins
055c78b475 squash 2021-02-22 15:15:51 +02:00
Adam Hopkins
a9a52ef1e9 Make codecov more lenient 2021-02-22 15:14:04 +02:00
Adam Hopkins
a760989354 Merge branch 'docs-annotations' of github.com:sanic-org/sanic into docs-annotations 2021-02-22 14:08:41 +02:00
Adam Hopkins
dee95fd1c0 Add more py37 typing hacks 2021-02-22 14:08:14 +02:00
Adam Hopkins
9c48c7d39b Add more py37 typing hacks 2021-02-22 14:08:04 +02:00
Adam Hopkins
fc5e3b4ede
Merge branch 'master' into docs-annotations 2021-02-22 13:43:23 +02:00
Adam Hopkins
baf96275bf
Merge pull request #2037 from sanic-org/drop36-tox
Fix tox for Python3.6 drop support
2021-02-22 13:43:03 +02:00
Adam Hopkins
3a45d3291b Add support for 3.7 checking of mock transport 2021-02-22 13:39:16 +02:00
Adam Hopkins
c7307c1f85 Add support for 3.7 checking of mock transport 2021-02-22 13:39:10 +02:00
Adam Hopkins
dec46d5c4a
Merge branch 'master' into drop36-tox 2021-02-22 13:21:45 +02:00
Adam Hopkins
93313e6385 Fix tox for Python3.6 drop support 2021-02-22 13:20:58 +02:00
Adam Hopkins
070236677c Merge in changes from 3.6 drop 2021-02-22 13:09:33 +02:00
Ashley Sommer
6b86921c7a
Merge pull request #2036 from sanic-org/drop-36
Remove Python 3.6 support
2021-02-22 09:13:07 +10:00
Adam Hopkins
8f3e076661 trivial 2021-02-21 23:42:32 +02:00
Adam Hopkins
37f0a51063 Remove Python 3.6 support 2021-02-21 23:28:28 +02:00
Adam Hopkins
d6343c367f Remove future annotations 2021-02-21 22:58:30 +02:00
Adam Hopkins
bad9fd0258 Cleanup type checking 2021-02-21 21:29:54 +02:00
Adam Hopkins
d402d0362e Cleanup type checking 2021-02-21 21:29:41 +02:00
Adam Hopkins
209579f280 Resolve tests 2021-02-17 16:10:57 +02:00
Adam Hopkins
9e23e75fb4 Resolve merge conflict 2021-02-16 11:36:06 +02:00
Adam Hopkins
8f8c00a99d
Merge pull request #2010 from sanic-org/sanic-routing
Sanic routing
2021-02-16 10:09:12 +02:00
Adam Hopkins
bb5501f4c4
Merge branch 'master' into sanic-routing 2021-02-16 09:37:59 +02:00
Adam Hopkins
d3cbcf0e46 Merge branch 'master' of github.com:sanic-org/sanic 2021-02-16 09:07:50 +02:00
Adam Hopkins
15502182e3 Update changelog 2021-02-16 09:07:12 +02:00
Adam Hopkins
375319038f Merge branch 'master' of github.com:sanic-org/sanic into sanic-routing 2021-02-16 01:34:44 +02:00
Adam Hopkins
4c29846cb1
Merge pull request #2024 from sanic-org/fix-uvloop-version
Fix uvloop to 0.14.0
2021-02-16 01:34:15 +02:00
Adam Hopkins
c942a5c51c Change uvloop ro range 2021-02-16 01:17:34 +02:00
Adam Hopkins
a913e712a7 test coverage 2021-02-15 22:45:21 +02:00
Adam Hopkins
7f63ad5484 Add some test coverage 2021-02-15 21:50:20 +02:00
Adam Hopkins
a498c29ec9 squash 2021-02-15 17:33:23 +02:00
Adam Hopkins
973c315790 Merge in latest from sanic-routing branch 2021-02-15 17:20:07 +02:00
Adam Hopkins
aea2e4e7f4 Fix uvloop to 0.14.0 2021-02-15 14:18:42 +02:00
Adam Hopkins
55a5ab4be1 squash 2021-02-15 14:01:32 +02:00
Adam Hopkins
5377a6eee3 squash 2021-02-15 13:54:08 +02:00
Adam Hopkins
6057da71f3 Resolve test suite 2021-02-15 13:45:29 +02:00
Adam Hopkins
e91b3d40a2 squash 2021-02-15 10:47:16 +02:00
Adam Hopkins
b89f9a57e0 static performance increase 2021-02-09 16:39:03 +02:00
Adam Hopkins
b850e49cb3 test coverage with param change 2021-02-09 16:17:53 +02:00
Adam Hopkins
6b68c3702e Temp performance testing 2021-02-09 12:25:08 +02:00
Adam Hopkins
5f17e9591b worker 2021-02-08 14:09:41 +02:00
Adam Hopkins
64f0496d9e ASGI working 2021-02-08 12:43:10 +02:00
Adam Hopkins
0d5b2a0f69 debug and working stage--squash 2021-02-08 12:18:29 +02:00
Adam Hopkins
c08b153cee Resolve some more tests 2021-02-07 11:38:37 +02:00
Adam Hopkins
a434ffa8b7 interim 2021-02-04 00:42:24 +02:00
Adam Hopkins
967c4e6a4e Clean up use cases 2021-02-03 22:37:19 +02:00
Adam Hopkins
3f1e9ff528 Clean up use cases: 2021-02-03 22:36:44 +02:00
Adam Hopkins
96cc49e31e fix method ignore on websocket route 2021-02-02 01:07:29 +02:00
Adam Hopkins
94e5f82a81 squash 2021-02-01 09:56:58 +02:00
Adam Hopkins
ffca01ffff
Merge pull request #2014 from sanic-org/test-manager-fix
Fix typo in asgi client
2021-01-31 16:59:00 +02:00
Adam Hopkins
0165c9c644 Fix typo in asgi client 2021-01-31 16:41:10 +02:00
Adam Hopkins
7b47a4bebc squash 2021-01-31 16:31:04 +02:00
Adam Hopkins
a46ea4fc59 squash 2021-01-31 16:08:19 +02:00
Adam Hopkins
4358a7eefd Add more documentationand type annotations 2021-01-31 12:30:37 +02:00
Adam Hopkins
b958cdc151 Additonal annotations 2021-01-29 16:19:10 +02:00
Ashley Sommer
afb527b37c
Merge pull request #2012 from sanic-org/testing-manage-2011
Testing manage 2011
2021-01-29 08:05:29 +10:00
Adam Hopkins
65b76f2762 Add in sanic-routing branch 2021-01-28 12:33:09 +02:00
Adam Hopkins
e54685d34d
Merge branch 'master' into testing-manage-2011 2021-01-28 12:03:51 +02:00
Adam Hopkins
6009e6d35d
Update SECURITY.md 2021-01-28 11:54:07 +02:00
Adam Hopkins
d5f09dd9d8
Merge pull request #2013 from sanic-org/ahopkins-patch-1
Create codeql-analysis.yml
2021-01-28 11:49:31 +02:00
Adam Hopkins
ffae6f56c5
Update codeql-analysis.yml 2021-01-28 11:35:51 +02:00
Adam Hopkins
838563c751
Create codeql-analysis.yml 2021-01-28 11:32:30 +02:00
Adam Hopkins
83705b91c2 squash 2021-01-28 09:34:51 +02:00
Adam Hopkins
5abeae8f46 squash 2021-01-28 09:34:13 +02:00
Adam Hopkins
693f2a5014 Adds testing manager to testing client property 2021-01-28 09:33:49 +02:00
Adam Hopkins
5545264cea
Remove test client (#2009)
* Initial

* remove testmanager

* Resolve tests
2021-01-28 09:22:22 +02:00
Adam Hopkins
e04f206c50 Add SanicBase 2021-01-28 09:18:06 +02:00
Adam Hopkins
e9459792a4 Finish moving some more logic to mixins 2021-01-27 15:57:21 +02:00
Adam Hopkins
dadf76ce72 Move logic into mixins 2021-01-27 10:25:05 +02:00
Adam Hopkins
33d7f4da6b Breakup App and Bluieprint 2021-01-26 23:14:47 +02:00
Adam Hopkins
5f79291b55 additional compat support 2021-01-26 09:24:38 +02:00
Adam Hopkins
792a72bdf4 Initial introduction of sanic-routing 2021-01-26 08:47:16 +02:00
Adam Hopkins
c32e7fd678 Resolve tests 2021-01-25 02:39:13 +02:00
Adam Hopkins
76ef641743 Resolve tests 2021-01-25 02:14:48 +02:00
Adam Hopkins
1f0f4ef5d5 remove testmanager 2021-01-19 16:34:52 +02:00
Adam Hopkins
933d005e5d squash 2021-01-19 16:17:07 +02:00
Adam Hopkins
f8f215772c squash 2021-01-19 16:11:09 +02:00
Adam Hopkins
a0066e5752 Initial 2021-01-19 15:54:20 +02:00
Adam Hopkins
976a4c764d Set 21.3 alpha version 2021-01-19 11:04:11 +02:00
Adam Hopkins
0d7e2f0d67
Add request.id (#2005) 2021-01-19 04:25:39 +02:00
Ashley Sommer
6c03dd87b1
Allow Pathlib Path objects to be passed to app.static() helper (#2008)
* Allow Pathlib Path objects to be passed to the app.static file endpoint register helper.

* fixed import sort

* Raise error if static file path is not an accepted object type
Added more tests to improve coverage on the new type checks.
2021-01-19 03:53:14 +02:00
Adam Hopkins
0c252e7904
21.3 deprecations (#2007)
* Cleanup deprecations

* Remove config deprecations and fix config compat

* Add some tests and remove unneeded dependency

* Add some tests and remove unneeded dependency

* Remove pytest-dependency
2021-01-19 01:36:50 +02:00
Adam Hopkins
8f4e0ad3c8
Raise ValueError when cookie max-age is not an integer (#2001)
* Raise valueerror when cookie max-age is not an integer
2021-01-19 01:11:39 +02:00
Adam Hopkins
95b5260b27 blueprints and compat docs 2021-01-18 22:10:47 +02:00
Adam Hopkins
2f48e81e0b Begin documentation and annotation backfill 2021-01-18 13:21:37 +02:00
L. Kärkkäinen
7028eae083
Streaming Server (#1876)
* Streaming request by async for.

* Make all requests streaming and preload body for non-streaming handlers.

* Cleanup of code and avoid mixing streaming responses.

* Async http protocol loop.

* Change of test: don't require early bad request error but only after CRLF-CRLF.

* Add back streaming requests.

* Rewritten request body parser.

* Misc. cleanup, down to 4 failing tests.

* All tests OK.

* Entirely remove request body queue.

* Let black f*ckup the layout

* Better testing error messages on protocol errors.

* Remove StreamBuffer tests because the type is about to be removed.

* Remove tests using the deprecated get_headers function that can no longer be supported. Chunked mode is now autodetected, so do not put content-length header if chunked mode is preferred.

* Major refactoring of HTTP protocol handling (new module http.py added), all requests made streaming. A few compatibility issues and a lot of cleanup to be done remain, 16 tests failing.

* Terminate check_timeouts once connection_task finishes.

* Code cleanup, 14 tests failing.

* Much cleanup, 12 failing...

* Even more cleanup and error checking, 8 failing tests.

* Remove keep-alive header from responses. First of all, it should say timeout=<value> which wasn't the case with existing implementation, and secondly none of the other web servers I tried include this header.

* Everything but CustomServer OK.

* Linter

* Disable custom protocol test

* Remove unnecessary variables, optimise performance.

* A test was missing that body_init/body_push/body_finish are never called. Rewritten using receive_body and case switching to make it fail if bypassed.

* Minor fixes.

* Remove unused code.

* Py 3.8 check for deprecated loop argument.

* Fix a middleware cancellation handling test with py38.

* Linter 'n fixes

* Typing

* Stricter handling of request header size

* More specific error messages on Payload Too Large.

* Init http.response = None

* Messages further tuned.

* Always try to consume request body, plus minor cleanup.

* Add a missing check in case of close_if_idle on a dead connection.

* Avoid error messages on PayloadTooLarge.

* Add test for new API.

* json takes str, not bytes

* Default to no maximum request size for streaming handlers.

* Fix chunked mode crash.

* Header values should be strictly ASCII but both UTF-8 and Latin-1 exist. Use UTF-8B to
cope with all.

* Refactoring and cleanup.

* Unify response header processing of ASGI and asyncio modes.

* Avoid special handling of StreamingHTTPResponse.

* 35 % speedup in HTTP/1.1 response formatting (not so much overall effect).

* Duplicate set-cookie headers were being produced.

* Cleanup processed_headers some more.

* Linting

* Import ordering

* Response middleware ran by async request.respond().

* Need to check if transport is closing to avoid getting stuck in sending loops after peer has disconnected.

* Middleware and error handling refactoring.

* Linter

* Fix tracking of HTTP stage when writing to transport fails.

* Add clarifying comment

* Add a check for request body functions and a test for NotImplementedError.

* Linter and typing

* These must be tuples + hack mypy warnings away.

* New streaming test and minor fixes.

* Constant receive buffer size.

* 256 KiB send and receive buffers.

* Revert "256 KiB send and receive buffers."

This reverts commit abc1e3edb2.

* app.handle_exception already sends the response.

* Improved handling of errors during request.

* An odd hack to avoid an httpx limitation that causes test failures.

* Limit request header size to 8 KiB at most.

* Remove unnecessary use of format string.

* Cleanup tests

* Remove artifact

* Fix type checking

* Mark test for skipping

* Cleanup some edge cases

* Add ignore_body flag to safe methods

* Add unit tests for timeout logic

* Add unit tests for timeout logic

* Fix Mock usage in timeout test

* Change logging test to only logger in handler

* Windows py3.8 logging issue with current testing client

* Add test_header_size_exceeded

* Resolve merge conflicts

* Add request middleware to hard exception handling

* Add request middleware to hard exception handling

* Request middleware on exception handlers

* Linting

* Cleanup deprecations

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2021-01-11 00:45:36 +02:00
Adam Hopkins
574a9c27a6 Update README 2021-01-07 08:25:36 +02:00
Adam Hopkins
f9414f89f3 Update README 2021-01-07 08:24:11 +02:00
Adam Hopkins
fcdbeb7bd4
20.12 lts (#1996)
* Bump to v20.12

* Update Changelog

* #1993 Disable registry (#1994)

* Bump to v20.12 (#1987)

* Bump to v20.12

* Update Changelog

* Add disable app registry

* squash

* Create FUNDING.yml (#1995)
2021-01-07 08:11:18 +02:00
Adam Hopkins
206992fe40
#1989 Add disable app registry (#1993)
* Bump to v20.12

* Update Changelog

* Add disable app registry

* squash
2021-01-05 16:57:35 +02:00
Adam Hopkins
31337ba92a
Create FUNDING.yml (#1995) 2021-01-05 10:43:22 +02:00
Adam Hopkins
150d75b7c6
Bump to v20.12 (#1987)
* Bump to v20.12

* Update Changelog
2020-12-28 23:51:23 +02:00
Tomasz Drożdż
7475897a03
Making static route more verbose if file not found (#1945)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-12-28 23:17:32 +02:00
Adam Hopkins
449bc417a3
App registry (#1979)
* Add app level registry

* Add documentation for app registry

* Remove unused import

* Add force_create keyword to Sanic.get_app

* Add force_commit to docs
2020-12-28 22:47:31 +02:00
Adam Hopkins
262f89f2b6
Merge pull request #1984 from markgras/patch-1
Fix typo in routing.rst
2020-12-25 08:29:21 +02:00
Adam Hopkins
38337446cf
Merge branch 'master' into patch-1 2020-12-25 06:48:42 +02:00
Adam Hopkins
ac1331ea4c
Merge pull request #1983 from sinabeuro/dev-typo_doc_r0
Remove duplicate contents in document
2020-12-25 06:48:26 +02:00
Adam Hopkins
2b947e831f
Merge branch 'master' into dev-typo_doc_r0 2020-12-25 01:35:22 +02:00
Adam Hopkins
112715eb80
Merge pull request #1986 from huge-success/tox-reqs
Update reqs to get tox running
2020-12-25 01:34:45 +02:00
Adam Hopkins
ea9cf365bc Turn off Appyveyor 3.9 2020-12-24 22:09:51 +02:00
Adam Hopkins
b9b3b4051a Update reqs to get tox running 2020-12-24 21:56:35 +02:00
Adam Hopkins
ecb6db29e6
Merge branch 'master' into dev-typo_doc_r0 2020-12-24 21:00:20 +02:00
Adam Hopkins
6515dde64b
Merge pull request #1981 from huge-success/deprecation-cleanup
Cleanup and remove some deprecated code
2020-12-24 19:48:58 +02:00
Mark Grassi
01d2a2aa3c
Fix typo in routing.rst
This fixes a small typo in the routing docs.
2020-12-20 16:08:51 -05:00
sinabeuro
39e12accb8 Remove duplicate contents in document
Since the contents of line 61 and line 75 of the 'testing' document are
duplicated, the content of line 61 is removed for context.

Signed-off-by: sinabeuro <ican312@hanmail.net>
2020-12-18 12:25:24 +09:00
Adam Hopkins
39fe6ea5b1 Cleanup and remove some deprecated code 2020-12-14 09:23:13 +02:00
Adam Hopkins
fc4b7df088
Merge pull request #1961 from huge-success/py39
Update testing for Python 3.9
2020-12-10 09:25:12 +02:00
Adam Hopkins
35f28f7a64
Merge branch 'master' into py39 2020-12-09 11:52:49 +02:00
Adam Hopkins
614be40438
Name endpoints at startup (#1972)
* Name endpoints at startup

* Beautify

* Fix reformatting
2020-11-29 23:26:12 +02:00
Adam Hopkins
bde0428d0c
Update README.rst (#1973)
Change `.org` to `.com` for transition in Travis.
2020-11-23 02:02:33 +02:00
Trevor Bekolay
63567c2ae4
Add py.typed file (#1970) 2020-11-19 11:18:25 +02:00
Ashley Sommer
ec10f337b6
Merge pull request #1969 from all2ham/remove-upper-bound-multidict-pin
loosen pin on multidict, add higher upper bound to multidict requirement
2020-11-18 15:25:18 +10:00
allandialpad
d0f0e73e96 remove upper bound for multidict 2020-11-17 11:18:18 -05:00
7
b4fe2c8a6b
bump up aiofile version constraint (#1967) 2020-11-06 08:32:04 +02:00
Adam Hopkins
33da0771d1
Merge pull request #1965 from ashleysommer/asgs_chunk_length
Fix Chunked Transport-Encoding in ASGI streaming response
2020-11-05 09:02:18 +02:00
Adam Hopkins
75994cd915 Fixes for linting and type hints 2020-11-05 08:49:55 +02:00
Ashley Sommer
c0839afdde Fix Chunked Transport-Encoding in ASGI streaming response
In ASGI-mode, don't do sanic-side response chunk encoding, leave that to the ASGI-response-transport
Don't set content-length when using chunked-encoding in ASGI mode, this is incompatible with ASGI Chunked Transport-Encoding.
2020-11-05 15:27:01 +10:00
Ashley Sommer
5961da3f57
Merge pull request #1960 from huge-success/release-notes-19.12.3-20.9.1
Update changelog for 19.12.3 and 20.9.1
2020-10-26 11:43:53 +10:00
Ashley Sommer
41f1809351
Merge branch 'master' into release-notes-19.12.3-20.9.1 2020-10-26 09:58:19 +10:00
Ashley Sommer
5fbdcb62e4
Merge pull request #1962 from huge-success/cli-upgrade
Sanic CLI upgrade
2020-10-26 08:31:45 +10:00
Ashley Sommer
677b83e9f8
Merge branch 'master' into release-notes-19.12.3-20.9.1 2020-10-26 08:21:44 +10:00
Adam Hopkins
6a5c8becac
Merge branch 'master' into cli-upgrade 2020-10-25 22:46:37 +02:00
Adam Hopkins
fd23b99d60
Merge pull request #1951 from tomaszdrozdz/Improving-documentation
Improving documentation.
2020-10-25 22:45:37 +02:00
Adam Hopkins
634b586df3
Merge branch 'master' into Improving-documentation 2020-10-25 21:32:54 +02:00
Ashley Sommer
4ca3e98082
Add pytest-dependency requirement to tests_require list in setup.py (#1955)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-10-25 21:31:34 +02:00
Adam Hopkins
d18a776964 squash 2020-10-25 21:22:19 +02:00
Adam Hopkins
d6b4d7d265 Add bionic in travis and change path in appveyor 2020-10-25 21:01:31 +02:00
Adam Hopkins
33ee4c21b3 Add BASE_LOGO to sanic cli 2020-10-25 20:45:06 +02:00
Adam Hopkins
a026cd7195 add --access-logs flag to sanic cli 2020-10-25 20:36:22 +02:00
Adam Hopkins
7b1bce8d90 Add some help messages and a user friendly cli experience 2020-10-25 20:21:09 +02:00
Adam Hopkins
217a7c5161 Small changes to sanic-cli to make it more user friendly 2020-10-25 20:09:42 +02:00
Adam Hopkins
2949e3422d Add 3.9 to appveyor 2020-10-25 15:37:48 +02:00
Adam Hopkins
16ea99b0c0 Update testing for Python 3.9 2020-10-25 15:21:48 +02:00
Adam Hopkins
19b84ce9f0 Update changelog for 19.12.3 and 20.9.1 2020-10-25 15:11:39 +02:00
Adam Hopkins
e5aed4c067
Ignore writing headers when in ASGI mode (#1957)
* Ignore writing headers when in ASGI mode for streaming responses

* Move asgi set on streaming until after response type check

* Adds multidict==5.0.0 to pass tests

* Bump version to 20.9.1
2020-10-25 15:01:53 +02:00
Ashley Sommer
9e048bc0c3
Merge pull request #1956 from huge-success/fix-load-module-test
Fix load module test
2020-10-25 22:09:24 +10:00
Adam Hopkins
5d7b0735ce
Merge branch 'master' into fix-load-module-test 2020-10-25 08:27:25 +02:00
Adam Hopkins
12521cd5b4
Merge branch 'master' into Improving-documentation 2020-10-25 00:02:32 +03:00
Adam Hopkins
7dbd3eb5e8 Update multidict version 2020-10-24 23:49:55 +03:00
Adam Hopkins
96364aacc0 squash 2020-10-24 23:42:38 +03:00
Adam Hopkins
fc18f86964 Resolve broken test in appveyor 2020-10-24 23:03:25 +03:00
Ashley Sommer
fb3d368a78
Add ability for app.static() to return the routes it created. (#1954)
This allows blueprint registration to add the bp's static routes to its list of own routes. So now blueprint middlewares will apply to a blueprint's static file routes.
Fixes #1953
2020-10-24 22:57:02 +03:00
tomaszdrozdz
f41435fae3 Improving documentation. 2020-10-19 10:12:20 +02:00
Adam Hopkins
5928c50057
Version 20.9 (#1940) 2020-09-30 17:30:21 +03:00
Tomasz Drożdż
1de4bcef55
Update config (#1903)
* New aproach for uploading sanic app config.

* Update config.rst

Co-authored-by: tigerthelion <bjt.thompson@gmail.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-09-30 16:44:09 +03:00
Adam Hopkins
7b7559309d
Add issue config.yml (#1936)
* Add issue config.yml

* Update SECURITY.md
2020-09-30 15:38:08 +03:00
Adam Hopkins
066df2c142
Add text and json fallback error handlers (#1937)
* Add text and json fallback error handlers

* Add tests and auto-detect error fallback type
2020-09-30 15:11:27 +03:00
Adam Hopkins
0c4a9b1dce
Merge pull request #1909 from brooklet/master
fix websocket ping variables issues
2020-09-29 01:08:04 +03:00
Adam Hopkins
65a7060d3b
Merge branch 'master' into master 2020-09-29 00:41:22 +03:00
Adam Hopkins
3483e7b061 Fix linting issues 2020-09-29 00:40:24 +03:00
Adam Hopkins
13094e02bc Revert check for websocket protocol to use hasattr 2020-09-29 00:24:00 +03:00
Ashley Sommer
ed777e9d5b
Merge pull request #1935 from huge-success/httpx-upgrade
Upgrade httpx
2020-09-28 09:06:37 +10:00
Adam Hopkins
8ad80a282a
Merge branch 'master' into httpx-upgrade 2020-09-27 11:20:07 +03:00
Adam Hopkins
0b7eb49839
Merge pull request #1924 from tomaszdrozdz/strict_markers_for_pytest
Adding --strict-markers for pytest
2020-09-27 11:18:24 +03:00
Adam Hopkins
de3b40c2e6
Merge branch 'master' into strict_markers_for_pytest 2020-09-27 10:57:31 +03:00
Adam Hopkins
efa0aaf2c2 Add asyncio markers to tox.ini 2020-09-27 10:46:51 +03:00
Adam Hopkins
bd4e1cdc1e squash 2020-09-27 10:27:12 +03:00
Adam Hopkins
eb8df1fc18 Upgrade httpx 2020-09-27 02:58:36 +03:00
tomaszdrozdz
9a8e49751d Adding --strict-markers for pytest 2020-09-08 13:08:49 +02:00
raphaelauv
58e15134fd
Add explicit ASGI compliance to the README (#1922) 2020-09-02 23:22:02 +03:00
Adam Hopkins
875be11ae5
Update README.rst (#1917) 2020-08-27 10:28:56 +03:00
Andrew Scott
3f7c9ea3f5
feat: fixes exception due to unread bytes in stream (#1897)
* feat: fixes exception due to unread bytes in stream

* feat: additonal unit tests to cover changes

* fix: automated changes by `make fix-import`

* fix: additonal changes by `make fix-import`

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-08-27 10:22:02 +03:00
brook
33aa4daac8 fixed the problem that the websocket ping_timeout and ping_interval parameter settings did not take effect 2020-08-13 14:39:55 +08:00
Shawn Hill
58e4087d4b
Add websocket ping variables (#1906)
* Add config params for websocket ping_timeout & ping_interval

* Include changelog

* Pass websocket config values to WebSocketProtocol init, test

* Linting

* Improve docs

Co-authored-by: shawnhill <shawn.hill@equipmentshare.com>
2020-08-07 06:37:59 +03:00
Ashley Sommer
0072fd1573
Add an additional component to the request_data context test. This checks if items stored a request.ctx are able to be accessed from a response-middleware after a response is issued. (#1888)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-07-29 14:25:31 +03:00
Lee Tat Wai David
5d5ed10a45
Websocket subprotocol (#1887)
* Added fix to include subprotocols from scope

* Added unit test to validate fix

* Changes by black

* Made changes to WebsocketConnection protocol

* Linter changes

* Added unit tests

* Fixing bugs in linting due to isort import checks

* Reverting compat import changes

* Fixing linter errors in compat.py

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-07-29 14:09:26 +03:00
Ashley Sommer
5ee8ee7b04
Merge pull request #1894 from huge-success/test_mode
add a test_mode boolean variable to sanic `app` which is set to True when using Sanic TestClient or ASGIClient, and False all other times.
2020-07-15 22:46:23 +10:00
Adam Hopkins
521ae7f60e squash 2020-07-14 10:41:28 +03:00
Adam Hopkins
27c8c12420 squash 2020-07-14 10:30:48 +03:00
Adam Hopkins
3d1f100781 squash 2020-07-14 10:30:01 +03:00
Adam Hopkins
16d36fc17f squash 2020-07-14 10:25:56 +03:00
Adam Hopkins
eddb5bad91 squash 2020-07-14 10:25:30 +03:00
Adam Hopkins
23e1b5ee3f squash 2020-07-14 10:23:31 +03:00
Adam Hopkins
9e053bef19 squash 2020-07-14 10:13:30 +03:00
Adam Hopkins
cf234fca15 squash this 2020-07-13 23:59:45 +03:00
Adam Hopkins
050a563e1d Add documentation on test mode 2020-07-09 14:57:42 +03:00
Adam Hopkins
c347ff742e Add app.test_mode which is set on testing calls 2020-07-09 14:52:58 +03:00
Adam Hopkins
db1c819fe1 Merge branch 'master' of github.com:huge-success/sanic 2020-07-09 14:24:06 +03:00
Egor
9f2818ee29
Remove version section (#1893) 2020-07-09 07:17:50 +03:00
Adam Hopkins
26aa6d23c7
Fix imports and isort to remove from Makefile deprecated options (#1891)
* Version

* Version 20.6.1

* Fix imports and isort to remove from Makefile deprecated options

* duplicate the mypy ignore hint across both lines

after splitting the `from trio import ...` statement onto two lines, need to duplicate the mypy ignore hint across both lines to keep mypy from complaining

Co-authored-by: Ashley Sommer <ashleysommer@gmail.com>
2020-07-07 16:13:03 +03:00
Adam Hopkins
ec7e894eb3 Merge branch 'master' of github.com:huge-success/sanic 2020-07-07 08:46:01 +03:00
Ashley Sommer
71a08382d6
Adjust isort options and invocation to work on isort 5.0.0 (#1890)
isort 5.0.0 removed command line option `recursive` and removed config option `not_skip`.
2020-07-07 08:43:33 +03:00
Adam Hopkins
09224f8676 Merge branch 'master' of github.com:huge-success/sanic 2020-06-29 15:19:32 +03:00
Adam Hopkins
008b8ac394
V2.6.3 changelog (#1886)
* Version

* Version 20.6.1

* v2.6.3 changelog and version
2020-06-29 15:16:06 +03:00
Adam Hopkins
a357add14e Merge branch 'master' of github.com:huge-success/sanic 2020-06-29 14:55:52 +03:00
Adam Hopkins
0cfd7b528b
V20.6.2 changelog (#1885)
* Version

* Version 20.6.1

* CHANGELOG for v20.6.2
2020-06-29 14:54:44 +03:00
Adam Hopkins
9ba4fe05df Merge branch 'master' of github.com:huge-success/sanic 2020-06-29 14:54:02 +03:00
Ashley Sommer
35786b4b74
Revert change to multiprocessing mode (#1884)
Revert change to multiprocessing mode accidentally included in https://github.com/huge-success/sanic/pull/1853

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-29 14:51:30 +03:00
Ashley Sommer
c7430d805a
Revert change to multiprocessing mode (#1884)
Revert change to multiprocessing mode accidentally included in https://github.com/huge-success/sanic/pull/1853

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-29 13:51:55 +03:00
Adam Hopkins
8a3fbb555f Merge branch 'master' of github.com:huge-success/sanic 2020-06-29 08:56:20 +03:00
L. Kärkkäinen
a62c84a954
Socket binding implemented properly for IPv6 and UNIX sockets. (#1641)
* Socket binding implemented properly for IPv6 and UNIX sockets.

- app.run("::1") for IPv6
- app.run("unix:/tmp/server.sock") for UNIX sockets
- app.run("localhost") retains old functionality (randomly either IPv4 or IPv6)

Do note that IPv6 and UNIX sockets are not fully supported by other Sanic facilities.
In particular, request.server_name and request.server_port are currently unreliable.

* Fix Windows compatibility by not referring to socket.AF_UNIX unless needed.

* Compatibility fix.

* Fix test of existing unix socket.

* Cleaner unix socket removal.

* Remove unix socket on exit also with workers=1.

* More pedantic UNIX socket implementation.

* Refactor app to take unix= argument instead of unix:-prefixed host. Goin' fast @ unix-socket fixed.

* Linter

* Proxy properties cleanup. Slight changes of semantics. SERVER_NAME now overrides everything.

* Have server fill in connection info instead of request asking the socket.

- Would be a good idea to remove request.transport entirely but I didn't dare to touch it yet.

* Linter 💣🌟💀

* Fix typing issues. request.server_name returns empty string if host header is missing.

* Fix tests

* Tests were failing, fix connection info.

* Linter nazi says you need that empty line.

* Rename a to addr, leave client empty for unix sockets.

* Add --unix support when sanic is run as module.

* Remove remove_route, deprecated in 19.6.

* Improved unix socket binding.

* More robust creating and unlinking of sockets. Show proper and not temporary name in conn_info.

* Add comprehensive tests for unix socket mode.

* Hide some imports inside functions to avoid Windows failure.

* Mention unix socket mode in deployment docs.

* Fix merge commit.

* Make test_unix_connection_multiple_workers pickleable for spawn mode multiprocessing.

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-29 08:55:32 +03:00
Adam Hopkins
4aba74d050
V20.6 version (#1882)
* Version

* Version 20.6.1

Co-authored-by: 7 <yunxu1992@gmail.com>
2020-06-29 00:17:24 +03:00
Adam Hopkins
ab2cb88cf4
CHANGELOG for v 20.6 and documentation change for sanic command (#1881)
* CHANGELOG for v 20.6 and documentation change for sanic command

* Update CHANGELOG.rst

20.6.0 and 20.6.1 are the same release. One change from `blueprints` had not made it in by accident, therefore the second subsequent release.
2020-06-28 11:42:12 -07:00
Adam Hopkins
e79ec7d7e0 Version 20.6.1 2020-06-28 17:21:48 +03:00
Adam Hopkins
ccdb74a9a7 Merge branch 'master' of github.com:huge-success/sanic 2020-06-28 17:21:12 +03:00
Adam Hopkins
7b96d633db Version 2020-06-28 17:19:57 +03:00
Adam Hopkins
938c49b899
Add handler names for websockets for url_for usage (#1880) 2020-06-28 14:45:52 +03:00
Ashley Sommer
761eef7d96
Fix pickle error when attempting to pickle an application which contains websocket routes. (#1853)
Moves the websocket_handler subfunction out to a class-level method, which can be more easily pickled by the built-in python Pickler.
Also includes a similar fix for the add_task deferred task scheduler subfunction.

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-28 11:05:06 +03:00
David Bordeynik
83511a0ba7
fix-#1851: correct step name (#1852)
* fix-#1851: correct step name

* fix-#1851: correct step name elsewhere as well

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-28 10:52:43 +03:00
Damian Jimenez
cf9ccdae47
Bug fix for host parameter issue with lists (#1776)
* Bug fix for host parameter issue with lists

As explained in #1772 there is an issue when using a list as an argument for the host parameter in the Blueprint.route() decorator. I've traced the issue back to this line, and the if conditional should ensure that the name attribute isn't accessed when route is None.

* Unit tests for blueprint.route host paramter set to list.

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-28 09:42:18 +03:00
Kiril Yershov
d81096fdc0
Clarified response middleware execution order in the documentation (#1846)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-28 09:29:48 +03:00
Adam Hopkins
6c8e20a859
Add version parameter to websocket routes (#1760)
* Add version parameter to websockets

* Run black and cleanup code
2020-06-28 09:17:18 +03:00
Liran Nuna
6239fa4f56
Deprecate body_bytes to merge into body (#1739)
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-28 08:59:23 +03:00
David Bordeynik
1b324ae981
fix-#1856: adjust websockets version to setup.py and make nightly (py39) tests pass (#1857)
* fix-#1856: adjust websockets version to setup.py and make nightly (py39) tests pass

* fix-#1856: set min websockets version to 8.1

* fix-#1856: suppress timeout for CI to pass

* fix-#1856: timeout -> close_timeout due to deprecation warning

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
Co-authored-by: 7 <yunxu1992@gmail.com>
2020-06-28 08:43:12 +03:00
Linus Groh
bedf68a9b2
Wrap run()'s "protocol" type annotation in Optional[] (#1869)
As the default is None and the function will determine a sane value
in that case, the correct annotation is "Optional[Type[Protocol]]".
2020-06-11 11:40:12 -07:00
Adam Hopkins
496e87e4ba
Add sanic as an entry point command (#1866)
* Add sanic as an entry point command

* Fix linting issue in imports

Co-authored-by: 7 <yunxu1992@gmail.com>
2020-06-05 07:14:18 -07:00
Luca Fabbri
fa4f85eb32
Fixing rst format issue (#1865)
Co-authored-by: 7 <yunxu1992@gmail.com>
2020-06-04 17:08:14 -07:00
Adam Hopkins
1b1dfedc74
Add changes from version 20.3 to CHANGELOG (#1867) 2020-06-04 15:45:55 -07:00
L. Kärkkäinen
230941ff4f
Fix reloader on OSX py38 and Windows (#1827)
* Fix watchdog reload worker repeatedly if there are multiple changed files

* Simplify autoreloader, don't need multiprocessing.Process. Now works on OSX py38.

* Allow autoreloader with multiple workers and run it earlier.

* This works OK on Windows too.

* I don't see how cwd could be different here.

* app.run and app.create_server argument fixup.

* Add test for auto_reload (coverage not working unfortunately).

* Reloader cleanup, don't use external kill commands and exit normally.

* Strip newlines on test output (Windows-compat).

* Report failures in test_auto_reload to avoid timeouts.

* Use different test server ports to avoid binding problems on Windows.

* Fix previous commit

* Listen on same port after reload.

* Show Goin' Fast banner on reloads.

* More robust testing, also -m sanic.

* Add a timeout to terminate process

* Try a workaround for tmpdir deletion on Windows.

* Join process also on error (context manager doesn't).

* Cleaner autoreloader termination on Windows.

* Remove unused code.

* Rename test.

* Longer timeout on test exit.

Co-authored-by: Hùng X. Lê <lexhung@gmail.com>
Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
2020-06-03 16:45:07 +03:00
Adam Hopkins
4658e0f2f3
Merge pull request #1842 from ashleysommer/fix_pickle_again
Fix static _handler pickling error.
2020-06-03 15:53:17 +03:00
Ashley Sommer
7c3c532dae
Merge branch 'master' into fix_pickle_again 2020-05-14 20:48:06 +10:00
Ashley Sommer
7c04c9a227
Merge pull request #1848 from ashleysommer/fix_named_response_middleware
Reverse named_response_middlware execution order, to match normal response middleware execution order.
2020-05-14 20:45:29 +10:00
Ashley Sommer
44973125c1 Reverse named_response_middlware execution order, to match normal response middleware execution order.
Fixes #1847
Adds a test to ensure fix is correct
Adds an example which demonstrates correct blueprint-middlware execution order behavior.
2020-05-14 09:54:47 +10:00
Adam Hopkins
6aaccd1e8b
Merge branch 'master' into fix_pickle_again 2020-05-13 15:46:37 +03:00
7
e7001b0074
release 20.3.0 (#1844) 2020-05-12 16:58:42 -07:00
Ashley Sommer
aacbd022cf Fix static _handler pickling error.
Moves the subfunction _handler out to a module-level function, and parameterizes it with functools.partial().
Fixes the case when picking a sanic app which has a registered static route handler. This is usually encountered when attempting to use multiprocessing or auto_reload on OSX or Windows.
Fixes #1774
2020-05-07 11:58:36 +10:00
WH-2099
ae1874ce34
Delete unnecessary isolated blanks and letters. (#1838) 2020-04-30 10:07:06 -07:00
L. Kärkkäinen
8abba597a8
Do not set content-type and content-length headers in exceptions. (#1820)
Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-04-25 20:18:59 -07:00
Prasanna Walimbe
9987893963
Update docs for order of listeners #1805 (#1834) 2020-04-25 17:03:23 -07:00
Jacob
638322d905
docs: Fix doc build (#1833)
* docs: Fix doc build

* docs: Use python-3.8 instead

* test: Remove pytest-asyncio form tox.ini
2020-04-24 14:13:35 -07:00
wangqr
ae40f960ff
Import ASGIDispatch from top-level httpx (#1806)
As importing from submodules of httpx is deprecated and removed in 0.12.0
2020-04-10 12:03:51 -07:00
koug44
d969fdc19f
[Doc] Update getting_started.rst (#1814)
* Update getting_started.rst

Replacing command to install Sanic without uvloop as the provided one is not working (at least in my case)

* Same thing as oneliner

* Update getting_started.rst

Dummy commit for Travis
2020-04-09 10:07:07 -07:00
L. Kärkkäinen
710024125e
Remove server config args that can be read directly from app. (#1807)
* Remove server config args that can be read directly from app.

* Linter

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-04-08 22:10:58 -07:00
Mykhailo Yusko
9a39aff803
Replaced str.format() method in core functionality (#1819)
* Replaced str.format() method in core functionality

* Fixed linter checks
2020-04-06 12:45:25 -07:00
L. Kärkkäinen
78e912ea45
Update docs with changes done in 20.3 (#1822)
* Remove raw_args from docs (deprecated feature removed in Sanic 20.3).

* Add missing Sanic(name) arguments in docs. Merge async/non-async class view examples.

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-03-31 10:57:09 -07:00
L. Kärkkäinen
aa6ea5b5a0
Updated deployment docs (#1821)
* Updated deployment docs

* Wording and formatting.

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-03-28 11:43:42 -07:00
L. Kärkkäinen
48800e657f
Deprecation and test cleanup (#1818)
* Remove remove_route, deprecated in 19.6.

* No need for py35 compat anymore.

* Rewrite asyncio.coroutines with async/await.

* Remove deprecated request.raw_args.

* response.text() takes str only: avoid deprecation warning in all but one test.

* Remove unused import.

* Revert unnecessary deprecation warning.

* Remove apparently unnecessary py38 compat.

* Avoid asyncio.Task.all_tasks deprecation warning.

* Avoid warning on a test that tests deprecated response.text(int).

* Add pytest-asyncio to tox deps.

* Run the coroutine returned by AsyncioServer.close.

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-03-28 11:43:14 -07:00
L. Kärkkäinen
120f0262f7
Fix Ctrl+C and tests on Windows. (#1808)
* Fix Ctrl+C on Windows.

* Disable testing of a function N/A on Windows.

* Add test for coverage, avoid crash on missing _stopping.

* Initialise StreamingHTTPResponse.protocol = None

* Improved comments.

* Reduce amount of data in test_request_stream to avoid failures on Windows.

* The Windows test doesn't work on Windows :(

* Use port numbers more likely to be free than 8000.

* Disable the other signal tests on Windows as well.

* Windows doesn't properly support SO_REUSEADDR, so that's disabled in Python, and thus rebinding fails. For successful testing, reuse port instead.

* app.run argument handling: added server kwargs (alike create_server), added warning on extra kwargs, made auto_reload explicit argument. Another go at Windows tests

* Revert "app.run argument handling: added server kwargs (alike create_server), added warning on extra kwargs, made auto_reload explicit argument. Another go at Windows tests"

This reverts commit dc5d682448.

* Use random test server port on most tests. Should avoid port/addr reuse issues.

* Another test to random port instead of 8000.

* Fix deprecation warnings about missing name on Sanic() in tests.

* Linter and typing

* Increase test coverage

* Rewrite test for ctrlc_windows_workaround

* py36 compat

* py36 compat

* py36 compat

* Don't rely on loop internals but add a stopping flag to app.

* App may be restarted.

* py36 compat

* Linter

* Add a constant for OS checking.

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-03-25 21:42:46 -07:00
L. Kärkkäinen
4db075ffc1
Streaming migration for 20.3 release (#1800)
* Compatibility and deprecations for Sanic 20.3 in preparation of the streaming branch.

* Add test for new API.

* isort tests

* More coverage

* json takes str, not bytes

Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-03-24 10:11:09 -07:00
Kevin Guillaumond
60b4efad67
Update config docs to match DEFAULT_CONFIG (#1803)
* Set REAL_IP_HEADER's default value to "X-Real-IP"

* Update config instead
2020-03-14 08:57:39 -07:00
L. Kärkkäinen
319388d78b
Remove the old request context API deprecated in 19.9. Use request.ctx instead. (#1801)
Co-authored-by: L. Kärkkäinen <tronic@users.noreply.github.com>
2020-03-05 21:40:46 -08:00
Subham Roy
ce71514d71
bump httpx dependency version to 0.11.1 (#1794) 2020-03-01 11:42:11 -08:00
L. Kärkkäinen
7833d70d9e
Allow multiple workers on MacOS with Python 3.8. Fallback to single worker on Windows until pickling can be fixed. (#1798) 2020-03-01 11:41:09 -08:00
Mykhailo Yusko
16961fab9d
Use f-strings instead of str.format() (#1793) 2020-02-25 14:01:13 -06:00
L. Kärkkäinen
861e87347a
Fix #1788 incorrect url_for for routes with hosts, added tests. (#1789)
* Fix #1788 incorrect url_for for routes with hosts, added tests.

* Linter

* Remove debug print
2020-02-21 09:10:22 -08:00
Tim Gates
91f6abaa81
Fix simple typo: viewes -> views (#1783)
Closes #1782
2020-02-17 10:16:58 -06:00
Eli Uriegas
d380b52f9a
Merge pull request #1784 from gdub/changelog_correction
Corrected changelog for docs move of MD to RST (#1691).
2020-02-15 17:09:41 -08:00
Gary Wilson Jr
d656a06a19 Corrected changelog for docs move of MD to RST (#1691). 2020-02-11 11:45:56 -06:00
Adam Hopkins
258dbee3b9
Py38 tox env (#1752)
* Set version

Set version

* Add Python 3.8 to tests and package classifiers

Add Python3.8 to Appveyor config
2020-02-05 13:17:55 -06:00
Sudeep Mandal
6b9287b076
Update README re: experimental support for Windows (#1778)
As mentioned in #1517 , Windows support is "experimental" and does not currently support multiple workers.
2020-02-03 10:27:56 -06:00
L. Kärkkäinen
dac0514441 Code cleanup in file responses (#1769)
* Code cleanup in file responses.

* Lint
2020-01-26 22:08:34 -08:00
L. Kärkkäinen
bffdb3b5c2 More robust response datatype handling (#1674)
* HTTP1 header formatting moved to headers.format_headers and rewritten.

- New implementation is one line of code and twice faster than the old one.
- Whole header block encoded to UTF-8 in one pass.
- No longer supports custom encode method on header values.
- Cookie objects now have __str__ in addition to encode, to work with this.

* Linter

* format_http1_response

* Replace encode_body with faster implementation based on f-string.

Benchmarks:

def encode_body(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()

def encode_body2(data):
    return f"{data}".encode()

def encode_body3(data):
    return str(data).encode()

data_str, data_int = "foo", 123

%timeit encode_body(data_int)
928 ns ± 2.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit encode_body2(data_int)
280 ns ± 2.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit encode_body3(data_int)
387 ns ± 1.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit encode_body(data_str)
202 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit encode_body2(data_str)
197 ns ± 0.507 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit encode_body3(data_str)
313 ns ± 1.28 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

* Wtf linter

* Content-type fixes.

* Body encoding sanitation, first pass.
- body/data type autodetection fixed.
- do not repr(body).encode() bytes-ish values.
- support __html__ and _repr_html_ in sanic.response.html().

* <any type>-to-str response autoconversion limited to sanic.response.text() only.

* Workaround MyPy issue.

* Add an empty line to make isort happy.

* Add html test for __html__ and _repr_html_.

* Remove StreamingHTTPResponse.get_headers helper function.

* Add back HTTPResponse Keep-Alive removed by earlier merge or something.

* Revert "Remove StreamingHTTPResponse.get_headers helper function."

Tests depend on this otherwise useless function.

This reverts commit 9651e6ae01.

* Add deprecation warnings; instead of assert for wrong HTTP version, and for non-string response.text.

* Add back missing import.

* Avoid duplicate response header tweaking code.

* Linter errors
2020-01-20 10:34:32 -06:00
L. Kärkkäinen
e908ca8cef [Trio] Quick fixes to make Sanic usable on hypercorn -k trio myweb.app (#1767)
* Quick fixes to make Sanic usable on hypercorn -k trio myweb.app

* Quick'n dirty compatibility and autodetection of hypercorn trio mode.

* mypy ignore for aiofiles/trio.

* lint
2020-01-20 10:29:06 -06:00
Ashley Sommer
801595e24a Add server.start_serving and server.serve_forever to AsyncioServer proxy object, to match asyncio-python3.7 example doc, fixes #1754 (#1762) 2020-01-20 09:00:48 -06:00
L. Kärkkäinen
ba9b432993 No tracebacks on normal errors and prettier error pages (#1768)
* Default error handler now only logs traceback on 500 errors and all responses are HTML formatted.

* Tests passing.

* Ability to flag any exception object with self.quiet = True following @ashleysommer suggestion.

* Refactor HTML formatting into errorpages.py. String escapes for debug tracebacks.

* Remove extra includes

* Auto-set quiet flag also when decorator is used.

* Cleanup, make error pages (probably) HTML5-compliant and similar for debug and non-debug modes.

* Fix lookup of non-existant status codes

* No logging of 503 errors after all.

* lint
2020-01-20 08:58:14 -06:00
Ashley Sommer
b565072ed9 Allow route decorators to stack up again (#1764)
* Allow route decorators to stack up without causing a function signature inspection crash
Fix #1742

* Apply fix to @websocket routes docorator too
Add test for double-stacked websocket decorator
remove introduction of new variable in route wrapper, extend routes in-place.
Add explanation of why a handler will be a tuple in the case of a double-stacked route decorator
2020-01-10 21:50:16 -08:00
Ashley Sommer
caa1b4d69b Fix dangling comma in arguments list for HTTPResponse in response.empty() (#1761)
* Fix dangling comma arguments list for HTTPResponse in response.empty()

* Found another black error, including another dangling comma
2020-01-10 19:58:01 -08:00
Liran Nuna
865536c5c4 Simplify status code to text lookup (#1738) 2020-01-10 08:43:44 -06:00
Eli Uriegas
784d5cce52
Merge pull request #1755 from Lagicrus/empty-response
Update docs
2020-01-04 19:15:24 -08:00
Lagicrus
0fd08c6114 Update response.rst 2020-01-04 21:26:03 +00:00
Lagicrus
cd779b6e4f Update response.rst 2020-01-04 19:51:50 +00:00
好风
3430907046 fix 1748 : Drop DeprecationWarning in python 3.8 (#1750)
https://github.com/huge-success/sanic/issues/1748
2020-01-03 20:20:42 -08:00
Eli Uriegas
2f776eba85
Release v19.12.0 (#1747)
Release v19.12.0
2020-01-03 11:50:33 -08:00
Adam Hopkins
b9cd2ed1f1
Merge pull request #1751 from huge-success/master
Move Release into LTS Branch
2020-01-02 23:45:08 +02:00
Adam Hopkins
850b63f642
Merge pull request #1743 from eric-nieuwland/master
Forgotten slot
2020-01-02 23:17:35 +02:00
Eric Nieuwland
a9c669f17b
Forgotten slot
Crashes the server at __init__() time
2019-12-28 15:21:27 +01:00
Stephen Sadowski
075affec23
Release v19.12.0 (#1740)
* Bumping up version from 19.9.0 to 19.12.0

* Pipfile crud removed
2019-12-27 07:10:46 -06:00
Stephen Sadowski
3411a12c40 Pipfile crud removed 2019-12-26 18:50:52 -06:00
Stephen Sadowski
28899356c8 Bumping up version from 19.12.0 to 19.12.0 2019-12-26 18:47:56 -06:00
Eli Uriegas
2b5f8d20de ci: Add python nightlies to test matrix (#1710)
Signed-off-by: Eli Uriegas <seemethere101@gmail.com>
2019-12-25 16:50:31 -08:00
Adam Hopkins
243f240e5f Add RFC labels to stale exclusion list (#1737) 2019-12-23 17:31:33 -06:00
L. Kärkkäinen
0a25868a86 HTTP1 header formatting moved to headers.format_headers and rewritten. (#1669)
* HTTP1 header formatting moved to headers.format_headers and rewritten.

- New implementation is one line of code and twice faster than the old one.
- Whole header block encoded to UTF-8 in one pass.
- No longer supports custom encode method on header values.
- Cookie objects now have __str__ in addition to encode, to work with this.

* Add an import missed in merge.
2019-12-23 17:30:45 -06:00
Liran Nuna
fccbc1adc4 Allow empty body without Content-Type; Introduce response.empty() (#1736) 2019-12-23 14:16:53 -06:00
Adam Hopkins
3f6a978328 Swap out requests-async for httpx (#1728)
* Begin swap of requests-async for httpx

* Finalize httpx adoption and resolve tests

Resolve linting and formatting

* Remove documentation references to requests-async in favor of httpx
2019-12-20 19:23:52 -08:00
Harsha Narayana
a6077a1790 GIT-37: fix blueprint middleware application (#1690)
* GIT-37: fix blueprint middleware application

1. If you register a middleware via `@blueprint.middleware` then it will apply only to the routes defined by the blueprint.
2. If you register a middleware via `@blueprint_group.middleware` then it will apply to all blueprint based routes that are part of the group.
3. If you define a middleware via `@app.middleware` then it will be applied on all available routes

Fixes #37

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* GIT-37: add changelog

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-12-20 10:01:04 -06:00
Eli Uriegas
179a07942e
Merge pull request #1734 from seemethere/testing_host
testing: Add host argument to SanicTestClient
2019-12-18 16:50:59 -08:00
Eli Uriegas
c3aed01096
testing: Add host argument to SanicTestClient
Adds the ability to specify a host argument when using the
SanicTestClient.

Signed-off-by: Eli Uriegas <eliuriegas@fb.com>
2019-12-18 16:31:38 -08:00
7
028778ed56 Fix #1714 (#1716)
* fix abort call errors out when calling inside stream handler

* handle pending task properly after cleanup
2019-12-16 09:46:18 -06:00
Adam Bannister
2d72874b0b Add return type to Sanic.create_server for type hinting and docs (#1724)
* add type hint and doc when create_server returns AsyncioServer

* fix linting
2019-12-12 10:25:13 -06:00
Seonghyeon Kim
4c45d30400 FIX: invalid rst syntax (#1727) 2019-12-12 10:24:11 -06:00
Junyeong Jeong
ecbe5c839f pass request_buffer_queue_size argument to HttpProtocol (#1717)
* pass request_buffer_queue_size argument to HttpProtocol

* fix to use simultaneously only one task to put body to stream buffer

* add a test code for REQUEST_BUFFER_QUEUE_SIZE
2019-11-21 09:33:50 -06:00
Vinícius Dantas
ed1f367a8a Reduce nesting for the sample authentication decorator (#1715)
* Reduce nesting for the sample authentication decorator

* Add missing decorator argument
2019-11-14 14:57:41 -06:00
Lagicrus
a4185a0ba7 Doc rework (#1698)
* blueprints

* class_based_views

* config

* decorators

* deploying

* exceptions

* extensions

* getting_started

* middleware

* request_data

* response

* routing

* static_files

* streaming

* testing

* versioning

* Fix bug and links

* spelling mistakes

* Bug fixes and minor tweaks

* Create 1691.doc.rst

* Bug fixes and tweaks

Co-Authored-By: Harsha Narayana <harsha2k4@gmail.com>
2019-11-14 14:11:38 -06:00
Harsha Narayana
e81a8ce073 fix SERVER_NAME enforcement in url_for and request.args documentation (#1708)
* 🐛 fix SERVER_NAME enforcement in url_for

fixes #1707

* 💡 add additional documentation for using request.args

fixes #1704

*  add additional test to check url_for without SERVER_NAME

* 📝 add changelog for fixes
2019-11-01 10:32:49 -07:00
Harsha Narayana
e506c89304 deprecate None value support for app name (#1705)
*  deprecate None value support for app name

* 🚨 cleanup linter issues across the codebase
2019-10-23 09:12:20 -07:00
Bruno Oliveira
fcdc9c83c5 Add 'python_requires' key to setup.py (#1701)
This key is important so that `pip` doesn't try to install `sanic` in unsupported Python versions:

https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires
2019-10-14 21:17:05 -07:00
7
be0d539746 19.9.0 release (#1699) 2019-10-12 09:54:47 -05:00
Lagicrus
4f9739ed2c Update helpers.py (#1693) 2019-10-08 16:29:03 -07:00
Lagicrus
0df37fa653 Update websocket.rst (#1694) 2019-10-08 16:28:09 -07:00
Eli Uriegas
3e932505b0
Bump up pytest version for fixing ci build (#1689)
Bump up pytest version for fixing ci build
2019-10-08 14:32:38 -07:00
Yun Xu
01be691936 misc: bump up pytest version for fixing ci build 2019-10-07 11:41:44 -07:00
Simon
134c414fe5 Support websockets 8.x as well as 7.x (#1687)
Sanic currently requires websockets 7.x, but it's straightforward to
also support the more recent 8.x.
2019-10-01 23:03:09 -07:00
L. Kärkkäinen
c54a8b10bb Implement dict-like API on request objects for custom data. (#1666)
* Implement dict-like API on request objects for custom data.
* Updated docs about custom_context.
2019-09-26 14:11:31 -07:00
Vinícius Dantas
6fc3381229 Add a type checking pipeline (#1682)
* Integrate with mypy
2019-09-22 13:55:36 -07:00
Ashley Sommer
927c0e082e Fix tests for multiprocessing pickle app and pickle blueprint (#1680)
The old tests were not quite checking for the right thing.
Fixing the test does not change Sanic code, expose any bugs, or fix any bugs.
2019-09-18 10:22:24 -07:00
Ashley Sommer
7674e917e4 Fixes "after_server_start" when using return_asyncio_server. (#1676)
* Fixes ability to trigger "after_server_start", "before_server_stop", "after_server_stop" server events when using app.create_server to start your own asyncio_server
See example file run_async_advanced for a full example

* Fix a missing method on AsyncServer that some tests need
Add a tiny bit more documentation in-code
Change name of AsyncServerCoro to AsyncioServer
2019-09-16 10:59:16 -07:00
ku-mu
e13f42c17b Fix docstring style in Sanic.register_listener (#1678)
* Fix docstring style: google -> reST
2019-09-16 10:27:22 -07:00
Lagicrus
b7d4121586 Update static_files.md (#1672) 2019-09-11 14:37:14 -07:00
L. Kärkkäinen
fbcd4b9767 Sanic does not support Python 3.5 and won't need this code. (#1670)
* imports code cleanup as we dropping python3.5 support
2019-09-08 14:08:34 -07:00
7
17c5e28727
Merge pull request #1665 from snguyenthanh/fix-changelog-link
doc: fix the link to CHANGELOG in README.rst
2019-09-06 11:07:41 -07:00
Son
e62b29ca44 Fix link to CHANGELOG in README.rst 2019-09-02 21:51:45 +08:00
L. Kärkkäinen
1e4b1c4d1a Forwarded headers and otherwise improved proxy handling (#1638)
* Added support for HTTP Forwarded header and combined parsing of other proxy headers.

- Accessible via request.forwarded that tries parse_forwarded and then parse_xforwarded
- parse_forwarded uses the Forwarded header, if config.FORWARDED_SECRET is provided and a matching header field is found
- parse_xforwarded uses X-Real-IP and X-Forwarded-* much alike the existing implementation
- This commit does not change existing request properties that still use the old code and won't make use of Forwarded headers.

* Use req.forwarded in req properties server_name, server_port, scheme and remote_addr.

X-Scheme handling moved to parse_xforwarded.

* Cleanup and fix req.server_port; no longer reports socket port if any forwards headers are used.

* Update docstrings to incidate that forwarded header is used first.

* Remove testing function.

* Fix tests and linting.

- One test removed due to change of semantics - no socket port will be used if any forwarded headers are in effect.
- Other tests augmented with X-Forwarded-For, to allow the header being tested take effect (shouldn't affect old implementation).

* Try to workaround buggy tools complaining about incorrect ordering of imports.

* Cleanup forwarded processing, add comments. secret is now also returned.

* Added tests, fixed quoted string handling, cleanup.

* Further tests for full coverage.

* Try'n make linter happy.

* Add support for multiple Forwarded headers. Unify parse_forwarded parameters with parse_xforwarded.

* Implement multiple headers support for X-Forwarded-For.

- Previously only the first header was used, so this BUGFIX may affect functionality.

* Bugfix for request.server_name: strip port and other parts.

- request.server_name docs claim that it returns the hostname only (no port).
- config.SERVER_NAME may be full URL, so strip scheme, port and path
- HTTP Host and consequently forwarded Host may include port number, so
  strip that also for forwarded hosts (previously only done for HTTP Host).
- Possible performance benefit of limiting to one split.

* Fallback to app.url_for and let it handle SERVER_NAME if defined (until a proper solution is implemented).

* Revise previous commit. Only fallback for full URL SERVER_NAMEs; allows host to be defined and proxied information still being used.

* Heil lintnazi.

* Modify testcase not to use underscores in URLs. Use hyphens which the spec allows for.

* Forwarded and Host header parsing improved.

- request.forwarded lowercases hosts, separates host:port into their own fields and lowercases addresses
- forwarded.parse_host helper function added and used for parsing all host-style headers (IPv6 cannot be simply split(":")).
- more tests fixed not to use underscores in hosts as those are no longer accepted and lead to the field being rejected

* Fixed typo in docstring.

* Added IPv6 address tests for Host header.

* Fix regex.

* Further tests and stricter forwarded handling.

* Fix merge commit

* Linter

* Linter

* Linter

* Add  to avoid re-using the  variable. Make a few raw strings non-raw.

* Remove unnecessary or

* Updated docs (work in progress).

* Enable REAL_IP_HEADER parsing irregardless of PROXIES_COUNT setting.

- Also cleanup and added comments

* New defaults for PROXIES_COUNT and REAL_IP_HEADER, updated tests.

* Remove support for PROXIES_COUNT=-1.

* Linter errors.

- This is getting ridiculous: cannot fit an URL on one line, linter requires
  splitting the string literal!

* Add support for by=_proxySecret, updated docs, updated tests.

* Forwarded headers' semantics tuning.

- Forwarded host is now preserved in original format
- request.host now returns a forwarded host if available, else the Host header
- Forwarded options are preserved in original order, and later keys override earlier ones
- Forwarded path is automatically URL-unquoted
- Forwarded 'by' and 'for' are omitted if their value is unknown
- Tests modified accordingly
- Cleanup and improved documentation

* Add ASGI test.

* Linter

* Linter #2
2019-09-02 08:50:56 -05:00
Subham Roy
ae91852cd5 check for already set asyncio event loop policy (#1637)
* check for already set asyncio event loop policy

* fix linting warning
2019-08-28 11:30:23 -05:00
L. Kärkkäinen
2011f3a0b2 PEP 594 has cgi module scheduled for deprecation in Python 3.8 (#1649)
* PEP 594 has cgi module scheduled for deprecation in Python 3.8. Reimplement
cgi.parse_header in Sanic. The new implementation is much faster than either
cgi.parse_header or equivalent werkzeug.parse_options_header, and unlike the
two, handles also quoted values with semicolons or \" in them.

* Fix string escape.

* Useless linter complaints.

* More linter issues

* Add return type hint.

* Do not support quoted-pair escapes.

- Improved documentation and renamed the function more aptly as it only seems
  to apply to content-type and content-disposition headers.

* Unquote filenames also in normal mode.

* Add tests for headers. Adapted from CPython parse_header tests with changes on the final test.

* Linter

* Revert "Unquote filenames also in normal mode."

This reverts commit bf0d502bcd.

* Improved parse_content_header and added tests with Firefox and Chrome.

- Unescaping of quotes moved to parse_content_header because it affects all fields,
  not just filenames.
- It is impossible to handle all cases correctly but the current heuristics should
  suffice well for typical cases and beyond.
- Added comparisons with cgi.parse_header and werkzeug.parse_options_header.

* Updated comments as well.
2019-08-27 08:30:23 -05:00
7
228a31ee0a
Merge pull request #1657 from huge-success/release-19.6.3
release: 19.6.3
2019-08-21 23:00:51 -07:00
Yun Xu
8bf2bdff74 Bumping up version from 19.6.2 to 19.6.3 2019-08-20 18:51:17 -07:00
7
41862eca61
Merge pull request #1654 from huge-success/asgi-content-type
Add content-type headers in response in ASGI mode
2019-08-13 12:30:40 -07:00
Yun Xu
21307b397b release: 19.6.3 2019-08-13 10:03:08 -07:00
7
3f9c94ba4a
Merge pull request #1635 from huge-success/upgrade-websockets
Upgrade websockets, resolve incompatible issue between multidict and websockets
2019-08-12 10:48:56 -07:00
Adam Hopkins
aa270d3ac2 Add content-type headers in response in ASGI mode 2019-08-11 11:29:08 +03:00
7
a15d9552c4
Merge pull request #1632 from harshanarayana/feature/GIT-1631-Enable_Towncrier
feature: GIT-1631 enable towncrier
2019-08-06 08:33:10 -07:00
7
2363c0653e
Merge pull request #1640 from Tronic/sockaddrfix
Fix server crash on request.server_port when bound to IPv6.
2019-07-25 00:10:56 -07:00
Harsha Narayana
651c98d19a
fix: #1631: add ignore file to ensure empty changelog dir is retained
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-24 05:39:20 +05:30
Harsha Narayana
c1a7e0e3cd
feat: #1631: enable change log as part of release script
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-24 05:32:00 +05:30
Harsha Narayana
80b32d0c71
feat: #1631: enable make command to support settings up release
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-24 05:03:04 +05:30
Harsha Narayana
3842eb36fd
fix: #1631: fix pyproject toml indentation
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-24 04:28:11 +05:30
L. Kärkkäinen
7c7bedfa5d Fix server crash on request.server_port when bound to IPv6.
If no X-Forwarded-Port nor Host headers are present, Sanic uses "sockname"
to determine the port. This expected (host, port) tuple to be returned but
for IPv6 a 4-tuple is returned instead. Changed code so that port is picked
up in either case. Handling of "peername" was already correct in this regard.

_get_address and server_port both still return incorrect data or crash for
other socket types (e.g unix). Socket type should checked before any queries.
2019-07-22 15:32:57 +03:00
Yun Xu
5dafa9a170 bugfix: replace CIMultiDict with compat.Header in all places 2019-07-18 20:11:25 -07:00
Yun Xu
b397637bb9 bugfix: fix incompatible api between multidict and websockets, and bump up websockets version to match uvicorn 2019-07-18 19:57:17 -07:00
Harsha Narayana
95a0b2db2c
fix: #1631: move pyproject.toml to avoid PEP 517 conflict 2019-07-14 14:26:22 +05:30
Harsha Narayana
83864f890a
fix: #1631: add common contribution guidelines and towncrier detail to contribution guides
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-13 21:48:34 +05:30
Harsha Narayana
a019ff61e3
fix: #1631: linter fix and tox platform selector
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-13 21:48:26 +05:30
Harsha Narayana
b3ada6308b
fix: #1631: add doc test for travis CI
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-13 21:48:16 +05:30
Harsha Narayana
4e50295bf0
fix: #1631: add tox test support for documentation
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-13 21:48:06 +05:30
Harsha Narayana
32eb8abb63
fix: #1631: add towncrier support and fix documentation warnings
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-13 21:47:48 +05:30
7
84b41123f2
Merge pull request #1625 from harshanarayana/fix/GIT-1623-Cookie_Handling
fix: GIT-1623: handle cookie duplication and serialization issue
2019-07-10 21:35:35 -07:00
Harsha Narayana
23f2d33394
fix: GIT-1623: fix dict initalization for empty case
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-11 06:38:55 +05:30
Harsha Narayana
97f288a534
fix: GIT-1623: handle cookie duplication and serialization issue
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-07-08 13:03:33 +05:30
Adam Hopkins
68d5039c5f
Merge pull request #1624 from huge-success/release-19-6-2
19.6.2 release
2019-07-07 05:04:23 +03:00
Yun Xu
9d07988d75 19.6.2 release 2019-07-06 18:05:44 -07:00
7
1eaa2e3a5f
Merge pull request #1614 from huge-success/asgi-custom-request
Add custom request support to ASGI mode; fix a couple tests
2019-07-06 11:47:58 -07:00
Yun Xu
c7f2399ded remove commented code 2019-07-06 11:34:22 -07:00
7
650ab61c2e
Merge pull request #1619 from huge-success/abc-fix
Resolve deprecation notice for import of an ABC from collections module
2019-07-04 15:07:53 -07:00
Lagicrus
b7df86e7dd Updated routing docs (#1620)
* Updated routing docs

Updated routing docs to show all supported types as defined within 3685b4de85/sanic/router.py (L18)
Added example code for all examples besides regex
Added examples of queries that work with that type and ones that would not

* Tweak to call out string not str

Related to https://github.com/huge-success/sanic/pull/1620#discussion_r300120962

* Changed to using code comments to achieve a mono space like display

To address https://github.com/huge-success/sanic/pull/1620#discussion_r300120726

* Adjusted to list

Following https://github.com/huge-success/sanic/pull/1620#discussion_r300120726
2019-07-04 07:14:10 -05:00
BananaWanted
72b445621b Respect X-Forward-* headers and generate correct URLs in url_for (#1465)
* handle forwarded address in request

* added test cases

* Fix lint errors

* Fix uncovered code branch

* Update docstrings

* Update documents

* fix import order
2019-07-04 07:13:43 -05:00
Adam Hopkins
ba0e9baffa Resolve deprecation notice for import of an ABC from collections module 2019-07-03 09:39:38 +03:00
Adam Hopkins
503622438a
Merge pull request #1617 from newAM/patch-2
Fix a minor typo in websocket.rst.
2019-07-01 09:37:40 +03:00
Alex
d5e9aae425
Fix a minor typo in websocket.rst. 2019-06-30 22:11:02 -07:00
Adam Hopkins
a2666a2b8a Add custom request support to ASGI mode; fix a couple tests
Undo change to request stream test
2019-06-24 22:59:23 +03:00
7
966b05b47e
Merge pull request #1612 from c-goosen/bandit_security_static_analysis
Add bandit code static analyzer for security.
2019-06-24 10:05:20 -07:00
Christo Goosen
78fe97b9cb Add bandit code static analyzer for security, some false positives removed with #nosec.
Bandit is a python package for staticly scanning code for security issues.
* Added to tox.ini
* Added to setup.py
* Added to .travis.yml

As part of CI/CD pipeline
2019-06-24 09:53:29 +02:00
7
d2094fed38
Merge pull request #1607 from huge-success/doc-changelog
Changelog for 19.6.0 release
2019-06-21 09:42:12 -07:00
Yun Xu
e2d65ba57c fix readthedoc changelog page 2019-06-20 22:35:47 -07:00
Yun Xu
c9d8ab4b27 release: add 19.6.0 standard release changelog 2019-06-20 22:35:26 -07:00
7
891f99d71d
Merge pull request #1475 from tomchristie/asgi-refactor-attempt
ASGI refactoring attempt
2019-06-20 16:33:44 -07:00
Adam Hopkins
3f47fa9f99 Specify websockets version 2019-06-19 00:40:44 +03:00
Adam Hopkins
b1c23fdbaa Increase testing coverage for ASGI
Beautify

Specify websockets version
2019-06-19 00:38:58 +03:00
Adam Hopkins
62e0e5b9ec Increase testing coverage for ASGI
Beautify
2019-06-19 00:19:40 +03:00
Adam Hopkins
fb61834a2e Add ASGI documentation 2019-06-18 09:57:42 +03:00
7
8fbbe94fe1
Merge pull request #1436 from jotagesales/config_from_object_string
Config from object string
2019-06-16 16:58:43 -07:00
Adam Hopkins
ab706dda7d Resolve linting issues with imports 2019-06-11 11:21:37 +03:00
Adam Hopkins
b2d4132a14
Merge branch 'master' into asgi-refactor-attempt 2019-06-11 11:11:32 +03:00
7
322cf89c92
Merge pull request #1605 from GTedHa/fix_typo/request_data_md
Fix typo in request_data.md, docs.
2019-06-10 20:20:12 -07:00
G.Ted
09acd64ba1 Fix typo in request_data.md, docs. 2019-06-11 11:09:29 +09:00
Eli Uriegas
072fcfe03e
Fix #1587: add support for handling Expect Header (#1600)
Fix #1587: add support for handling Expect Header
2019-06-10 14:45:37 -07:00
Harsha Narayana
13079c6e30 GIT-1591 Strict Slashes behavior fix (#1594)
* fix: GIT-1591: fix strict_slashes option inheriting behavior

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* doc: GIT-1591: add documentation exlaining the strict_slashes behavior

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* fix: GIT-1591: fix deprecated for test_client

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-06-06 07:21:58 -05:00
Yun Xu
1b1a51c1bb minor: fix typo in error msg 2019-06-04 10:37:03 -07:00
Yun Xu
39d134994d minor: address pr feedbacks, small refactoring and fix 2019-06-04 10:25:32 -07:00
Adam Hopkins
5f9e98554f Run black and manually break up some text lines to correct linting 2019-06-04 13:26:05 +03:00
Adam Hopkins
0d9a21718f Run black and manually break up some text lines to correct linting 2019-06-04 13:18:05 +03:00
Adam Hopkins
daf42c5f43 Add placement of before_server_start and after_server_stop 2019-06-04 12:59:15 +03:00
Adam Hopkins
3685b4de85 Lifespan and code cleanup 2019-06-04 10:58:00 +03:00
Yun Xu
2631f10c5e lint: fix isort and flake8 complains 2019-06-03 22:12:10 -07:00
Yun Xu
f21db60859 fix: handle expect header 2019-06-03 22:08:24 -07:00
Adam Hopkins
c15158224b Set testing.PORT on all app.create_server() in tests (#1593) 2019-05-30 09:10:00 -05:00
Adam Hopkins
a57c14c70b Add requests-async as a hard requirement. See #1592 (#1595) 2019-05-28 08:30:07 -05:00
Adam Hopkins
bb2bd2fe53 Point extensions page to awesome-sanic repo (#1596) 2019-05-28 08:13:12 -05:00
Adam Hopkins
aebe2b5809
Merge branch 'master' into asgi-refactor-attempt 2019-05-27 21:03:23 +03:00
Adam Hopkins
9172399b8c Implement ASGI lifespan events to match Sanic listeners 2019-05-27 12:33:25 +03:00
Adam Hopkins
22c0d97783 Streaming responses 2019-05-27 02:11:52 +03:00
Adam Hopkins
3ead529693 Setup streaming on ASGI 2019-05-27 00:57:50 +03:00
7
e36f398aa6
Merge pull request #1590 from huge-success/security-md
Create SECURITY.md
2019-05-23 17:40:19 -07:00
Adam Hopkins
18cd4caf70
Create SECURITY.md 2019-05-23 23:58:15 +03:00
7
80df45ba6d
Merge pull request #1588 from huge-success/prepare-19.6.0
Prepare 19.6.0
2019-05-22 16:32:36 -07:00
Yun Xu
16d262e3e5 release: v19.6.0 2019-05-22 15:51:56 -07:00
Harsha Narayana
83e3d4ca1f doc: GIT-1582: add fedora package dependency
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-05-22 15:51:17 -07:00
zach valenta
1c9141bd5d fix typo 2019-05-22 15:51:17 -07:00
Yun Xu
1b984422db add help wanted in stale.yml 2019-05-22 15:51:17 -07:00
Adam Hopkins
b6453e9fac Update stale.yml 2019-05-22 15:51:17 -07:00
Adam Hopkins
7b8e3624b8 Prepare initial websocket support 2019-05-22 01:42:19 +03:00
Adam Hopkins
8a56da84e6 Create SanicASGITestClient and refactor ASGI methods 2019-05-21 19:30:55 +03:00
7
14a00490e2
Merge pull request #1585 from harshanarayana/fix/GIT-1582-Fix_Install_Documentation
doc: GIT-1582: add fedora package dependency
2019-05-19 18:56:20 -07:00
Harsha Narayana
29bf967a7e
doc: GIT-1582: add fedora package dependency
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-05-20 06:46:18 +05:30
7
eeb79f2587
Merge pull request #1583 from zachvalenta/patch-1
fix typo
2019-05-18 15:56:09 -07:00
zach valenta
6d1741694d
fix typo 2019-05-18 15:05:03 -04:00
7
746dccf8f9
Merge pull request #1575 from huge-success/add-necessary-stale
Update stale.yml
2019-05-18 12:00:35 -07:00
Yun Xu
28a897e599 add help wanted in stale.yml 2019-05-18 11:02:46 -07:00
7
21ebf6d777
Merge pull request #1581 from huge-success/fix-build-time
Fix build time
2019-05-17 13:45:36 -07:00
Yun Xu
a2dbbb25a1 add try/finally block for always clean up resources 2019-05-17 00:25:46 -07:00
Yun Xu
2a64dabe82 fix request_timeout and request_streaming tests 2019-05-17 00:22:34 -07:00
Yun Xu
046ca6eaf1 fix unit tests due to dependency upgrade 2019-05-16 22:44:46 -07:00
Yun Xu
3661afa461 bump request-async version for fixing build time issue 2019-05-16 08:56:25 -07:00
7
12f1985375
Merge pull request #1576 from huge-success/conda-docs
Add conda install and download stats
2019-05-15 22:42:25 -07:00
Adam Hopkins
bb800c9db8 Add conda install and download stats 2019-05-15 09:54:02 +03:00
Adam Hopkins
262048df95
Update stale.yml 2019-05-15 07:46:58 +03:00
7
9255eb6902
Merge pull request #1573 from huge-success/doc-fix-for-35
Remove Python 3.5 references in docs
2019-05-14 09:15:52 -07:00
7
56d386f152
Merge pull request #1571 from huge-success/stale
Add stale to repo
2019-05-14 09:15:16 -07:00
Adam Hopkins
193dbe89cd Remove Python 3.5 references in docs 2019-05-14 11:21:24 +03:00
Adam Hopkins
601e158ffe Add stale to repo 2019-05-14 10:50:34 +03:00
7
42b9fa3779
Merge pull request #1570 from 5onic/FIX-add-missed-documentation
Added documentation for missed arguments
2019-05-12 21:53:30 -07:00
Adam Hopkins
4767a67acd Merge branch 'master' into asgi-refactor-attempt 2019-05-12 22:57:02 +03:00
Mike Yusko
4c8cc84b64 Delete unnecessary whitespace 2019-05-12 15:36:13 +03:00
Mike Yusko
c5efc4b64b Added documentation for missed arguments 2019-05-12 15:32:34 +03:00
7
25e2151fdf
Merge pull request #1568 from huge-success/deprecate-route-removal
deprecation: deprecate the use of remove_route
2019-05-11 02:24:11 +08:00
7
cb10e261a2
Merge pull request #1567 from huge-success/fix-readthedoc-build
minor: fix readthedoc build
2019-05-10 12:16:09 +08:00
Yun Xu
bd89c7f269 fix lint issue 2019-05-09 21:14:27 -07:00
Yun Xu
d4ef151cc4 deprecation: deprecate the use of remove_route 2019-05-09 20:52:24 -07:00
7
669cfa33df
Merge pull request #1566 from ketan86/developer-guide-improvements
developer guide enhancements.
2019-05-09 04:14:21 +08:00
7
f70ab2f68a
Merge pull request #1565 from ketan86/1564-processes-initialization-fix
1564 - Moving `processes` variable intialization before `sig_handler`.
2019-05-09 04:13:29 +08:00
Ketan Patel
900020ddc9 developer guide enhancements. 2019-05-08 00:40:40 -07:00
Ketan Patel
ec428135ce 1564 - Moving processes variable intialization before sig_handler. 2019-05-07 22:38:29 -07:00
Yun Xu
8e2a1a61a5 minor: fix readthedoc build 2019-05-07 16:51:24 -07:00
Adam Hopkins
5fb8f5d3e7 Add Awesome Sanic list button (#1563) 2019-05-06 07:47:16 -05:00
Adam Hopkins
c68523150f
Merge branch 'master' into asgi-refactor-attempt 2019-05-06 12:59:56 +03:00
7
ae2b8f0056
Merge pull request #1562 from huge-success/testing-client
Testing client
2019-05-03 06:32:26 +08:00
Eli Uriegas
ef6d78c580
Allow to disable Transfer-Encoding: chunked (#1560)
Allow to disable Transfer-Encoding: chunked
2019-04-30 14:56:27 -07:00
Adam Hopkins
ccd4c9615c Create requests-async based TestClient, remove aiohttp dependency, drop Python 3.5
Update all tests to be compatible with requests-async
Cleanup testing client changes with black and isort
Remove Python 3.5 and other meta doc cleanup
rename pyproject and fix pep517 error
Add black config to tox.ini
Cleanup tests and remove aiohttp
tox.ini change for easier development commands
Remove aiohttp from changelog and requirements
Cleanup imports and Makefile
2019-04-30 15:26:06 +03:00
andreymal
7d6e60ab7d
Never use chunked transfer encoding for HTTP/1.0 2019-04-22 10:53:13 +03:00
andreymal
9615e37ef9
Add file streaming section to the streaming documentation page 2019-04-20 23:50:19 +03:00
andreymal
6be12ba773
Upadte documentation for streaming response 2019-04-20 23:38:16 +03:00
andreymal
03855d316b
Update tests for StreamingHTTPResponse 2019-04-20 22:27:10 +03:00
andreymal
9f07109616
Allow to disable Transfer-Encoding: chunked 2019-04-20 22:26:30 +03:00
7
6a4a3f617f
Merge pull request #1558 from andreymal/fix/graceful_shutdown
Fix graceful shutdown
2019-04-20 20:02:16 +08:00
Eli Uriegas
f32c9be41f
Merge pull request #1559 from andreymal/fix/pytest_behchmark_require
Add pytest-benchmark to tests_require
2019-04-19 15:52:39 -07:00
andreymal
d83d829e0a
Add pytest-benchmark to tests_require 2019-04-19 17:31:23 +03:00
andreymal
99e56ef74b
Fix broken bail_out when HttpProtocol is closed 2019-04-19 16:14:27 +03:00
andreymal
df23692802
Fix graceful shutdown (the connections set was always empty in serve function) 2019-04-19 15:58:17 +03:00
7
b68a7fe7ae doc: fix README.rst for pip installing sanic without uvloop and ujson (#1554) 2019-04-17 08:48:21 -05:00
andreymal
5c9ba189bc Add options to control the behavior of Request.remote_addr (#1539)
* Add options to control the behavior of Request.remote_addr

* Update tests for Request.remote_addr

* Update documentation for Request.remote_addr
2019-04-16 08:30:28 -05:00
7
5631a31099
Merge pull request #1553 from jrmi/master
Fix #1551 add missing parameter in create_server
2019-04-15 17:36:51 -07:00
Jeremie Pardou-Piquemal
f4bc0efc31 Fix #1551 missing parameter in create_server 2019-04-15 22:18:35 +02:00
7
53f45810ff Fix #1528 (#1549)
* assign app before handle_request so that request.app could be used in case of connection timeout

* gitignore pip-wheel-metadata/

* remove default app for request class and fix lint issue
2019-04-12 07:48:32 -05:00
7
d58151a0eb
Merge pull request #1546 from krigar1184/master
Fixed a docstring typo and simplified code a little
2019-04-11 10:37:32 -07:00
Nikita Antonenkov
de582d2fc7 Refactor the app.route decorator 2019-04-06 22:26:56 +03:00
Nikita Antonenkov
653ac7ee14 Fix app.patch decorator docstring typo 2019-04-06 22:23:50 +03:00
Zaar Hai
0b4769289a Drop dependency on disutils (#1544)
* Drop dependency on distutils

While distutils is part of stdlib, it feels odd to use distutils in main application code.

I personally use a (lean)[https://hub.docker.com/r/haizaar/python-minimal/tags] Python distribution for running my applications that does not include distutils.

* Flake8 fixes

* "black" fixes

* strtobool should actually return bool
2019-04-02 08:22:26 -05:00
Daniel Golding
3bedb223fc Add 19.03 release to changelog (#1537) 2019-03-29 10:34:13 -05:00
7
94a1720e04
Merge pull request #1541 from cakemanny/fix-number-route-accepting-invalid-float
stop number route accepting excess '.'s
2019-03-28 10:42:24 -07:00
Eli Uriegas
d0c8808340
Merge pull request #1542 from cakemanny/some-typo-fixes
Fix some typos in docs
2019-03-27 21:24:33 -07:00
cakemanny
dd32d81726 fix typos in docs 2019-03-28 01:05:39 +00:00
cakemanny
378a732968 fix expected float error message 2019-03-27 22:46:30 +00:00
cakemanny
b2e82685b4 stop number route accepting excess '.'s
We stop getting:

    ValueError: could not convert string to float: '12.34.56'

when passing 12.34.56 as a number route parameter argument.
By accepting ".12" and "12.", this is a non-breaking change. All valid
floats described by [0-9\.]+ are still accepted, just invalid ones are
now rejected.
2019-03-27 02:49:05 +00:00
andreymal
566940e052 Fix typo in CONTRIBUTING.md: [.dev] -> .[dev] (#1538) 2019-03-26 11:08:08 -05:00
Eli Uriegas
dab802fbf4
Merge pull request #1530 from seemethere/bump_19031
Bump version to 19.03.1
2019-03-22 19:48:50 -07:00
Eli Uriegas
7bca95205d Bump version to 19.03.1
Couldn't delete the release on github so we go with the next best thing
which is to just bump the patch version

Signed-off-by: Eli Uriegas <seemethere101@gmail.com>
2019-03-22 16:44:28 -07:00
Eli Uriegas
669e2ed5b0
Merge pull request #1529 from huge-success/pypi-credentials
Update PyPI credentials
2019-03-22 16:41:12 -07:00
Eli Uriegas
783eb1a6e8
Merge pull request #1527 from seemethere/bump_1903
Bump version to 19.03.0
2019-03-22 16:40:54 -07:00
Adam Hopkins
9b9599b12f Update PyPI credentials 2019-03-22 13:44:13 +02:00
Eli Uriegas
6ed0d3def7 Bump version to 19.03.0
Signed-off-by: Eli Uriegas <seemethere101@gmail.com>
2019-03-21 16:24:57 -07:00
Amit Garu
c42731a55c await keyword missing fix in response doc (#1520) 2019-03-19 07:15:28 -05:00
Sam Havens
abf8534ea9 fix typo in Asyncio example (#1510)
* fix typo

* args to kwargs
2019-03-15 12:28:15 -05:00
Moshe Zada
773a66bc5b Fix typo (#1516) 2019-03-15 11:49:18 -05:00
Harsha Narayana
269100eac1 format: fix linter issue causing travis build failures (fix #1514) (#1515)
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-03-14 12:18:47 -05:00
Serge Fedoruk
2a15583b87 add Request.not_grouped_args, deprecation warning Request.raw_args (#1476)
* add Request.not_grouped_args, deprecation warning Request.raw_args

* add 1 more test for coverage

* custom parser for Request.args and Request.query_args, some additional tests

* add docs for custom queryset parsing

* fix import sorting

* docstrings for get_query_args and get_args methods

* lost import
2019-03-14 09:04:05 -05:00
Jotagê Sales
b534df242b rename config in class in test_config 2019-03-05 14:36:54 -03:00
Jotagê Sales
734730640a added param package to relative imports 2019-03-05 01:40:17 -03:00
Jotagê Sales
bee7cfa6aa Merge branch 'master' of github.com:huge-success/sanic into config_from_object_string 2019-03-05 01:10:09 -03:00
Daniel Thorn
d5813152ab Allow sanic test client to bind to a random port (#1376) 2019-03-04 15:23:03 -06:00
Jotagê Sales
eacf78b83c Merge branch 'master' of github.com:huge-success/sanic into config_from_object_string 2019-03-04 00:37:59 -03:00
Harsha Narayana
348964fe12 Enable Middleware Support for Blueprint Groups (#1399)
* enable blueprint group middleware support

This commit will enable the users to implement a middleware at the
blueprint group level whereby enforcing the middleware automatically to
each of the available Blueprints that are part of the group.

This will eanble a simple way in which a certain set of common features
and criteria can be enforced on a Blueprint group. i.e. authentication
and authorization

This commit will address the feature request raised as part of Issue #1386

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* enable indexing of BlueprintGroup object

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* rename blueprint group file to fix spelling error

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* add documentation and additional unit tests

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* cleanup and optimize headers in unit test file

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* fix Bluprint Group iteratable method

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* add additional unit test to check StopIteration condition

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* cleanup iter protocol implemenation for blueprint group and add slots

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* fix blueprint group middleware invocation identification

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* feat: enable list behavior on blueprint group object and use append instead of properly to add blueprint to group

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-03-03 16:26:05 -06:00
Markus Lång
e5c7589fc0 Remove update_current_time refresh (#1502) 2019-03-03 11:22:26 -06:00
Ashley Sommer
4260528645 Fix the auto_reloader to work when the executable was launched with a module, rather than a script. (#1501) 2019-03-03 11:03:26 -06:00
Harsha Narayana
34fe26e51b Add Route Resolution Benchmarking to Unit Test (#1499)
* feat: add benchmark tester for route resolution and cleanup test warnings

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>

* feat: refactor sanic benchmark test util into fixtures

Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2019-02-28 08:56:41 -06:00
PWZER
8a59907319 Recognizes non-ASCII filenames in RFC 2231, and suport filename length is zero for multipart/form-data. (#1497)
* suport filename length is 0

* 1. suport filename length is zero for multipart/form-data.
2. Now recognizes non-ASCII filenames in RFC 2231, "filename*" format
3. Add some test cases in tests/test_requests.py::test_request_multipart_files.

* reformat sanic/request.py
2019-02-28 08:55:32 -06:00
7
52deebaf65
Merge pull request #1490 from chenjr0719/fix_doc_build
Fix python version in doc build
2019-02-19 16:26:56 -08:00
jacob
1e05b22fbc Fix python version in environment.yml 2019-02-18 14:02:45 +08:00
7
ab56af5d15
Merge pull request #1489 from tomchristie/patch-1
Added "databases"
2019-02-15 16:43:38 -08:00
Tom Christie
123f00eee6
Added "databases"
Adds https://github.com/encode/databases to the "Database Integration" section.
2019-02-14 13:44:18 +00:00
Mykhailo Kushchenko
42bf103269 Remove deleted repo (#1487)
https://github.com/Sniedes722/Sanic-OAuth  (Sanic-OAuth: OAuth Library for connecting to & creating your own token providers.) returns  404
2019-02-08 08:43:43 -06:00
0xflotus
c8d2a462e3 did you mean specific? (#1486) 2019-02-06 16:28:32 -06:00
Leonardo Teixeira Menezes
08794ae1cf Enforce Datetime Type for Expires on Set-Cookie (#1484)
* Enforce Datetime Type for Expires on Set-Cookie

* Fix lint issues

* Format code and improve error type

* Fix import order
2019-02-06 12:29:33 -06:00
Kevin ZHANG Qing
4f70dba935 sanic-zipkin (#1483) 2019-02-05 07:59:33 -06:00
Enda Farrell
b926a2c9b0 sanic#1480 Allow negative int/number in path (#1481)
* sanic#1480 Allow negative int/number

* Rerun ``make beautify`` on this change.
2019-02-05 07:54:48 -06:00
Jacob
52bdd1d5a2 Add stream support for bp.add_route() (#1482)
* Fix #1454

* Update doc

* Fix F632 in response.py
2019-02-05 07:47:46 -06:00
7
bc7d0f0da5
Merge pull request #1478 from chenjr0719/fix_doc_build
Upgrade setuptools version and use native docutils in doc build
2019-01-21 22:42:51 -08:00
jacob
6a8e9c9e95 Add deps based on docs extras require, Remove unnecessary deps 2019-01-22 14:05:29 +08:00
jacob
211a922f3c Upgrade setuptools version and use native docutils 2019-01-21 10:16:57 +08:00
7
2758a3ade6
Merge pull request #1472 from xxNB/dev
Remove unwanted None check for __repr__ in `Request` class
2019-01-20 14:21:57 -08:00
7
ef3c9eae73
Merge pull request #1477 from kyb3r/patch-2
Fix grammar in README.md
2019-01-20 14:21:27 -08:00
7
9cf2e1b519
Merge pull request #1470 from denismakogon/create-server
make Sanic.create_server return an asyncio.Server
2019-01-20 14:21:11 -08:00
Kyber
51c2f7a599
Use backticks 2019-01-19 20:10:44 +11:00
Kyber
5bdd046b11
Fix grammar in README.md
>  It allows usage the async and await syntax 

Doesn't make sense.
2019-01-19 20:08:47 +11:00
Tom Christie
95526a82de ASGI refactoring attempt 2019-01-18 14:50:42 +00:00
章昕
af7ad0a621 Remove unwanted None check for __repr__ in class 2019-01-17 00:24:11 +08:00
Denis Makogon
1473753d43 linter fix 2019-01-15 17:48:26 +02:00
Denis Makogon
b36bd21813 fix uvloop check 2019-01-15 17:45:47 +02:00
Denis Makogon
f8f0241c27 refactor uvloop detection in its own method 2019-01-15 17:33:53 +02:00
Denis Makogon
1af16836d4 make tests dependent on uvloop 2019-01-15 17:30:32 +02:00
Denis Makogon
757974714e skip tests if python version is not 3.7 at least 2019-01-15 17:27:41 +02:00
Denis Makogon
eed22a7a24 Fix app.create_server calls 2019-01-15 15:47:35 +02:00
Denis Makogon
0242bc999f Fix type asserting 2019-01-15 15:11:38 +02:00
Denis Makogon
b89c533818 Adding doc 2019-01-15 15:04:30 +02:00
Denis Makogon
2cb05ab865 More tests, attempting to fix CI 2019-01-15 14:52:53 +02:00
Denis Makogon
391639210e make Sanic.create_server return an asyncio.Server
- adding 2 new parameters to Sanic.create_server:
   * return_asyncio_server=False - defines whether there's
     a need to return an asyncio.Server or run it right away
   * asyncio_server_kwargs=None - for python 3.7 uvloop doesn't
     support all necessary features like "start_serving",
     so, in order to make sanic work well with asyncio from 3.7
     there's a need to introduce generic way for passing
     kwargs for "loop.create_server"

Closes: #1469
2019-01-15 13:38:47 +02:00
7
99f34c9f50
Merge pull request #1457 from huge-success/max-age-integer
enforce integer for max-age cookie
2019-01-13 13:15:10 -08:00
Raphael Deem
d418cc9950 formatting 2019-01-12 20:41:35 -08:00
Raphael Deem
6dfafb0787 test float handling 2019-01-12 20:41:35 -08:00
Raphael Deem
7067295e67 enforce integer for max-age cookie 2019-01-12 20:41:35 -08:00
Eli Uriegas
2af229eb1a
Merge pull request #1445 from huge-success/r0fls-977
add handler name to request as endpoint
2019-01-08 16:12:25 -08:00
7
8dd8e9916e upgrade pytest version that compatible with pytest-cov, fixes some caplog unit tests (#1464) 2019-01-08 09:15:23 -06:00
7
96af1fe7cf
Merge pull request #1460 from huge-success/18.12-changelog
18.12 Changelog
2019-01-06 22:33:37 -08:00
Yun Xu
cb3a03356b added changelogs to README and readthedocs 2019-01-06 13:50:40 -08:00
Yun Xu
68aa2ae3ce added changelog for 18.12 release 2019-01-06 13:44:18 -08:00
7
52de354e24
Merge pull request #1442 from Amanit/feature/gunicorn-logging
add an option to change access_log using gunicorn
2019-01-05 11:40:55 -08:00
7
f4f90cada4
Merge pull request #1449 from chenjr0719/add_amending_request_object_example
Add example of amending request object
2019-01-02 18:32:24 -08:00
Jotagê Sales
62420e0f40 resolve conflict 2019-01-02 21:19:40 -02:00
Sergey Fedoruk
102e651741 refactor typing imports 2019-01-02 23:28:06 +01:00
Sergey Fedoruk
65daaaf64b linteger fix and delete old tests 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
b7a6f36e95 add type annotations in run and create_server 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
a86a10b128 add control of access_log argument type 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
0b728ade3a change Config.__init__ 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
74f05108d7 async test for access_log in create_server 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
9d4d15ddc7 add config tests 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
0c5c6dff8f fix linting 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
391fcdc83d fix access_log in run server and fix bool in env variables 2019-01-02 23:28:05 +01:00
Sergey Fedoruk
d76d5e2c5f add an option to change access_log using gunicorn 2019-01-02 23:28:05 +01:00
jacob
f0ada573bb Fix a grammar error 2019-01-02 20:37:26 +08:00
jacob
ec5b790b51 Extend example of modifying the request in middleware document 2019-01-02 17:29:01 +08:00
jacob
613b23748d Add example of amending request object 2019-01-02 14:52:25 +08:00
Adam Hopkins
cea1547e08
Merge pull request #1446 from huge-success/ahopkins-patch-1
Update README.rst
2019-01-01 14:51:05 +02:00
7
fd5ae01e1d
Merge pull request #1444 from ja8zyjits/master
Updated README.md
2018-12-31 11:49:03 -08:00
Adam Hopkins
9b6b93d467
Update README.rst 2018-12-31 21:41:35 +02:00
Adam Hopkins
ca179c12a1
Update README.rst 2018-12-31 18:47:27 +02:00
Adam Hopkins
4d527035ae
Add dotted endpoint notation and additional tests 2018-12-31 13:40:07 +02:00
Jitesh Nair
19b42830ea
Merge pull request #1 from ja8zyjits/ja8zyjits-patch-1-readme
Update README.rst
2018-12-31 16:01:01 +05:30
Jitesh Nair
f5162f8ab1
Update README.rst
Made the optional Environment variable declaration for installation more clear.
2018-12-31 16:00:34 +05:30
7
ff38a3c6b6
Merge pull request #1443 from huge-success/new-readme
Update README with new logo, change Congfig.LOGO, run linter
2018-12-30 13:23:12 -08:00
Adam Hopkins
94e85686b5
Ignore first row of logs when no uvloop 2018-12-30 14:07:21 +02:00
Adam Hopkins
aea4a8ed33
Modify test_logo runner 2018-12-30 13:46:08 +02:00
Adam Hopkins
05dd3b2e9d
Run linter 2018-12-30 13:18:06 +02:00
Adam Hopkins
040468755c
Change ASCII Logo
Update logo text

Reformat app.py
2018-12-30 12:49:23 +02:00
Adam Hopkins
50b359fdb2
Update README.rst
Add new logo and update contents of README.

Update README.rst

Fix image syntax.

Update README.rst

Fix README links.
2018-12-30 11:48:59 +02:00
7
72f2e18a84
Merge pull request #1440 from harshanarayana/fix/Contribution_Guide_Pip_Install
fix minor type and pip install instruction mismatch
2018-12-28 18:43:41 -08:00
Jotagê Sales
b36dc22b45 resolve conflict in setup.py 2018-12-28 12:08:10 -02:00
Harsha Narayana
15b1c875f5
fix minor type and pip install instruction mismatch 2018-12-28 11:32:30 +05:30
7
13804dc380
Merge pull request #1424 from harshanarayana/enh/Documentation_Update
Documentation Enhancements
2018-12-27 21:30:02 -08:00
Harsha Narayana
9bea23da29
fix makefile phony targets
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:03 +05:30
Harsha Narayana
7005fabd4d
add code beautification task to makefile
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:03 +05:30
Harsha Narayana
de8c37ad00
fix pip install typo in contribution page
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:03 +05:30
Harsha Narayana
a80499c4b7
update installation steps to be consistent across documentation and readme
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:03 +05:30
Harsha Narayana
82f7f847ba
cleanup requirements and move dependency inside setup.py
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:03 +05:30
Harsha Narayana
4880761fe0
add setuputil based test running and makefile support
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:02 +05:30
Harsha Narayana
87ab0b386d
fix current version in setup.cfg for relase script
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:02 +05:30
Harsha Narayana
c42c274002
update manifest configuration
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:02 +05:30
Harsha Narayana
2d82b8951f
make release script black compliant and tweak documentation with indexing and format
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:24:02 +05:30
Harsha Narayana
b7702bc3e8
add monitoring examples and documents 2018-12-28 10:22:28 +05:30
Harsha Narayana
9c6b83501f
add release note chnage log generation
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
5189d8b14c
fix string formatting error in git commands for release script
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
e13053ed89
add automated calendar version manager
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
efa77cf5ec
add api documentation for router and server
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
f6355bd075
add additional examples to documentation
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
e3dfce88ff
fix linter issues
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
939b5ea095
update copyright date and add example section with category
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
e6fba01682
add documentation for cookies, exception, blueprint and handlers
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:28 +05:30
Harsha Narayana
1623d397be
categorize the sanic extensions list
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:27 +05:30
Harsha Narayana
09678d601d
add sanic app module documentations
Signed-off-by: Harsha Narayana <harsha2k4@gmail.com>
2018-12-28 10:22:27 +05:30
7
67d51f7e1b
Merge pull request #1423 from yunstanford/request-streaming-support
basic request streaming support with flow control
2018-12-27 18:06:02 -08:00
Jotagê Sales
f2a55d01ea fix error in import_string 2018-12-27 15:20:58 -02:00
Jotagê Sales
bf029c1b9d added docstring to helper function import_string 2018-12-27 14:35:04 -02:00
Jotagê Sales
375ebd39f0 fix pep8 errors 2018-12-26 21:28:42 -02:00
Jotagê Sales
a33ebbaf11 remove dependence and implmented import_string 2018-12-26 21:19:54 -02:00
Jotagê Sales
19b304b0fc fix doc 2018-12-26 18:31:43 -02:00
Jotagê Sales
0b64fe6746 create a documentation for config path 2018-12-26 18:27:02 -02:00
Jotagê Sales
e978121d58 configure app from object by path string 2018-12-26 16:23:16 -02:00
Yun Xu
956793e066 address review feedback, small code refactoring 2018-12-09 15:18:33 -08:00
Yun Xu
1bfbc67c62 expose request_buffer_queue_size to be configurable and update documentation
fix StreamBuffer buffer_size
2018-12-04 20:21:00 -08:00
Yun Xu
b5287184e9 fix lint
fix isort
2018-12-03 23:25:41 -08:00
Yun Xu
7c9957e058 update README.rst (clean up badges) 2018-12-03 23:03:14 -08:00
Yun Xu
fca7cb9fb0 update request streaming doc 2018-12-03 22:51:09 -08:00
Yun Xu
268d254d85 fix unit tests 2018-12-03 22:28:22 -08:00
Yun Xu
181adebf82 add StreamBuffer for request flow control 2018-12-03 22:19:26 -08:00
Raphael Deem
63bbcb5152 Merge branch 'master' into 977 2017-10-25 22:18:25 -07:00
Raphael Deem
9150767574 add blueprint name to request.endpoint 2017-10-16 23:25:37 -07:00
Raphael Deem
75f2180cb1 add handler name to request as endpoint 2017-10-16 22:43:40 -07:00
668 changed files with 94093 additions and 12812 deletions

View File

@ -2,11 +2,6 @@ version: "{branch}.{build}"
environment:
matrix:
- TOXENV: py35-no-ext
PYTHON: "C:\\Python35-x64"
PYTHON_VERSION: "3.5.x"
PYTHON_ARCH: "64"
- TOXENV: py36-no-ext
PYTHON: "C:\\Python36-x64"
PYTHON_VERSION: "3.6.x"
@ -17,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:

View File

@ -1,7 +1,25 @@
[run]
branch = True
source = sanic
omit = site-packages, sanic/utils.py, sanic/__main__.py
omit =
site-packages
sanic/__main__.py
sanic/server/legacy.py
sanic/compat.py
sanic/simple.py
sanic/utils.py
sanic/cli
sanic/pages
[html]
directory = coverage
[report]
exclude_lines =
no cov
no qa
noqa
NOQA
pragma: no cover
TYPE_CHECKING
skip_empty = True

3
.github/CODEOWNERS vendored Normal file
View 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
View 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']

78
.github/ISSUE_TEMPLATE/bug-report.yml vendored Normal file
View File

@ -0,0 +1,78 @@
name: 🐞 Bug report
description: Create a report to help us improve
labels: ["bug", "triage"]
body:
- type: checkboxes
id: existing
attributes:
label: Is there an existing issue for this?
description: Please search to see if an issue already exists for the bug you encountered.
options:
- label: I have searched the existing issues
required: true
- type: textarea
id: description
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is, make sure to paste any exceptions and tracebacks using markdown code-block syntax to make it easier to read.
validations:
required: true
- type: textarea
id: code
attributes:
label: Code snippet
description: |
Relevant source code, make sure to remove what is not necessary. Please try and format your code so that it is easier to read. For example:
```python
from sanic import Sanic
app = Sanic("Example")
```
validations:
required: false
- type: textarea
id: expected
attributes:
label: Expected Behavior
description: A concise description of what you expected to happen.
validations:
required: false
- type: dropdown
id: running
attributes:
label: How do you run Sanic?
options:
- Sanic CLI
- As a module
- As a script (`app.run` or `Sanic.serve`)
- ASGI
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating System
description: What OS?
options:
- Linux
- MacOS
- Windows
- Other (tell us in the description)
validations:
required: true
- type: input
id: version
attributes:
label: Sanic Version
description: Check startup logs or try `sanic --version`
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false

View File

@ -1,25 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is, make sure to paste any exceptions and tracebacks.
**Code snippet**
Relevant source code, make sure to remove what is not necessary.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Environment (please complete the following information):**
- OS: [e.g. iOS]
- Version [e.g. 0.8.3]
**Additional context**
Add any other context about the problem here.

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,8 @@
blank_issues_enabled: false
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.
- name: Discussion and Support
url: https://discord.gg/FARQzAEMAA
about: For live discussion and support, checkout the Sanic Discord server.

View File

@ -0,0 +1,34 @@
name: 🌟 Feature request
description: Suggest an enhancement for Sanic
labels: ["feature request"]
body:
- type: checkboxes
id: existing
attributes:
label: Is there an existing issue for this?
description: Please search to see if an issue already exists for the enhancement you are proposing.
options:
- label: I have searched the existing issues
required: true
- type: textarea
id: description
attributes:
label: Is your feature request related to a problem? Please describe.
description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
validations:
required: false
- type: textarea
id: code
attributes:
label: Describe the solution you'd like
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false

View File

@ -1,16 +0,0 @@
---
name: Feature request
about: Suggest an idea for Sanic
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Additional context**
Add any other context or sample code about the feature request here.

View File

@ -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

33
.github/ISSUE_TEMPLATE/rfc.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: 💡 Request for Comments
description: Open an RFC for discussion
labels: ["RFC"]
body:
- type: input
id: compare
attributes:
label: Link to code
description: If available, share a [comparison](https://github.com/sanic-org/sanic/compare) from a POC branch to main
placeholder: https://github.com/sanic-org/sanic/compare/main...some-new-branch
validations:
required: false
- type: textarea
id: proposal
attributes:
label: Proposal
description: A thorough discussion of the proposal discussing the problem it solves, potential code, use cases, and impacts
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context that is relevant
validations:
required: false
- type: checkboxes
id: breaking
attributes:
label: Is this a breaking change?
options:
- label: "Yes"
required: false

20
.github/stale.yml vendored Normal file
View File

@ -0,0 +1,20 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 90
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 30
# Issues with these labels will never be considered stale
exemptLabels:
- bug
- urgent
- necessary
- help wanted
- RFC
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. If this
is incorrect, please respond with an update. Thank you for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

42
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,42 @@
name: "CodeQL"
on:
push:
branches:
- main
- current-release
- "*LTS"
pull_request:
branches:
- main
- current-release
- "*LTS"
types: [opened, synchronize, reopened, ready_for_review]
schedule:
- cron: '25 16 * * 0'
jobs:
analyze:
if: github.event.pull_request.draft == false
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [ 'python' ]
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

34
.github/workflows/coverage.yml vendored Normal file
View File

@ -0,0 +1,34 @@
name: Coverage check
on:
push:
branches:
- main
- current-release
- "*LTS"
tags:
- "!*" # Do not execute on tags
pull_request:
branches:
- main
- current-release
- "*LTS"
jobs:
coverage:
name: Check coverage
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Run coverage
uses: sanic-org/simple-tox-action@v1
with:
python-version: "3.11"
tox-env: coverage
ignore-errors: true
- name: Run Codecov
uses: codecov/codecov-action@v3
with:
files: ./coverage.xml
fail_ci_if_error: false

174
.github/workflows/publish-release.yml vendored Normal file
View File

@ -0,0 +1,174 @@
name: Publish release
on:
release:
types: [created]
env:
IS_TEST: false
DOCKER_ORG_NAME: sanicframework
DOCKER_IMAGE_NAME: sanic
DOCKER_BASE_IMAGE_NAME: sanic-build
DOCKER_IMAGE_DOCKERFILE: ./docker/Dockerfile
DOCKER_BASE_IMAGE_DOCKERFILE: ./docker/Dockerfile-base
jobs:
generate_info:
name: Generate info
runs-on: ubuntu-latest
outputs:
docker-tags: ${{ steps.generate_docker_info.outputs.tags }}
pypi-version: ${{ steps.parse_version_tag.outputs.pypi-version }}
steps:
- name: Parse version tag
id: parse_version_tag
env:
TAG_NAME: ${{ github.event.release.tag_name }}
run: |
tag_name="${{ env.TAG_NAME }}"
if [[ ! "${tag_name}" =~ ^v([0-9]{2})\.([0-9]{1,2})\.([0-9]+)$ ]]; then
echo "::error::Tag name must be in the format vYY.MM.MICRO"
exit 1
fi
year_output="year=${BASH_REMATCH[1]}"
month_output="month=${BASH_REMATCH[2]}"
pypi_output="pypi-version=${tag_name#v}"
echo "${year_output}"
echo "${month_output}"
echo "${pypi_output}"
echo "${year_output}" >> $GITHUB_OUTPUT
echo "${month_output}" >> $GITHUB_OUTPUT
echo "${pypi_output}" >> $GITHUB_OUTPUT
- name: Get latest release
id: get_latest_release
run: |
latest_tag=$(
curl -L \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ github.token }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/${{ github.repository }}/releases/latest \
| jq -r '.tag_name'
)
echo "latest_tag=$latest_tag" >> $GITHUB_OUTPUT
- name: Generate Docker info
id: generate_docker_info
run: |
tag_year="${{ steps.parse_version_tag.outputs.year }}"
tag_month="${{ steps.parse_version_tag.outputs.month }}"
latest_tag="${{ steps.get_latest_release.outputs.latest_tag }}"
tag="${{ github.event.release.tag_name }}"
tags="${tag_year}.${tag_month}"
if [[ "${tag_month}" == "12" ]]; then
tags+=",LTS"
echo "::notice::Tag ${tag} is LTS version"
else
echo "::notice::Tag ${tag} is not LTS version"
fi
if [[ "${latest_tag}" == "${{ github.event.release.tag_name }}" ]]; then
tags+=",latest"
echo "::notice::Tag ${tag} is marked as latest"
else
echo "::notice::Tag ${tag} is not marked as latest"
fi
tags_output="tags=${tags}"
echo "${tags_output}"
echo "${tags_output}" >> $GITHUB_OUTPUT
publish_package:
name: Build and publish package
runs-on: ubuntu-latest
needs: generate_info
steps:
- name: Checkout repo
uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
- name: Install dependencies
run: pip install build twine
- name: Update package version
run: |
echo "__version__ = \"${{ needs.generate_info.outputs.pypi-version }}\"" > sanic/__version__.py
- name: Build a binary wheel and a source tarball
run: python -m build --sdist --wheel --outdir dist/ .
- name: Publish to PyPi 🚀
run: twine upload --non-interactive --disable-progress-bar dist/*
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ env.IS_TEST == 'true' && secrets.SANIC_TEST_PYPI_API_TOKEN || secrets.SANIC_PYPI_API_TOKEN }}
TWINE_REPOSITORY: ${{ env.IS_TEST == 'true' && 'testpypi' || 'pypi' }}
publish_docker:
name: Publish Docker / Python ${{ matrix.python-version }}
needs: [generate_info, publish_package]
runs-on: ubuntu-latest
strategy:
fail-fast: true
matrix:
python-version: ["3.10", "3.11"]
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_ACCESS_USER }}
password: ${{ secrets.DOCKER_ACCESS_TOKEN }}
- name: Build and push base image
uses: docker/build-push-action@v4
with:
push: ${{ env.IS_TEST == 'false' }}
file: ${{ env.DOCKER_BASE_IMAGE_DOCKERFILE }}
tags: ${{ env.DOCKER_ORG_NAME }}/${{ env.DOCKER_BASE_IMAGE_NAME }}:${{ matrix.python-version }}
build-args: |
PYTHON_VERSION=${{ matrix.python-version }}
- name: Parse tags for this Python version
id: parse_tags
run: |
IFS=',' read -ra tags <<< "${{ needs.generate_info.outputs.docker-tags }}"
tag_args=""
for tag in "${tags[@]}"; do
tag_args+=",${{ env.DOCKER_ORG_NAME }}/${{ env.DOCKER_IMAGE_NAME }}:${tag}-py${{ matrix.python-version }}"
done
tag_args_output="tag_args=${tag_args:1}"
echo "${tag_args_output}"
echo "${tag_args_output}" >> $GITHUB_OUTPUT
- name: Build and push Sanic image
uses: docker/build-push-action@v4
with:
push: ${{ env.IS_TEST == 'false' }}
file: ${{ env.DOCKER_IMAGE_DOCKERFILE }}
tags: ${{ steps.parse_tags.outputs.tag_args }}
build-args: |
BASE_IMAGE_ORG=${{ env.DOCKER_ORG_NAME }}
BASE_IMAGE_NAME=${{ env.DOCKER_BASE_IMAGE_NAME }}
BASE_IMAGE_TAG=${{ matrix.python-version }}
SANIC_PYPI_VERSION=${{ needs.generate_info.outputs.pypi-version }}

56
.github/workflows/tests.yml vendored Normal file
View File

@ -0,0 +1,56 @@
name: Tests
on:
push:
branches:
- main
- current-release
- "*LTS"
tags:
- "!*"
pull_request:
branches:
- main
- current-release
- "*LTS"
types: [opened, synchronize, reopened, ready_for_review]
jobs:
run_tests:
name: "${{ matrix.config.platform == 'windows-latest' && 'Windows' || 'Linux' }} / Python ${{ matrix.config.python-version }} / tox -e ${{ matrix.config.tox-env }}"
if: github.event.pull_request.draft == false
runs-on: ${{ matrix.config.platform || 'ubuntu-latest' }}
strategy:
fail-fast: true
matrix:
config:
- { python-version: "3.8", tox-env: security }
- { python-version: "3.9", tox-env: security }
- { python-version: "3.10", tox-env: security }
- { python-version: "3.11", tox-env: security }
- { python-version: "3.10", tox-env: lint }
# - { python-version: "3.10", tox-env: docs }
- { python-version: "3.8", tox-env: type-checking }
- { python-version: "3.9", tox-env: type-checking }
- { python-version: "3.10", tox-env: type-checking }
- { python-version: "3.11", tox-env: type-checking }
- { python-version: "3.8", tox-env: py38, max-attempts: 3 }
- { python-version: "3.8", tox-env: py38-no-ext, max-attempts: 3 }
- { python-version: "3.9", tox-env: py39, max-attempts: 3 }
- { python-version: "3.9", tox-env: py39-no-ext, max-attempts: 3 }
- { python-version: "3.10", tox-env: py310, max-attempts: 3 }
- { python-version: "3.10", tox-env: py310-no-ext, max-attempts: 3 }
- { python-version: "3.11", tox-env: py311, max-attempts: 3 }
- { python-version: "3.11", tox-env: py311-no-ext, max-attempts: 3 }
- { python-version: "3.8", tox-env: py38-no-ext, platform: windows-latest, ignore-errors: true }
- { python-version: "3.9", tox-env: py39-no-ext, platform: windows-latest, ignore-errors: true }
- { python-version: "3.10", tox-env: py310-no-ext, platform: windows-latest, ignore-errors: true }
- { python-version: "3.11", tox-env: py310-no-ext, platform: windows-latest, ignore-errors: true }
steps:
- name: Run tests
uses: sanic-org/simple-tox-action@v1
with:
python-version: ${{ matrix.config.python-version }}
tox-env: ${{ matrix.config.tox-env }}
max-attempts: ${{ matrix.config.max-attempts || 1 }}
ignore-errors: ${{ matrix.config.ignore-errors || false }}

9
.gitignore vendored
View File

@ -6,12 +6,21 @@
.coverage
.coverage.*
coverage
coverage.xml
.tox
settings.py
.idea/*
.cache/*
.mypy_cache/
.python-version
docs/_build/
docs/_api/
build/*
.DS_Store
dist/*
pip-wheel-metadata/
.pytest_cache/*
.venv/*
venv/*
.vscode/*
guide/node_modules/

View File

@ -1,41 +0,0 @@
sudo: false
language: python
cache:
directories:
- $HOME/.cache/pip
matrix:
include:
- env: TOX_ENV=py35
python: 3.5
- env: TOX_ENV=py35-no-ext
python: 3.5
- env: TOX_ENV=py36
python: 3.6
- env: TOX_ENV=py36-no-ext
python: 3.6
- env: TOX_ENV=py37
python: 3.7
dist: xenial
sudo: true
- env: TOX_ENV=py37-no-ext
python: 3.7
dist: xenial
sudo: true
- env: TOX_ENV=lint
python: 3.6
- env: TOX_ENV=check
python: 3.6
install:
- pip install -U tox
- pip install codecov
script: travis_retry tox -e $TOX_ENV
after_success:
- codecov
deploy:
provider: pypi
user: channelcat
password:
secure: h7oNDjA/ObDBGK7xt55SV0INHOclMJW/byxMrNxvCZ0JxiRk7WBNtWYt0WJjyf5lO/L0/sfgiAk0GIdFon57S24njSLPAq/a4ptkWZ68s2A+TaF6ezJSZvE9V8khivjoeub90TzfX6P5aukRja1CSxXKJm+v0V8hGE4CZGyCgEDvK3JqIakpXllSDl19DhVftCS/lQZD7AXrZlg1kZnPCMtB5IbCVR4L2bfrSJVNptBi2CqqxacY2MOLu+jv5FzJ2BGVIJ2zoIJS2T+JmGJzpiamF6y8Amv0667i9lg2DXWCtI3PsQzCmwa3F/ZsI+ohUAvJC5yvzP7SyTJyXifRBdJ9O137QkNAHFoJOOY3B4GSnTo8/boajKXEqGiV4h2EgwNjBaR0WJl0pB7HHUCBMkNRWqo6ACB8eCr04tXWXPvkGIc+wPjq960hsUZea1O31MuktYc9Ot6eiFqm7OKoItdi7LxCen1eTj93ePgkiEnVZ+p/04Hh1U7CX31UJMNu5kCvZPIANnAuDsS2SK7Qkr88OAuWL0wmrBcXKOcnVkJtZ5mzx8T54bI1RrSYtFDBLFfOPb0GucSziMBtQpE76qPEauVwIXBk3RnR8N57xBR/lvTaIk758tf+haO0llEO5rVls1zLNZ+VlTzXy7hX0OZbdopIAcCFBFWqWMAdXQc=
on:
tags: true
distributions: "sdist bdist_wheel"

View File

@ -1,99 +0,0 @@
Version 0.8
-----------
0.8.3
- Changes:
- Ownership changed to org 'huge-success'
0.8.0
- Changes:
- Add Server-Sent Events extension (Innokenty Lebedev)
- Graceful handling of request_handler_task cancellation (Ashley Sommer)
- Sanitize URL before redirection (aveao)
- Add url_bytes to request (johndoe46)
- py37 support for travisci (yunstanford)
- Auto reloader support for OSX (garyo)
- Add UUID route support (Volodymyr Maksymiv)
- Add pausable response streams (Ashley Sommer)
- Add weakref to request slots (vopankov)
- remove ubuntu 12.04 from test fixture due to deprecation (yunstanford)
- Allow streaming handlers in add_route (kinware)
- use travis_retry for tox (Raphael Deem)
- update aiohttp version for test client (yunstanford)
- add redirect import for clarity (yingshaoxo)
- Update HTTP Entity headers (Arnulfo Solís)
- Add register_listener method (Stephan Fitzpatrick)
- Remove uvloop/ujson dependencies for Windows (abuckenheimer)
- Content-length header on 204/304 responses (Arnulfo Solís)
- Extend WebSocketProtocol arguments and add docs (Bob Olde Hampsink, yunstanford)
- Update development status from pre-alpha to beta (Maksim Anisenkov)
- KeepAlive Timout log level changed to debug (Arnulfo Solís)
- Pin pytest to 3.3.2 because of pytest-dev/pytest#3170 (Maksim Aniskenov)
- Install Python 3.5 and 3.6 on docker container for tests (Shahin Azad)
- Add support for blueprint groups and nesting (Elias Tarhini)
- Remove uvloop for windows setup (Aleksandr Kurlov)
- Auto Reload (Yaser Amari)
- Documentation updates/fixups (multiple contributors)
- Fixes:
- Fix: auto_reload in Linux (Ashley Sommer)
- Fix: broken tests for aiohttp >= 3.3.0 (Ashley Sommer)
- Fix: disable auto_reload by default on windows (abuckenheimer)
- Fix (1143): Turn off access log with gunicorn (hqy)
- Fix (1268): Support status code for file response (Cosmo Borsky)
- Fix (1266): Add content_type flag to Sanic.static (Cosmo Borsky)
- Fix: subprotocols parameter missing from add_websocket_route (ciscorn)
- Fix (1242): Responses for CI header (yunstanford)
- Fix (1237): add version constraint for websockets (yunstanford)
- Fix (1231): memory leak - always release resource (Phillip Xu)
- Fix (1221): make request truthy if transport exists (Raphael Deem)
- Fix failing tests for aiohttp>=3.1.0 (Ashley Sommer)
- Fix try_everything examples (PyManiacGR, kot83)
- Fix (1158): default to auto_reload in debug mode (Raphael Deem)
- Fix (1136): ErrorHandler.response handler call too restrictive (Julien Castiaux)
- Fix: raw requires bytes-like object (cloudship)
- Fix (1120): passing a list in to a route decorator's host arg (Timothy Ebiuwhe)
- Fix: Bug in multipart/form-data parser (DirkGuijt)
- Fix: Exception for missing parameter when value is null (NyanKiyoshi)
- Fix: Parameter check (Howie Hu)
- Fix (1089): Routing issue with named parameters and different methods (yunstanford)
- Fix (1085): Signal handling in multi-worker mode (yunstanford)
- Fix: single quote in readme.rst (Cosven)
- Fix: method typos (Dmitry Dygalo)
- Fix: log_response correct output for ip and port (Wibowo Arindrarto)
- Fix (1042): Exception Handling (Raphael Deem)
- Fix: Chinese URIs (Howie Hu)
- Fix (1079): timeout bug when self.transport is None (Raphael Deem)
- Fix (1074): fix strict_slashes when route has slash (Raphael Deem)
- Fix (1050): add samesite cookie to cookie keys (Raphael Deem)
- Fix (1065): allow add_task after server starts (Raphael Deem)
- Fix (1061): double quotes in unauthorized exception (Raphael Deem)
- Fix (1062): inject the app in add_task method (Raphael Deem)
- Fix: update environment.yml for readthedocs (Eli Uriegas)
- Fix: Cancel request task when response timeout is triggered (Jeong YunWon)
- Fix (1052): Method not allowed response for RFC7231 compliance (Raphael Deem)
- Fix: IPv6 Address and Socket Data Format (Dan Palmer)
Note: Changelog was unmaintained between 0.1 and 0.7
Version 0.1
-----------
- 0.1.7
- Reversed static url and directory arguments to meet spec
- 0.1.6
- Static files
- Lazy Cookie Loading
- 0.1.5
- Cookies
- Blueprint listeners and ordering
- Faster Router
- Fix: Incomplete file reads on medium+ sized post requests
- Breaking: after_start and before_stop now pass sanic as their first argument
- 0.1.4
- Multiprocessing
- 0.1.3
- Blueprint support
- Faster Response processing
- 0.1.1 - 0.1.2
- Struggling to update pypi via CI
- 0.1.0
- Released to public

1159
CHANGELOG.rst Normal file

File diff suppressed because it is too large Load Diff

View File

@ -55,7 +55,7 @@ further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at sanic-maintainers@googlegroups.com. All
reported by contacting the project team at adam@sanicframework.org. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.

View File

@ -1,72 +0,0 @@
# 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.
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.
## Installation
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
a virtual environment already set up, then run:
```bash
python setup.py develop && pip install -r requirements-dev.txt
```
## Running tests
To run the tests for sanic it is recommended to use tox like so:
```bash
tox
```
See it's that simple!
## Pull requests!
So the pull request approval rules are pretty simple:
1. All pull requests must pass unit tests.
2. All pull requests must be reviewed and approved by at least
one current collaborator on the project.
3. All pull requests must pass flake8 checks.
4. All pull requests must be consistent with the existing code.
5. If you decide to remove/change anything from any common interface
a deprecation message should accompany it.
6. If you implement a new feature you should have at least one unit
test to accompany it.
7. An example must be one of the following:
* Example of how to use Sanic
* Example of how to use Sanic extensions
* Example of how to use Sanic and asynchronous library
## 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
automatically generated using `sphinx-apidoc`.
To generate the documentation from scratch:
```bash
sphinx-apidoc -fo docs/_api/ sanic
sphinx-build -b html docs docs/_build
```
The HTML documentation will be created in the `docs/_build` folder.
## 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
merged. Please don't let this intimidate you! If you have any concerns about an
idea, open an issue for discussion and help.

240
CONTRIBUTING.rst Normal file
View File

@ -0,0 +1,240 @@
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,
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 <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
install from sources.
So assume you have already cloned the repo and are in the working directory with
a virtual environment already set up, then run:
.. code-block:: bash
pip install -e ".[dev]"
Dependency Changes
------------------
``Sanic`` doesn't use ``requirements*.txt`` files to manage any kind of dependencies related to it in order to simplify the
effort required in managing the dependencies. Please make sure you have read and understood the following section of
the document that explains the way ``sanic`` manages dependencies inside the ``setup.py`` file.
.. list-table::
:header-rows: 1
* - Dependency Type
- Usage
- Installation
* - requirements
- Bare minimum dependencies required for sanic to function
- ``pip3 install -e .``
* - tests_require / extras_require['test']
- Dependencies required to run the Unit Tests for ``sanic``
- ``pip3 install -e '.[test]'``
* - extras_require['dev']
- Additional Development requirements to add contributing
- ``pip3 install -e '.[dev]'``
* - extras_require['docs']
- Dependencies required to enable building and enhancing sanic documentation
- ``pip3 install -e '.[docs]'``
Running all tests
-----------------
To run the tests for Sanic it is recommended to use tox like so:
.. code-block:: bash
tox
See it's that simple!
``tox.ini`` contains different environments. Running ``tox`` without any arguments will
run all unittests, perform lint and other checks.
Run unittests
-------------
``tox`` environment -> ``[testenv]``
To execute only unittests, run ``tox`` with environment like so:
.. code-block:: bash
tox -e py37 -v -- tests/test_config.py
# or
tox -e py310 -v -- tests/test_config.py
Run lint checks
---------------
``tox`` environment -> ``[testenv:lint]``
Permform ``flake8``\ , ``black`` and ``isort`` checks.
.. code-block:: bash
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
----------------
``tox`` environment -> ``[testenv:check]``
Perform other checks.
.. code-block:: bash
tox -e check
Run Static Analysis
-------------------
``tox`` environment -> ``[testenv:security]``
Perform static analysis security scan
.. code-block:: bash
tox -e security
Run Documentation sanity check
------------------------------
``tox`` environment -> ``[testenv:docs]``
Perform sanity check on documentation
.. code-block:: bash
tox -e docs
Code Style
----------
To maintain the code consistency, Sanic uses following tools.
#. `isort <https://github.com/timothycrosley/isort>`_
#. `black <https://github.com/python/black>`_
#. `flake8 <https://github.com/PyCQA/flake8>`_
#. `slotscheck <https://github.com/ariebovenberg/slotscheck>`_
isort
*****
``isort`` sorts Python imports. It divides imports into three
categories sorted each in alphabetical order.
#. built-in
#. third-party
#. project-specific
black
*****
``black`` is a Python code formatter.
flake8
******
``flake8`` is a Python style guide that wraps following tools into one.
#. PyFlakes
#. pycodestyle
#. Ned Batchelder's McCabe script
slotscheck
**********
``slotscheck`` ensures that there are no problems with ``__slots__``
(e.g. overlaps, or missing slots in base classes).
``isort``\ , ``black``\ , ``flake8`` and ``slotscheck`` checks are performed during ``tox`` lint checks.
The **easiest** way to make your code conform is to run the following before committing.
.. code-block:: bash
make pretty
Refer `tox <https://tox.readthedocs.io/en/latest/index.html>`_ documentation for more details.
Pull requests
-------------
So the pull request approval rules are pretty simple:
#. All pull requests must pass unit tests.
#. 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 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:
* Example of how to use Sanic
* Example of how to use Sanic extensions
* Example of how to use Sanic and asynchronous library
Documentation
-------------
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
sphinx-apidoc -fo docs/_api/ sanic
sphinx-build -b html docs docs/_build
# There is a simple make command provided to ease the work required in generating
# the documentation
make docs
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
merged. Please don't let this intimidate you! If you have any concerns about an
idea, open an issue for discussion and help.

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2016-present Channel Cat
Copyright (c) 2016-present Sanic Community
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,7 +1,15 @@
include README.rst
include MANIFEST.in
# Non Code related contents
include LICENSE
include setup.py
include README.rst
include pyproject.toml
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
# Setup
include setup.py
include Makefile
# Tests
include .coveragerc
graft tests
global-exclude __pycache__
global-exclude *.py[co]

105
Makefile
View File

@ -1,4 +1,105 @@
test:
find . -name "*.pyc" -delete
.PHONY: help test test-coverage install docker-test black fix-import beautify
.DEFAULT: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo "test"
@echo " Run Sanic Unit Tests"
@echo "test-coverage"
@echo " Run Sanic Unit Tests with Coverage"
@echo "install"
@echo " Install Sanic"
@echo "docker-test"
@echo " Run Sanic Unit Tests using Docker"
@echo "black"
@echo " Analyze and fix linting issues using Black"
@echo "fix-import"
@echo " Analyze and fix import order using isort"
@echo "beautify [sort_imports=1] [include_tests=1]"
@echo " Analyze and fix linting issue using black and optionally fix import sort using isort"
@echo ""
@echo "docs"
@echo " Generate Sanic documentation"
@echo ""
@echo "clean-docs"
@echo " Clean Sanic documentation"
@echo ""
@echo "docs-test"
@echo " Test Sanic Documentation for errors"
@echo ""
@echo "changelog"
@echo " Generate changelog for Sanic to prepare for new release"
@echo ""
@echo "release"
@echo " Prepare Sanic for a new changes by version bump and changelog"
@echo ""
clean:
find . ! -path "./.eggs/*" -name "*.pyc" -exec rm {} \;
find . ! -path "./.eggs/*" -name "*.pyo" -exec rm {} \;
find . ! -path "./.eggs/*" -name ".coverage" -exec rm {} \;
rm -rf build/* > /dev/null 2>&1
rm -rf dist/* > /dev/null 2>&1
test: clean
python setup.py test
test-coverage: clean
python setup.py test --pytest-args="--cov sanic --cov-report term --cov-append "
view-coverage:
sanic ./coverage --simple
install:
python setup.py install
docker-test: clean
docker build -t sanic/test-image -f docker/Dockerfile .
docker run -t sanic/test-image tox
beautify: black
ifdef sort_imports
ifdef include_tests
$(warning It is suggested that you do not run sort import on tests)
isort -rc sanic tests
else
$(info Sorting Imports)
isort -rc sanic tests
endif
endif
black:
black sanic tests
isort:
isort sanic tests
pretty: black isort
docs-clean:
cd docs && make clean
docs: docs-clean
cd docs && make html
docs-test: docs-clean
cd docs && make dummy
docs-serve:
sphinx-autobuild docs docs/_build/html --port 9999 --watch ./
changelog:
python scripts/changelog.py
guide-serve:
cd guide && sanic server:app -r -R ./content -R ./style
release:
ifdef version
python scripts/release.py --release-version ${version} --generate-changelog
else
python scripts/release.py --generate-changelog
endif

View File

@ -1,15 +1,105 @@
Sanic
=====
.. image:: https://raw.githubusercontent.com/sanic-org/sanic-assets/master/png/sanic-framework-logo-400x97.png
:alt: Sanic | Build fast. Run fast.
|Join the chat at https://gitter.im/sanic-python/Lobby| |Build Status| |AppVeyor Build Status| |Documentation| |Codecov| |PyPI| |PyPI version| |Code style black|
Sanic | Build fast. Run fast.
=============================
Sanic is a Flask-like Python 3.5+ web server that's written to go fast. It's based on the work done by the amazing folks at magicstack, and was inspired by `this article <https://magic.io/blog/uvloop-blazing-fast-python-networking/>`_.
.. start-badges
On top of being Flask-like, Sanic supports async request handlers. This means you can use the new shiny async/await syntax from Python 3.5, making your code non-blocking and speedy.
.. list-table::
:widths: 15 85
:stub-columns: 1
Sanic is developed `on GitHub <https://github.com/huge-success/sanic/>`_. We also have `a community discussion board <https://community.sanicframework.org/>`_. Contributions are welcome!
* - Build
- | |Tests|
* - Docs
- | |UserGuide| |Documentation|
* - Package
- | |PyPI| |PyPI version| |Wheel| |Supported implementations| |Code style black|
* - Support
- | |Forums| |Discord| |Awesome|
* - Stats
- | |Monthly Downloads| |Weekly Downloads| |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/
.. |Discord| image:: https://img.shields.io/discord/812221182594121728?logo=discord
:target: https://discord.gg/FARQzAEMAA
.. |Tests| image:: https://github.com/sanic-org/sanic/actions/workflows/tests.yml/badge.svg?branch=main
:target: https://github.com/sanic-org/sanic/actions/workflows/tests.yml
.. |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
:target: https://pypi.python.org/pypi/sanic/
.. |PyPI version| image:: https://img.shields.io/pypi/pyversions/sanic.svg
:target: https://pypi.python.org/pypi/sanic/
.. |Code style black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
.. |Wheel| image:: https://img.shields.io/pypi/wheel/sanic.svg
:alt: PyPI Wheel
:target: https://pypi.python.org/pypi/sanic
.. |Supported implementations| image:: https://img.shields.io/pypi/implementation/sanic.svg
:alt: Supported implementations
:target: https://pypi.python.org/pypi/sanic
.. |Awesome| image:: https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg
:alt: Awesome Sanic List
:target: https://github.com/mekicha/awesome-sanic
.. |Monthly Downloads| image:: https://img.shields.io/pypi/dm/sanic.svg
:alt: Downloads
:target: https://pepy.tech/project/sanic
.. |Weekly Downloads| image:: https://img.shields.io/pypi/dw/sanic.svg
: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
.. |Linode| image:: https://www.linode.com/wp-content/uploads/2021/01/Linode-Logo-Black.svg
:alt: Linode
:target: https://www.linode.com
:width: 200px
.. end-badges
Sanic is a **Python 3.8+** web server and web framework that's written to go fast. It allows the usage of the ``async/await`` syntax added in Python 3.5, which makes your code non-blocking and speedy.
Sanic is also ASGI compliant, so you can deploy it with an `alternative ASGI webserver <https://sanicframework.org/en/guide/deployment/running.html#asgi>`_.
`Source code on GitHub <https://github.com/sanic-org/sanic/>`_ | `Help and discussion board <https://community.sanicframework.org/>`_ | `User Guide <https://sanicframework.org>`_ | `Chat on Discord <https://discord.gg/FARQzAEMAA>`_
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
-------
Check out `open collective <https://opencollective.com/sanic-org>`_ to learn more about helping to fund Sanic.
Thanks to `Linode <https://www.linode.com>`_ for their contribution towards the development and community of Sanic.
|Linode|
Installation
------------
``pip3 install sanic``
Sanic makes use of ``uvloop`` and ``ujson`` to help with performance. If you do not want to use those packages, simply add an environmental variable ``SANIC_NO_UVLOOP=true`` or ``SANIC_NO_UJSON=true`` at install time.
.. code:: shell
$ export SANIC_NO_UVLOOP=true
$ export SANIC_NO_UJSON=true
$ pip3 install --no-binary :all: sanic
.. note::
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.
If you have a project that utilizes Sanic make sure to comment on the `issue <https://github.com/huge-success/sanic/issues/396>`_ that we use to track those projects!
Hello World Example
-------------------
@ -19,85 +109,55 @@ 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()
Installation
------------
Sanic can now be easily run using ``sanic hello.app``.
- ``pip install sanic``
.. code::
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 NO_X to true will stop that features
installation.
[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]
- ``SANIC_NO_UVLOOP=true SANIC_NO_UJSON=true pip install sanic``
And, we can verify it is working: ``curl localhost:8000 -i``
.. code::
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 17
Content-Type: application/json
{"hello":"world"}
**Now, let's go build something fast!**
Minimum Python version is 3.8. If you need Python 3.7 support, please use v22.12LTS.
Documentation
-------------
`Documentation on Readthedocs <http://sanic.readthedocs.io/>`_.
`User Guide <https://sanic.dev>`__ and `API Documentation <http://sanic.readthedocs.io/>`__.
Changelog
---------
`Release Changelogs <https://sanic.readthedocs.io/en/stable/sanic/changelog.html>`__.
.. |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
.. |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
.. |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
:target: https://pypi.python.org/pypi/sanic/
.. |PyPI version| image:: https://img.shields.io/pypi/pyversions/sanic.svg
:target: https://pypi.python.org/pypi/sanic/
.. |Code style black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
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
------------
Examples
--------
`Non-Core examples <https://github.com/huge-success/sanic/wiki/Examples/>`_. Examples of plugins and Sanic that are outside the scope of Sanic core.
`Extensions <https://github.com/huge-success/sanic/wiki/Extensions/>`_. Sanic extensions created by the community.
`Projects <https://github.com/huge-success/sanic/wiki/Projects/>`_. Sanic in production use.
Final Thoughts
--------------
::
▄▄▄▄▄
▀▀▀██████▄▄▄ _______________
▄▄▄▄▄ █████████▄ / \
▀▀▀▀█████▌ ▀▐▄ ▀▐█ | Gotta go fast! |
▀▀█████▄▄ ▀██████▄██ | _________________/
▀▄▄▄▄▄ ▀▀█▄▀█════█▀ |/
▀▀▀▄ ▀▀███ ▀ ▄▄
▄███▀▀██▄████████▄ ▄▀▀▀▀▀▀█▌
██▀▄▄▄██▀▄███▀ ▀▀████ ▄██
▄▀▀▀▄██▄▀▀▌████▒▒▒▒▒▒███ ▌▄▄▀
▌ ▐▀████▐███▒▒▒▒▒▐██▌
▀▄▄▄▄▀ ▀▀████▒▒▒▒▄██▀
▀▀█████████▀
▄▄██▀██████▀█
▄██▀ ▀▀▀ █
▄█ ▐▌
▄▄▄▄█▌ ▀█▄▄▄▄▀▀▄
▌ ▐ ▀▀▄▄▄▀
▀▀▄▄▀
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>`_.

45
SECURITY.md Normal file
View File

@ -0,0 +1,45 @@
# Security Policy
## Supported Versions
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 |
| ------- | ------------- | ----------------------- |
| 22.12 | until 2024-12 | :white_check_mark: |
| 22.9 | | :x: |
| 22.6 | | :x: |
| 22.3 | | :x: |
| 21.12 | until 2023-12 | :ballot_box_with_check: |
| 21.9 | | :x: |
| 21.6 | | :x: |
| 21.3 | | :x: |
| 20.12 | | :x: |
| 20.9 | | :x: |
| 20.6 | | :x: |
| 20.3 | | :x: |
| 19.12 | | :x: |
| 19.9 | | :x: |
| 19.6 | | :x: |
| 19.3 | | :x: |
| 18.12 | | :x: |
| 0.8.3 | | :x: |
| 0.7.0 | | :x: |
| 0.6.0 | | :x: |
| 0.5.4 | | :x: |
| 0.4.1 | | :x: |
| 0.3.1 | | :x: |
| 0.2.0 | | :x: |
| 0.1.9 | | :x: |
:ballot_box_with_check: = security/bug fixes
:white_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.
Alternatively, you can send a private message to Adam Hopkins on Discord. Find him on the [Sanic discord server](https://discord.gg/FARQzAEMAA).
This will help to not publicize the issue until the team can address it and resolve it.

2
changelogs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
# Except this file
!.gitignore

View File

@ -0,0 +1 @@
Remove [version] section.

View 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
View File

@ -0,0 +1 @@
Adds py.typed file to expose type information to other packages.

28
codecov.yml Normal file
View File

@ -0,0 +1,28 @@
coverage:
status:
patch:
default:
target: auto
threshold: 0.75
informational: true
project:
default:
target: auto
threshold: 0.5
precision: 3
codecov:
require_ci_to_pass: false
ignore:
- "sanic/__main__.py"
- "sanic/compat.py"
- "sanic/simple.py"
- "sanic/utils.py"
- "sanic/cli/"
- "sanic/pages/"
- ".github/"
- "changelogs/"
- "docker/"
- "docs/"
- "examples/"
- "scripts/"
- "tests/"

View File

@ -1,28 +1,13 @@
FROM alpine:3.7
ARG BASE_IMAGE_ORG
ARG BASE_IMAGE_NAME
ARG BASE_IMAGE_TAG
RUN apk add --no-cache --update \
curl \
bash \
build-base \
ca-certificates \
git \
bzip2-dev \
linux-headers \
ncurses-dev \
openssl \
openssl-dev \
readline-dev \
sqlite-dev
FROM ${BASE_IMAGE_ORG}/${BASE_IMAGE_NAME}:${BASE_IMAGE_TAG}
RUN apk update
RUN update-ca-certificates
RUN rm -rf /var/cache/apk/*
ENV PYENV_ROOT="/root/.pyenv"
ENV PATH="$PYENV_ROOT/bin:$PATH"
ARG SANIC_PYPI_VERSION
ADD . /app
WORKDIR /app
RUN /app/docker/bin/install_python.sh 3.5.4 3.6.4
ENTRYPOINT ["./docker/bin/entrypoint.sh"]
RUN pip install -U pip && pip install sanic==${SANIC_PYPI_VERSION}
RUN apk del build-base

9
docker/Dockerfile-base Normal file
View File

@ -0,0 +1,9 @@
ARG PYTHON_VERSION
FROM python:${PYTHON_VERSION}-alpine
RUN apk update
RUN apk add --no-cache --update build-base \
ca-certificates \
openssl
RUN update-ca-certificates
RUN rm -rf /var/cache/apk/*

View File

@ -1,11 +0,0 @@
#!/bin/bash
set -e
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
source /root/.pyenv/completions/pyenv.bash
pip install tox
exec $@

View File

@ -1,17 +0,0 @@
#!/bin/bash
set -e
export CFLAGS='-O2'
export EXTRA_CFLAGS="-DTHREAD_STACK_SIZE=0x100000"
curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
eval "$(pyenv init -)"
for ver in $@
do
pyenv install $ver
done
pyenv global $@
pip install --upgrade pip
pyenv rehash

13
docs/_static/custom.css vendored Normal file
View File

@ -0,0 +1,13 @@
.wy-side-nav-search,
.wy-nav-top {
background: #444444;
}
#changelog section {
padding-left: 3rem;
}
#changelog section h2,
#changelog section h3 {
margin-left: -3rem;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -10,11 +10,9 @@
import os
import sys
# Add support for Markdown documentation using Recommonmark
from recommonmark.parser import CommonMarkParser
# Add support for auto-doc
from recommonmark.transform import AutoStructify
# Ensure that sanic is present in the path, to allow sphinx-apidoc to
# autogenerate documentation from docstrings
@ -23,24 +21,29 @@ sys.path.insert(0, root_directory)
import sanic
# -- General configuration ------------------------------------------------
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.asyncio']
extensions = [
"sphinx.ext.autodoc",
"m2r2",
"enum_tools.autoenum",
]
templates_path = ['_templates']
templates_path = ["_templates"]
# Enable support for both Restructured Text and Markdown
source_parsers = {'.md': CommonMarkParser}
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 = '2016, 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.
@ -55,7 +58,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.
@ -63,10 +66,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
@ -75,17 +78,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 ---------------------------------------------
@ -93,15 +96,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',
@ -110,14 +110,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 -------------------------------------------
@ -125,8 +132,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 ----------------------------------------------
@ -138,17 +152,18 @@ 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"]
# app setup hook
def setup(app):
app.add_config_value('recommonmark_config', {
'enable_eval_rst': True,
'enable_auto_doc_ref': True,
}, True)
app.add_transform(AutoStructify)
autodoc_typehints = "description"
autodoc_default_options = {
"member-order": "groupwise",
}
html_theme_options = {
"style_external_links": False,
}

468
docs/index.html Normal file
View File

@ -0,0 +1,468 @@
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.15.2: http://docutils.sourceforge.net/" />
<title>index.rst</title>
<style type="text/css">
/*
:Author: David Goodger (goodger@python.org)
:Id: $Id: html4css1.css 7952 2016-07-26 18:15:59Z milde $
:Copyright: This stylesheet has been placed in the public domain.
Default cascading style sheet for the HTML output of Docutils.
See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
customize this style sheet.
*/
/* used to remove borders from tables and images */
.borderless, table.borderless td, table.borderless th {
border: 0 }
table.borderless td, table.borderless th {
/* Override padding for "table.docutils td" with "! important".
The right padding separates the table cells. */
padding: 0 0.5em 0 0 ! important }
.first {
/* Override more specific margin styles with "! important". */
margin-top: 0 ! important }
.last, .with-subtitle {
margin-bottom: 0 ! important }
.hidden {
display: none }
.subscript {
vertical-align: sub;
font-size: smaller }
.superscript {
vertical-align: super;
font-size: smaller }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] {
overflow: hidden;
}
/* Uncomment (and remove this text!) to get bold-faced definition list terms
dl.docutils dt {
font-weight: bold }
*/
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title, .code .error {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em ;
margin-right: 2em }
div.footer, div.header {
clear: both;
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin: 0 0 0.5em 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
margin-top: 0.4em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
img.align-left, .figure.align-left, object.align-left, table.align-left {
clear: left ;
float: left ;
margin-right: 1em }
img.align-right, .figure.align-right, object.align-right, table.align-right {
clear: right ;
float: right ;
margin-left: 1em }
img.align-center, .figure.align-center, object.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
table.align-center {
margin-left: auto;
margin-right: auto;
}
.align-left {
text-align: left }
.align-center {
clear: both ;
text-align: center }
.align-right {
text-align: right }
/* reset inner alignment in figures */
div.align-right {
text-align: inherit }
/* div.align-center * { */
/* text-align: left } */
.align-top {
vertical-align: top }
.align-middle {
vertical-align: middle }
.align-bottom {
vertical-align: bottom }
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font: inherit }
pre.literal-block, pre.doctest-block, pre.math, pre.code {
margin-left: 2em ;
margin-right: 2em }
pre.code .ln { color: grey; } /* line numbers */
pre.code, code { background-color: #eeeeee }
pre.code .comment, code .comment { color: #5C6576 }
pre.code .keyword, code .keyword { color: #3B0D06; font-weight: bold }
pre.code .literal.string, code .literal.string { color: #0C5404 }
pre.code .name.builtin, code .name.builtin { color: #352B84 }
pre.code .deleted, code .deleted { background-color: #DEB0A1}
pre.code .inserted, code .inserted { background-color: #A3D289}
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
span.section-subtitle {
/* font-size relative to parent (h1..h6 element) */
font-size: 80% }
table.citation {
border-left: solid 1px gray;
margin-left: 1px }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid 1px black;
margin-left: 1px }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
/* "booktabs" style (no vertical lines) */
table.docutils.booktabs {
border: 0px;
border-top: 2px solid;
border-bottom: 2px solid;
border-collapse: collapse;
}
table.docutils.booktabs * {
border: 0px;
}
table.docutils.booktabs th {
border-bottom: thin solid;
text-align: left;
}
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
ul.auto-toc {
list-style-type: none }
</style>
</head>
<body>
<div class="document">
<div class="section" id="sanic">
<h1>Sanic</h1>
<p>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.</p>
<p>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.</p>
<p>Sanic is developed <a class="reference external" href="https://github.com/channelcat/sanic/">on GitHub</a>. Contributions are welcome!</p>
<div class="section" id="sanic-aspires-to-be-simple">
<h2>Sanic aspires to be simple</h2>
<pre class="code python literal-block">
<span class="keyword namespace">from</span> <span class="name namespace">sanic</span> <span class="keyword namespace">import</span> <span class="name">Sanic</span>
<span class="keyword namespace">from</span> <span class="name namespace">sanic.response</span> <span class="keyword namespace">import</span> <span class="name">json</span>
<span class="name">app</span> <span class="operator">=</span> <span class="name">Sanic</span><span class="punctuation">()</span>
<span class="name decorator">&#64;app.route</span><span class="punctuation">(</span><span class="literal string double">&quot;/&quot;</span><span class="punctuation">)</span>
<span class="name">async</span> <span class="keyword">def</span> <span class="name function">test</span><span class="punctuation">(</span><span class="name">request</span><span class="punctuation">):</span>
<span class="keyword">return</span> <span class="name">json</span><span class="punctuation">({</span><span class="literal string double">&quot;hello&quot;</span><span class="punctuation">:</span> <span class="literal string double">&quot;world&quot;</span><span class="punctuation">})</span>
<span class="keyword">if</span> <span class="name variable magic">__name__</span> <span class="operator">==</span> <span class="literal string double">&quot;__main__&quot;</span><span class="punctuation">:</span>
<span class="name">app</span><span class="operator">.</span><span class="name">run</span><span class="punctuation">(</span><span class="name">host</span><span class="operator">=</span><span class="literal string double">&quot;0.0.0.0&quot;</span><span class="punctuation">,</span> <span class="name">port</span><span class="operator">=</span><span class="literal number integer">8000</span><span class="punctuation">)</span>
</pre>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">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.</p>
</div>
</div>
</div>
<div class="section" id="guides">
<h1>Guides</h1>
<div class="system-message">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">E:/OneDrive/GitHub/sanic/docs/index.rst</tt>, line 6)</p>
<p>Unknown directive type &quot;toctree&quot;.</p>
<pre class="literal-block">
.. 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
sanic/changelog
sanic/contributing
sanic/api_reference
sanic/asyncio_python37
</pre>
</div>
</div>
<div class="section" id="module-documentation">
<h1>Module Documentation</h1>
<div class="system-message">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">E:/OneDrive/GitHub/sanic/docs/index.rst</tt>, line 42)</p>
<p>Unknown directive type &quot;toctree&quot;.</p>
<pre class="literal-block">
.. toctree::
</pre>
</div>
<ul>
<li><p class="first"><a href="#id1"><span class="problematic" id="id2">:ref:`genindex`</span></a></p>
<div class="system-message" id="id1">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">E:/OneDrive/GitHub/sanic/docs/index.rst</tt>, line 44); <em><a href="#id2">backlink</a></em></p>
<p>Unknown interpreted text role &quot;ref&quot;.</p>
</div>
</li>
<li><p class="first"><a href="#id3"><span class="problematic" id="id4">:ref:`modindex`</span></a></p>
<div class="system-message" id="id3">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">E:/OneDrive/GitHub/sanic/docs/index.rst</tt>, line 45); <em><a href="#id4">backlink</a></em></p>
<p>Unknown interpreted text role &quot;ref&quot;.</p>
</div>
</li>
<li><p class="first"><a href="#id5"><span class="problematic" id="id6">:ref:`search`</span></a></p>
<div class="system-message" id="id5">
<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">E:/OneDrive/GitHub/sanic/docs/index.rst</tt>, line 46); <em><a href="#id6">backlink</a></em></p>
<p>Unknown interpreted text role &quot;ref&quot;.</p>
</div>
</li>
</ul>
</div>
</div>
</body>
</html>

View File

@ -1,36 +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
:maxdepth: 3
sanic/getting_started
sanic/routing
sanic/request_data
sanic/response
sanic/static_files
sanic/exceptions
sanic/middleware
sanic/blueprints
sanic/websocket
sanic/config
sanic/cookies
sanic/decorators
sanic/streaming
sanic/class_based_views
sanic/custom_protocol
sanic/sockets
sanic/ssl
sanic/logging
sanic/versioning
sanic/debug_mode
sanic/testing
sanic/deploying
sanic/extensions
sanic/contributing
👥 User Guide <https://sanicframework.org/guide/>
sanic/api_reference
💻 Source code <https://github.com/sanic-org/sanic/>
sanic/changelog
sanic/contributing
❓ Support <https://community.sanicframework.org/>
💬 Chat <https://discord.gg/FARQzAEMAA>
Module Documentation
@ -40,4 +27,3 @@ Module Documentation
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

33
docs/sanic/api/app.rst Normal file
View File

@ -0,0 +1,33 @@
Application
===========
sanic.app
---------
.. automodule:: sanic.app
:members:
:show-inheritance:
:inherited-members:
sanic.config
------------
.. automodule:: sanic.config
:members:
:show-inheritance:
sanic.application.constants
---------------------------
.. automodule:: sanic.application.constants
:exclude-members: StrEnum
:members:
:show-inheritance:
:inherited-members:
sanic.application.state
-----------------------
.. automodule:: sanic.application.state
:members:
:show-inheritance:

View File

@ -0,0 +1,17 @@
Blueprints
==========
sanic.blueprints
----------------
.. automodule:: sanic.blueprints
:members:
:show-inheritance:
:inherited-members:
sanic.blueprint_group
---------------------
.. automodule:: sanic.blueprint_group
:members:
:special-members:

48
docs/sanic/api/core.rst Normal file
View File

@ -0,0 +1,48 @@
Core
====
sanic.cookies
-------------
.. automodule:: sanic.cookies
:members:
:show-inheritance:
sanic.handlers
--------------
.. automodule:: sanic.handlers
:members:
:show-inheritance:
sanic.headers
--------------
.. automodule:: sanic.headers
:members:
:show-inheritance:
sanic.request
-------------
.. automodule:: sanic.request
:members:
:show-inheritance:
sanic.response
--------------
.. automodule:: sanic.response
:members:
:show-inheritance:
sanic.views
-----------
.. automodule:: sanic.views
:members:
:show-inheritance:

View File

@ -0,0 +1,16 @@
Exceptions
==========
sanic.errorpages
----------------
.. automodule:: sanic.errorpages
:members:
:show-inheritance:
sanic.exceptions
----------------
.. automodule:: sanic.exceptions
:members:
:show-inheritance:

18
docs/sanic/api/router.rst Normal file
View File

@ -0,0 +1,18 @@
Routing
=======
sanic_routing models
--------------------
.. autoclass:: sanic_routing.route::Route
:members:
.. autoclass:: sanic_routing.group::RouteGroup
:members:
sanic.router
------------
.. automodule:: sanic.router
:members:
:show-inheritance:

18
docs/sanic/api/server.rst Normal file
View File

@ -0,0 +1,18 @@
Sanic Server
============
sanic.http
----------
.. automodule:: sanic.http
:members:
:show-inheritance:
sanic.server
------------
.. automodule:: sanic.server
:members:
:show-inheritance:

View File

@ -0,0 +1,16 @@
Utility
=======
sanic.compat
------------
.. automodule:: sanic.compat
:members:
:show-inheritance:
sanic.log
---------
.. automodule:: sanic.log
:members:
:show-inheritance:

View File

@ -1,150 +1,13 @@
API Reference
=============
📑 API Reference
================
Submodules
----------
.. toctree::
:maxdepth: 2
sanic.app module
----------------
.. automodule:: sanic.app
:members:
:undoc-members:
:show-inheritance:
sanic.blueprints module
-----------------------
.. automodule:: sanic.blueprints
:members:
:undoc-members:
:show-inheritance:
sanic.config module
-------------------
.. automodule:: sanic.config
:members:
:undoc-members:
:show-inheritance:
sanic.constants module
----------------------
.. automodule:: sanic.constants
:members:
:undoc-members:
:show-inheritance:
sanic.cookies module
--------------------
.. automodule:: sanic.cookies
:members:
:undoc-members:
:show-inheritance:
sanic.exceptions module
-----------------------
.. automodule:: sanic.exceptions
:members:
:undoc-members:
:show-inheritance:
sanic.handlers module
---------------------
.. automodule:: sanic.handlers
:members:
:undoc-members:
:show-inheritance:
sanic.log module
----------------
.. automodule:: sanic.log
:members:
:undoc-members:
:show-inheritance:
sanic.request module
--------------------
.. automodule:: sanic.request
:members:
:undoc-members:
:show-inheritance:
sanic.response module
---------------------
.. automodule:: sanic.response
:members:
:undoc-members:
:show-inheritance:
sanic.router module
-------------------
.. automodule:: sanic.router
:members:
:undoc-members:
:show-inheritance:
sanic.server module
-------------------
.. 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
------------------
.. automodule:: sanic.views
:members:
:undoc-members:
:show-inheritance:
sanic.websocket module
----------------------
.. automodule:: sanic.websocket
:members:
:undoc-members:
:show-inheritance:
sanic.worker module
-------------------
.. automodule:: sanic.worker
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: sanic
:members:
:undoc-members:
:show-inheritance:
api/app
api/blueprints
api/core
api/exceptions
api/router
api/server
api/utility

View File

@ -1,256 +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.
```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.
```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:
```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:
```python
# api/content/authors.py
from sanic import Blueprint
authors = Blueprint('content_authors', url_prefix='/authors')
```
```python
# api/content/static.py
from sanic import Blueprint
static = Blueprint('content_static', url_prefix='/static')
```
```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')
```
```python
# api/info.py
from sanic import Blueprint
info = Blueprint('info', url_prefix='/info')
```
```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:
```python
# app.py
from sanic import Sanic
from .api import api
app = Sanic(__name__)
app.blueprint(api)
```
## Using blueprints
Blueprints have much 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.
### Middleware
Using blueprints allows you to also register middleware globally.
```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')
```
### Exceptions
Exceptions can be applied exclusively to blueprints globally.
```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.
```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
```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 `url_prefix` argument,
which will be prepended to all routes defined on the blueprint. This feature
can be used to implement our API versioning scheme.
```python
# blueprints.py
from sanic.response import text
from sanic import Blueprint
blueprint_v1 = Blueprint('v1', url_prefix='/v1')
blueprint_v2 = Blueprint('v2', url_prefix='/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` and `/v2` will now
point to the individual blueprints, which allows the creation of *sub-sites*
for each API version.
```python
# main.py
from sanic import Sanic
from blueprints import blueprint_v1, blueprint_v2
app = Sanic(__name__)
app.blueprint(blueprint_v1, url_prefix='/v1')
app.blueprint(blueprint_v2, url_prefix='/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:
```python
@blueprint_v1.route('/')
async def root(request):
url = request.app.url_for('v1.post_handler', post_id=5) # --> '/v1/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))
```

16
docs/sanic/changelog.rst Normal file
View File

@ -0,0 +1,16 @@
📜 Changelog
============
| 🔶 Current release
| 🔷 In support release
|
.. mdinclude:: ./releases/23/23.6.md
.. mdinclude:: ./releases/23/23.3.md
.. mdinclude:: ./releases/22/22.12.md
.. mdinclude:: ./releases/22/22.9.md
.. mdinclude:: ./releases/22/22.6.md
.. mdinclude:: ./releases/22/22.3.md
.. mdinclude:: ./releases/21/21.12.md
.. mdinclude:: ./releases/21/21.9.md
.. include:: ../../CHANGELOG.rst

View File

@ -1,166 +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.
```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.
```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.
```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.
```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:
```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:
```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:
```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`.

View File

@ -1,121 +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:
```
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:
```
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:
```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:
```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:
```
import myapp.default_settings
app = Sanic('myapp')
app.config.from_object(myapp.default_settings)
```
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:
```
app = Sanic('myapp')
app.config.from_envvar('MYAPP_SETTINGS')
```
Then you can run your application with the `MYAPP_SETTINGS` environment variable set:
```
$ 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:
```
# 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_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 take to force close non-idle connection (sec) |
| ACCESS_LOG | True | Disable or enable access log |
### The different Timeout variables:
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 a HTTP 408 response and sends that to the client. Adjust this value higher if your clients routinely pass very large request payloads or upload requests very slowly.
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 a HTTP 503 response and sets that to the client. Adjust this value higher if your application is likely to have long-running process that delay the generation of a response.
### What is Keep Alive? And what does the Keep Alive Timeout value do?
Keep-Alive is a HTTP feature indroduced in HTTP 1.1. When sending a HTTP request, the client (usually a web browser application) can set a Keep-Alive header to indicate for 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
```

View File

@ -1,62 +0,0 @@
# 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.
## Installation
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
a virtual environment already set up, then run:
```bash
python setup.py develop && pip install -r requirements-dev.txt
```
## Running tests
To run the tests for sanic it is recommended to use tox like so:
```bash
tox
```
See it's that simple!
## Pull requests!
So the pull request approval rules are pretty simple:
* 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 pass flake8 checks
* If you decide to remove/change anything from any common interface
a deprecation message should accompany it.
* If you implement a new feature you should have at least one unit
test to accompany it.
## 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
automatically generated using `sphinx-apidoc`.
To generate the documentation from scratch:
```bash
sphinx-apidoc -fo docs/_api/ sanic
sphinx-build -b html docs docs/_build
```
The HTML documentation will be created in the `docs/_build` folder.
## 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
merged. Please don't let this intimidate you! If you have any concerns about an
idea, open an issue for discussion and help.

View File

@ -0,0 +1,4 @@
♥️ Contributing
===============
.. include:: ../../CONTRIBUTING.rst

View File

@ -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/

View File

@ -1,72 +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`.
```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)
```

View File

@ -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 outputed
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)

View File

@ -1,39 +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.
```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'})
```

View File

@ -1,78 +0,0 @@
# Deploying
Deploying Sanic is made simple by the inbuilt 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).
## 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.
```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 server 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.
```python
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1337, workers=4)
```
## Running via Gunicorn
[Gunicorn](http://gunicorn.org/) Green Unicorn is a WSGI HTTP Server for UNIX.
Its a pre-fork worker model ported from Rubys 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.
## Asynchronous support
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):
```python
server = app.create_server(host="0.0.0.0", port=8000)
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(server)
loop.run_forever()
```

View File

@ -1,88 +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.
```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:
```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.
```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:
```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 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:
```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.

View File

@ -1,36 +0,0 @@
# Extensions
A list of Sanic extensions created by the community.
- [Sanic-Plugins-Framework](https://github.com/ashleysommer/sanicpluginsframework): Library for easily creating and using Sanic plugins.
- [Sessions](https://github.com/subyraman/sanic_session): Support for sessions.
Allows using redis, memcache or an in memory store.
- [CORS](https://github.com/ashleysommer/sanic-cors): A port of flask-cors.
- [Compress](https://github.com/subyraman/sanic_compress): Allows you to easily gzip Sanic responses. A port of Flask-Compress.
- [Jinja2](https://github.com/lixxu/sanic-jinja2): Support for Jinja2 template.
- [Sanic JWT](https://github.com/ahopkins/sanic-jwt): Authentication, JWT, and permission scoping for Sanic.
- [Sanic-JWT-Extended](https://github.com/devArtoria/Sanic-JWT-Extended): Provides extended JWT support for Sanic
- [OpenAPI/Swagger](https://github.com/channelcat/sanic-openapi): OpenAPI support, plus a Swagger UI.
- [Pagination](https://github.com/lixxu/python-paginate): Simple pagination support.
- [Motor](https://github.com/lixxu/sanic-motor): Simple motor wrapper.
- [Sanic CRUD](https://github.com/Typhon66/sanic_crud): CRUD REST API generation with peewee models.
- [UserAgent](https://github.com/lixxu/sanic-useragent): Add `user_agent` to request
- [Limiter](https://github.com/bohea/sanic-limiter): Rate limiting for sanic.
- [Sanic EnvConfig](https://github.com/jamesstidard/sanic-envconfig): Pull environment variables into your sanic config.
- [Babel](https://github.com/lixxu/sanic-babel): Adds i18n/l10n support to Sanic applications with the help of the
`Babel` library
- [Dispatch](https://github.com/ashleysommer/sanic-dispatcher): A dispatcher inspired by `DispatcherMiddleware` in werkzeug. Can act as a Sanic-to-WSGI adapter.
- [Sanic-OAuth](https://github.com/Sniedes722/Sanic-OAuth): OAuth Library for connecting to & creating your own token providers.
- [sanic-oauth](https://gitlab.com/SirEdvin/sanic-oauth): OAuth Library with many provider and OAuth1/OAuth2 support.
- [Sanic-nginx-docker-example](https://github.com/itielshwartz/sanic-nginx-docker-example): Simple and easy to use example of Sanic behined nginx using docker-compose.
- [sanic-graphql](https://github.com/graphql-python/sanic-graphql): GraphQL integration with Sanic
- [sanic-prometheus](https://github.com/dkruchinin/sanic-prometheus): Prometheus metrics for Sanic
- [Sanic-RestPlus](https://github.com/ashleysommer/sanic-restplus): A port of Flask-RestPlus for Sanic. Full-featured REST API with SwaggerUI generation.
- [sanic-transmute](https://github.com/yunstanford/sanic-transmute): A Sanic extension that generates APIs from python function and classes, and also generates Swagger UI/documentation automatically.
- [pytest-sanic](https://github.com/yunstanford/pytest-sanic): A pytest plugin for Sanic. It helps you to test your code asynchronously.
- [jinja2-sanic](https://github.com/yunstanford/jinja2-sanic): a jinja2 template renderer for Sanic.([Documentation](http://jinja2-sanic.readthedocs.io/en/latest/))
- [GINO](https://github.com/fantix/gino): An asyncio ORM on top of SQLAlchemy core, delivered with a Sanic extension. ([Documentation](https://python-gino.readthedocs.io/))
- [Sanic-Auth](https://github.com/pyx/sanic-auth): A minimal backend agnostic session-based user authentication mechanism for Sanic.
- [Sanic-CookieSession](https://github.com/pyx/sanic-cookiesession): A client-side only, cookie-based session, similar to the built-in session in Flask.
- [Sanic-WTF](https://github.com/pyx/sanic-wtf): Sanic-WTF makes using WTForms with Sanic and CSRF (Cross-Site Request Forgery) protection a little bit easier.
- [sanic-script](https://github.com/tim2anna/sanic-script): An extension for Sanic that adds support for writing commands to your application.
- [sanic-sse](https://github.com/inn0kenty/sanic_sse): [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) implementation for Sanic.

View File

@ -1,40 +0,0 @@
# Getting Started
Make sure you have both [pip](https://pip.pypa.io/en/stable/installing/) and at
least version 3.5 of Python before starting. Sanic uses the new `async`/`await`
syntax, so earlier versions of python won't work.
## 1. Install Sanic
```
python3 -m pip install sanic
```
## 2. Create a file called `main.py`
```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
```
python3 main.py
```
## 4. Check your browser
Open the address `http://0.0.0.0:8000` in your web browser. You should see
the message *Hello world!*.
You now have a working Sanic server!

View File

@ -1,25 +0,0 @@
Sanic
=================================
Sanic is a Flask-like Python 3.5+ web server that's written to go fast. It's based on the work done by the amazing folks at magicstack, and was inspired by `this article <https://magic.io/blog/uvloop-blazing-fast-python-networking/>`_.
On top of being Flask-like, Sanic supports async request handlers. This means you can use the new shiny async/await syntax from Python 3.5, making your code non-blocking and speedy.
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)

View File

@ -1,100 +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](https://docs.python.org/3/howto/logging.html). 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:
```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:
```python
app = Sanic('test', log_config=LOGGING_CONFIG)
```
And to close logging, simply assign access_log=False:
```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:
```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**:
- sanic.root:<br>
Used to log internal messages.
- sanic.error:<br>
Used to log error logs.
- sanic.access:<br>
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:
- host (str)<br>
request.ip
- request (str)<br>
request.method + " " + request.url
- status (int)<br>
response.status
- byte (int)<br>
len(response.body)
The default access log format is
```python
%(asctime)s - (%(name)s)[%(levelname)s][%(host)s]: %(request)s %(message)s %(status)d %(byte)d
```

View File

@ -1,147 +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:
```
@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.
```
app = Sanic(__name__)
@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.run(host="0.0.0.0", port=8000)
```
The above code will apply the two middleware in order. First, the middleware
**custom_banner** will change the HTTP response header *Server* to
*Fake-Server*, and the second middleware **prevent_xss** will add the HTTP
header for preventing Cross-Site-Scripting (XSS) attacks. These two functions
are invoked *after* a user function returns a response.
## 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.
```
@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')
```
## 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:
```
@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.
```
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.
```
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:
```
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:
```
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))
`

View File

@ -0,0 +1,66 @@
## Version 21.12.1 🔷
_Current LTS version_
- [#2349](https://github.com/sanic-org/sanic/pull/2349) Only display MOTD on startup
- [#2354](https://github.com/sanic-org/sanic/pull/2354) Ignore name argument in Python 3.7
- [#2355](https://github.com/sanic-org/sanic/pull/2355) Add config.update support for all config values
## Version 21.12.0 🔹
### Features
- [#2260](https://github.com/sanic-org/sanic/pull/2260) Allow early Blueprint registrations to still apply later added objects
- [#2262](https://github.com/sanic-org/sanic/pull/2262) Noisy exceptions - force logging of all exceptions
- [#2264](https://github.com/sanic-org/sanic/pull/2264) Optional `uvloop` by configuration
- [#2270](https://github.com/sanic-org/sanic/pull/2270) Vhost support using multiple TLS certificates
- [#2277](https://github.com/sanic-org/sanic/pull/2277) Change signal routing for increased consistency
- *BREAKING CHANGE*: If you were manually routing signals there is a breaking change. The signal router's `get` is no longer 100% determinative. There is now an additional step to loop thru the returned signals for proper matching on the requirements. If signals are being dispatched using `app.dispatch` or `bp.dispatch`, there is no change.
- [#2290](https://github.com/sanic-org/sanic/pull/2290) Add contextual exceptions
- [#2291](https://github.com/sanic-org/sanic/pull/2291) Increase join concat performance
- [#2295](https://github.com/sanic-org/sanic/pull/2295), [#2316](https://github.com/sanic-org/sanic/pull/2316), [#2331](https://github.com/sanic-org/sanic/pull/2331) Restructure of CLI and application state with new displays and more command parity with `app.run`
- [#2302](https://github.com/sanic-org/sanic/pull/2302) Add route context at definition time
- [#2304](https://github.com/sanic-org/sanic/pull/2304) Named tasks and new API for managing background tasks
- [#2307](https://github.com/sanic-org/sanic/pull/2307) On app auto-reload, provide insight of changed files
- [#2308](https://github.com/sanic-org/sanic/pull/2308) Auto extend application with [Sanic Extensions](https://sanicframework.org/en/plugins/sanic-ext/getting-started.html) if it is installed, and provide first class support for accessing the extensions
- [#2309](https://github.com/sanic-org/sanic/pull/2309) Builtin signals changed to `Enum`
- [#2313](https://github.com/sanic-org/sanic/pull/2313) Support additional config implementation use case
- [#2321](https://github.com/sanic-org/sanic/pull/2321) Refactor environment variable hydration logic
- [#2327](https://github.com/sanic-org/sanic/pull/2327) Prevent sending multiple or mixed responses on a single request
- [#2330](https://github.com/sanic-org/sanic/pull/2330) Custom type casting on environment variables
- [#2332](https://github.com/sanic-org/sanic/pull/2332) Make all deprecation notices consistent
- [#2335](https://github.com/sanic-org/sanic/pull/2335) Allow underscore to start instance names
### Bugfixes
- [#2273](https://github.com/sanic-org/sanic/pull/2273) Replace assignation by typing for `websocket_handshake`
- [#2285](https://github.com/sanic-org/sanic/pull/2285) Fix IPv6 display in startup logs
- [#2299](https://github.com/sanic-org/sanic/pull/2299) Dispatch `http.lifecyle.response` from exception handler
### Deprecations and Removals
- [#2306](https://github.com/sanic-org/sanic/pull/2306) Removal of deprecated items
- `Sanic` and `Blueprint` may no longer have arbitrary properties attached to them
- `Sanic` and `Blueprint` forced to have compliant names
- alphanumeric + `_` + `-`
- must start with letter or `_`
- `load_env` keyword argument of `Sanic`
- `sanic.exceptions.abort`
- `sanic.views.CompositionView`
- `sanic.response.StreamingHTTPResponse`
- *NOTE:* the `stream()` response method (where you pass a callable streaming function) has been deprecated and will be removed in v22.6. You should upgrade all streaming responses to the new style: https://sanicframework.org/en/guide/advanced/streaming.html#response-streaming
- [#2320](https://github.com/sanic-org/sanic/pull/2320) Remove app instance from Config for error handler setting
### Developer infrastructure
- [#2251](https://github.com/sanic-org/sanic/pull/2251) Change dev install command
- [#2286](https://github.com/sanic-org/sanic/pull/2286) Change codeclimate complexity threshold from 5 to 10
- [#2287](https://github.com/sanic-org/sanic/pull/2287) Update host test function names so they are not overwritten
- [#2292](https://github.com/sanic-org/sanic/pull/2292) Fail CI on error
- [#2311](https://github.com/sanic-org/sanic/pull/2311), [#2324](https://github.com/sanic-org/sanic/pull/2324) Do not run tests for draft PRs
- [#2336](https://github.com/sanic-org/sanic/pull/2336) Remove paths from coverage checks
- [#2338](https://github.com/sanic-org/sanic/pull/2338) Cleanup ports on tests
### Improved Documentation
- [#2269](https://github.com/sanic-org/sanic/pull/2269), [#2329](https://github.com/sanic-org/sanic/pull/2329), [#2333](https://github.com/sanic-org/sanic/pull/2333) Cleanup typos and fix language
### Miscellaneous
- [#2257](https://github.com/sanic-org/sanic/pull/2257), [#2294](https://github.com/sanic-org/sanic/pull/2294), [#2341](https://github.com/sanic-org/sanic/pull/2341) Add Python 3.10 support
- [#2279](https://github.com/sanic-org/sanic/pull/2279), [#2317](https://github.com/sanic-org/sanic/pull/2317), [#2322](https://github.com/sanic-org/sanic/pull/2322) Add/correct missing type annotations
- [#2305](https://github.com/sanic-org/sanic/pull/2305) Fix examples to use modern implementations

View File

@ -0,0 +1,50 @@
## Version 21.9.3
*Rerelease of v21.9.2 with some cleanup*
## Version 21.9.2
- [#2268](https://github.com/sanic-org/sanic/pull/2268) Make HTTP connections start in IDLE stage, avoiding delays and error messages
- [#2310](https://github.com/sanic-org/sanic/pull/2310) More consistent config setting with post-FALLBACK_ERROR_FORMAT apply
## Version 21.9.1
- [#2259](https://github.com/sanic-org/sanic/pull/2259) Allow non-conforming ErrorHandlers
## Version 21.9.0
### Features
- [#2158](https://github.com/sanic-org/sanic/pull/2158), [#2248](https://github.com/sanic-org/sanic/pull/2248) Complete overhaul of I/O to websockets
- [#2160](https://github.com/sanic-org/sanic/pull/2160) Add new 17 signals into server and request lifecycles
- [#2162](https://github.com/sanic-org/sanic/pull/2162) Smarter `auto` fallback formatting upon exception
- [#2184](https://github.com/sanic-org/sanic/pull/2184) Introduce implementation for copying a Blueprint
- [#2200](https://github.com/sanic-org/sanic/pull/2200) Accept header parsing
- [#2207](https://github.com/sanic-org/sanic/pull/2207) Log remote address if available
- [#2209](https://github.com/sanic-org/sanic/pull/2209) Add convenience methods to BP groups
- [#2216](https://github.com/sanic-org/sanic/pull/2216) Add default messages to SanicExceptions
- [#2225](https://github.com/sanic-org/sanic/pull/2225) Type annotation convenience for annotated handlers with path parameters
- [#2236](https://github.com/sanic-org/sanic/pull/2236) Allow Falsey (but not-None) responses from route handlers
- [#2238](https://github.com/sanic-org/sanic/pull/2238) Add `exception` decorator to Blueprint Groups
- [#2244](https://github.com/sanic-org/sanic/pull/2244) Explicit static directive for serving file or dir (ex: `static(..., resource_type="file")`)
- [#2245](https://github.com/sanic-org/sanic/pull/2245) Close HTTP loop when connection task cancelled
### Bugfixes
- [#2188](https://github.com/sanic-org/sanic/pull/2188) Fix the handling of the end of a chunked request
- [#2195](https://github.com/sanic-org/sanic/pull/2195) Resolve unexpected error handling on static requests
- [#2208](https://github.com/sanic-org/sanic/pull/2208) Make blueprint-based exceptions attach and trigger in a more intuitive manner
- [#2211](https://github.com/sanic-org/sanic/pull/2211) Fixed for handling exceptions of asgi app call
- [#2213](https://github.com/sanic-org/sanic/pull/2213) Fix bug where ws exceptions not being logged
- [#2231](https://github.com/sanic-org/sanic/pull/2231) Cleaner closing of tasks by using `abort()` in strategic places to avoid dangling sockets
- [#2247](https://github.com/sanic-org/sanic/pull/2247) Fix logging of auto-reload status in debug mode
- [#2246](https://github.com/sanic-org/sanic/pull/2246) Account for BP with exception handler but no routes
### Developer infrastructure
- [#2194](https://github.com/sanic-org/sanic/pull/2194) HTTP unit tests with raw client
- [#2199](https://github.com/sanic-org/sanic/pull/2199) Switch to codeclimate
- [#2214](https://github.com/sanic-org/sanic/pull/2214) Try Reopening Windows Tests
- [#2229](https://github.com/sanic-org/sanic/pull/2229) Refactor `HttpProtocol` into a base class
- [#2230](https://github.com/sanic-org/sanic/pull/2230) Refactor `server.py` into multi-file module
### Miscellaneous
- [#2173](https://github.com/sanic-org/sanic/pull/2173) Remove Duplicated Dependencies and PEP 517 Support
- [#2193](https://github.com/sanic-org/sanic/pull/2193), [#2196](https://github.com/sanic-org/sanic/pull/2196), [#2217](https://github.com/sanic-org/sanic/pull/2217) Type annotation changes

View File

@ -0,0 +1,55 @@
## Version 22.12.0 🔷
_Current version_
### Features
- [#2569](https://github.com/sanic-org/sanic/pull/2569) Add `JSONResponse` class with some convenient methods when updating a response object
- [#2598](https://github.com/sanic-org/sanic/pull/2598) Change `uvloop` requirement to `>=0.15.0`
- [#2609](https://github.com/sanic-org/sanic/pull/2609) Add compatibility with `websockets` v11.0
- [#2610](https://github.com/sanic-org/sanic/pull/2610) Kill server early on worker error
- Raise deadlock timeout to 30s
- [#2617](https://github.com/sanic-org/sanic/pull/2617) Scale number of running server workers
- [#2621](https://github.com/sanic-org/sanic/pull/2621) [#2634](https://github.com/sanic-org/sanic/pull/2634) Send `SIGKILL` on subsequent `ctrl+c` to force worker exit
- [#2622](https://github.com/sanic-org/sanic/pull/2622) Add API to restart all workers from the multiplexer
- [#2624](https://github.com/sanic-org/sanic/pull/2624) Default to `spawn` for all subprocesses unless specifically set:
```python
from sanic import Sanic
Sanic.start_method = "fork"
```
- [#2625](https://github.com/sanic-org/sanic/pull/2625) Filename normalisation of form-data/multipart file uploads
- [#2626](https://github.com/sanic-org/sanic/pull/2626) Move to HTTP Inspector:
- Remote access to inspect running Sanic instances
- TLS support for encrypted calls to Inspector
- Authentication to Inspector with API key
- Ability to extend Inspector with custom commands
- [#2632](https://github.com/sanic-org/sanic/pull/2632) Control order of restart operations
- [#2633](https://github.com/sanic-org/sanic/pull/2633) Move reload interval to class variable
- [#2636](https://github.com/sanic-org/sanic/pull/2636) Add `priority` to `register_middleware` method
- [#2639](https://github.com/sanic-org/sanic/pull/2639) Add `unquote` to `add_route` method
- [#2640](https://github.com/sanic-org/sanic/pull/2640) ASGI websockets to receive `text` or `bytes`
### Bugfixes
- [#2607](https://github.com/sanic-org/sanic/pull/2607) Force socket shutdown before close to allow rebinding
- [#2590](https://github.com/sanic-org/sanic/pull/2590) Use actual `StrEnum` in Python 3.11+
- [#2615](https://github.com/sanic-org/sanic/pull/2615) Ensure middleware executes only once per request timeout
- [#2627](https://github.com/sanic-org/sanic/pull/2627) Crash ASGI application on lifespan failure
- [#2635](https://github.com/sanic-org/sanic/pull/2635) Resolve error with low-level server creation on Windows
### Deprecations and Removals
- [#2608](https://github.com/sanic-org/sanic/pull/2608) [#2630](https://github.com/sanic-org/sanic/pull/2630) Signal conditions and triggers saved on `signal.extra`
- [#2626](https://github.com/sanic-org/sanic/pull/2626) Move to HTTP Inspector
- 🚨 *BREAKING CHANGE*: Moves the Inspector to a Sanic app from a simple TCP socket with a custom protocol
- *DEPRECATE*: The `--inspect*` commands have been deprecated in favor of `inspect ...` commands
- [#2628](https://github.com/sanic-org/sanic/pull/2628) Replace deprecated `distutils.strtobool`
### Developer infrastructure
- [#2612](https://github.com/sanic-org/sanic/pull/2612) Add CI testing for Python 3.11

View File

@ -0,0 +1,52 @@
## Version 22.3.0
### Features
- [#2347](https://github.com/sanic-org/sanic/pull/2347) API for multi-application server
- 🚨 *BREAKING CHANGE*: The old `sanic.worker.GunicornWorker` has been **removed**. To run Sanic with `gunicorn`, you should use it thru `uvicorn` [as described in their docs](https://www.uvicorn.org/#running-with-gunicorn).
- 🧁 *SIDE EFFECT*: Named background tasks are now supported, even in Python 3.7
- [#2357](https://github.com/sanic-org/sanic/pull/2357) Parse `Authorization` header as `Request.credentials`
- [#2361](https://github.com/sanic-org/sanic/pull/2361) Add config option to skip `Touchup` step in application startup
- [#2372](https://github.com/sanic-org/sanic/pull/2372) Updates to CLI help messaging
- [#2382](https://github.com/sanic-org/sanic/pull/2382) Downgrade warnings to backwater debug messages
- [#2396](https://github.com/sanic-org/sanic/pull/2396) Allow for `multidict` v0.6
- [#2401](https://github.com/sanic-org/sanic/pull/2401) Upgrade CLI catching for alternative application run types
- [#2402](https://github.com/sanic-org/sanic/pull/2402) Conditionally inject CLI arguments into factory
- [#2413](https://github.com/sanic-org/sanic/pull/2413) Add new start and stop event listeners to reloader process
- [#2414](https://github.com/sanic-org/sanic/pull/2414) Remove loop as required listener arg
- [#2415](https://github.com/sanic-org/sanic/pull/2415) Better exception for bad URL parsing
- [sanic-routing#47](https://github.com/sanic-org/sanic-routing/pull/47) Add a new extention parameter type: `<file:ext>`, `<file:ext=jpg>`, `<file:ext=jpg|png|gif|svg>`, `<file=int:ext>`, `<file=int:ext=jpg|png|gif|svg>`, `<file=float:ext=tar.gz>`
- 👶 *BETA FEATURE*: This feature will not work with `path` type matching, and is being released as a beta feature only.
- [sanic-routing#57](https://github.com/sanic-org/sanic-routing/pull/57) Change `register_pattern` to accept a `str` or `Pattern`
- [sanic-routing#58](https://github.com/sanic-org/sanic-routing/pull/58) Default matching on non-empty strings only, and new `strorempty` pattern type
- 🚨 *BREAKING CHANGE*: Previously a route with a dynamic string parameter (`/<foo>` or `/<foo:str>`) would match on any string, including empty strings. It will now **only** match a non-empty string. To retain the old behavior, you should use the new parameter type: `/<foo:strorempty>`.
### Bugfixes
- [#2373](https://github.com/sanic-org/sanic/pull/2373) Remove `error_logger` on websockets
- [#2381](https://github.com/sanic-org/sanic/pull/2381) Fix newly assigned `None` in task registry
- [sanic-routing#52](https://github.com/sanic-org/sanic-routing/pull/52) Add type casting to regex route matching
- [sanic-routing#60](https://github.com/sanic-org/sanic-routing/pull/60) Add requirements check on regex routes (this resolves, for example, multiple static directories with differing `host` values)
### Deprecations and Removals
- [#2362](https://github.com/sanic-org/sanic/pull/2362) 22.3 Deprecations and changes
1. `debug=True` and `--debug` do _NOT_ automatically run `auto_reload`
2. Default error render is with plain text (browsers still get HTML by default because `auto` looks at headers)
3. `config` is required for `ErrorHandler.finalize`
4. `ErrorHandler.lookup` requires two positional args
5. Unused websocket protocol args removed
- [#2344](https://github.com/sanic-org/sanic/pull/2344) Deprecate loading of lowercase environment variables
### Developer infrastructure
- [#2363](https://github.com/sanic-org/sanic/pull/2363) Revert code coverage back to Codecov
- [#2405](https://github.com/sanic-org/sanic/pull/2405) Upgrade tests for `sanic-routing` changes
- [sanic-testing#35](https://github.com/sanic-org/sanic-testing/pull/35) Allow for httpx v0.22
### Improved Documentation
- [#2350](https://github.com/sanic-org/sanic/pull/2350) Fix link in README for ASGI
- [#2398](https://github.com/sanic-org/sanic/pull/2398) Document middleware on_request and on_response
- [#2409](https://github.com/sanic-org/sanic/pull/2409) Add missing documentation for `Request.respond`
### Miscellaneous
- [#2376](https://github.com/sanic-org/sanic/pull/2376) Fix typing for `ListenerMixin.listener`
- [#2383](https://github.com/sanic-org/sanic/pull/2383) Clear deprecation warning in `asyncio.wait`
- [#2387](https://github.com/sanic-org/sanic/pull/2387) Cleanup `__slots__` implementations
- [#2390](https://github.com/sanic-org/sanic/pull/2390) Clear deprecation warning in `asyncio.get_event_loop`

View File

@ -0,0 +1,54 @@
## Version 22.6.2
### Bugfixes
- [#2522](https://github.com/sanic-org/sanic/pull/2522) Always show server location in ASGI
## Version 22.6.1
### Bugfixes
- [#2477](https://github.com/sanic-org/sanic/pull/2477) Sanic static directory fails when folder name ends with ".."
## Version 22.6.0
### Features
- [#2378](https://github.com/sanic-org/sanic/pull/2378) Introduce HTTP/3 and autogeneration of TLS certificates in `DEBUG` mode
- 👶 *EARLY RELEASE FEATURE*: Serving Sanic over HTTP/3 is an early release feature. It does not yet fully cover the HTTP/3 spec, but instead aims for feature parity with Sanic's existing HTTP/1.1 server. Websockets, WebTransport, push responses are examples of some features not yet implemented.
- 📦 *EXTRA REQUIREMENT*: Not all HTTP clients are capable of interfacing with HTTP/3 servers. You may need to install a [HTTP/3 capable client](https://curl.se/docs/http3.html).
- 📦 *EXTRA REQUIREMENT*: In order to use TLS autogeneration, you must install either [mkcert](https://github.com/FiloSottile/mkcert) or [trustme](https://github.com/python-trio/trustme).
- [#2416](https://github.com/sanic-org/sanic/pull/2416) Add message to `task.cancel`
- [#2420](https://github.com/sanic-org/sanic/pull/2420) Add exception aliases for more consistent naming with standard HTTP response types (`BadRequest`, `MethodNotAllowed`, `RangeNotSatisfiable`)
- [#2432](https://github.com/sanic-org/sanic/pull/2432) Expose ASGI `scope` as a property on the `Request` object
- [#2438](https://github.com/sanic-org/sanic/pull/2438) Easier access to websocket class for annotation: `from sanic import Websocket`
- [#2439](https://github.com/sanic-org/sanic/pull/2439) New API for reading form values with options: `Request.get_form`
- [#2445](https://github.com/sanic-org/sanic/pull/2445) Add custom `loads` function
- [#2447](https://github.com/sanic-org/sanic/pull/2447), [#2486](https://github.com/sanic-org/sanic/pull/2486) Improved API to support setting cache control headers
- [#2453](https://github.com/sanic-org/sanic/pull/2453) Move verbosity filtering to logger
- [#2475](https://github.com/sanic-org/sanic/pull/2475) Expose getter for current request using `Request.get_current()`
### Bugfixes
- [#2448](https://github.com/sanic-org/sanic/pull/2448) Fix to allow running with `pythonw.exe` or places where there is no `sys.stdout`
- [#2451](https://github.com/sanic-org/sanic/pull/2451) Trigger `http.lifecycle.request` signal in ASGI mode
- [#2455](https://github.com/sanic-org/sanic/pull/2455) Resolve typing of stacked route definitions
- [#2463](https://github.com/sanic-org/sanic/pull/2463) Properly catch websocket CancelledError in websocket handler in Python 3.7
### Deprecations and Removals
- [#2487](https://github.com/sanic-org/sanic/pull/2487) v22.6 deprecations and changes
1. Optional application registry
1. Execution of custom handlers after some part of response was sent
1. Configuring fallback handlers on the `ErrorHandler`
1. Custom `LOGO` setting
1. `sanic.response.stream`
1. `AsyncioServer.init`
### Developer infrastructure
- [#2449](https://github.com/sanic-org/sanic/pull/2449) Clean up `black` and `isort` config
- [#2479](https://github.com/sanic-org/sanic/pull/2479) Fix some flappy tests
### Improved Documentation
- [#2461](https://github.com/sanic-org/sanic/pull/2461) Update example to match current application naming standards
- [#2466](https://github.com/sanic-org/sanic/pull/2466) Better type annotation for `Extend`
- [#2485](https://github.com/sanic-org/sanic/pull/2485) Improved help messages in CLI

View File

@ -0,0 +1,74 @@
## Version 22.9.1
### Features
- [#2585](https://github.com/sanic-org/sanic/pull/2585) Improved error message when no applications have been registered
### Bugfixes
- [#2578](https://github.com/sanic-org/sanic/pull/2578) Add certificate loader for in process certificate creation
- [#2591](https://github.com/sanic-org/sanic/pull/2591) Do not use sentinel identity for `spawn` compatibility
- [#2592](https://github.com/sanic-org/sanic/pull/2592) Fix properties in nested blueprint groups
- [#2595](https://github.com/sanic-org/sanic/pull/2595) Introduce sleep interval on new worker reloader
### Deprecations and Removals
### Developer infrastructure
- [#2588](https://github.com/sanic-org/sanic/pull/2588) Markdown templates on issue forms
### Improved Documentation
- [#2556](https://github.com/sanic-org/sanic/pull/2556) v22.9 documentation
- [#2582](https://github.com/sanic-org/sanic/pull/2582) Cleanup documentation on Windows support
## Version 22.9.0
### Features
- [#2445](https://github.com/sanic-org/sanic/pull/2445) Add custom loads function
- [#2490](https://github.com/sanic-org/sanic/pull/2490) Make `WebsocketImplProtocol` async iterable
- [#2499](https://github.com/sanic-org/sanic/pull/2499) Sanic Server WorkerManager refactor
- [#2506](https://github.com/sanic-org/sanic/pull/2506) Use `pathlib` for path resolution (for static file serving)
- [#2508](https://github.com/sanic-org/sanic/pull/2508) Use `path.parts` instead of `match` (for static file serving)
- [#2513](https://github.com/sanic-org/sanic/pull/2513) Better request cancel handling
- [#2516](https://github.com/sanic-org/sanic/pull/2516) Add request properties for HTTP method info:
- `request.is_safe`
- `request.is_idempotent`
- `request.is_cacheable`
- *See* [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) *for more information about when these apply*
- [#2522](https://github.com/sanic-org/sanic/pull/2522) Always show server location in ASGI
- [#2526](https://github.com/sanic-org/sanic/pull/2526) Cache control support for static files for returning 304 when appropriate
- [#2533](https://github.com/sanic-org/sanic/pull/2533) Refactor `_static_request_handler`
- [#2540](https://github.com/sanic-org/sanic/pull/2540) Add signals before and after handler execution
- `http.handler.before`
- `http.handler.after`
- [#2542](https://github.com/sanic-org/sanic/pull/2542) Add *[redacted]* to CLI :)
- [#2546](https://github.com/sanic-org/sanic/pull/2546) Add deprecation warning filter
- [#2550](https://github.com/sanic-org/sanic/pull/2550) Middleware priority and performance enhancements
### Bugfixes
- [#2495](https://github.com/sanic-org/sanic/pull/2495) Prevent directory traversion with static files
- [#2515](https://github.com/sanic-org/sanic/pull/2515) Do not apply double slash to paths in certain static dirs in Blueprints
### Deprecations and Removals
- [#2525](https://github.com/sanic-org/sanic/pull/2525) Warn on duplicate route names, will be prevented outright in v23.3
- [#2537](https://github.com/sanic-org/sanic/pull/2537) Raise warning and deprecation notice on duplicate exceptions, will be prevented outright in v23.3
### Developer infrastructure
- [#2504](https://github.com/sanic-org/sanic/pull/2504) Cleanup test suite
- [#2505](https://github.com/sanic-org/sanic/pull/2505) Replace Unsupported Python Version Number from the Contributing Doc
- [#2530](https://github.com/sanic-org/sanic/pull/2530) Do not include tests folder in installed package resolver
### Improved Documentation
- [#2502](https://github.com/sanic-org/sanic/pull/2502) Fix a few typos
- [#2517](https://github.com/sanic-org/sanic/pull/2517) [#2536](https://github.com/sanic-org/sanic/pull/2536) Add some type hints

View File

@ -0,0 +1,53 @@
## Version 23.3.0
### Features
- [#2545](https://github.com/sanic-org/sanic/pull/2545) Standardize init of exceptions for more consistent control of HTTP responses using exceptions
- [#2606](https://github.com/sanic-org/sanic/pull/2606) Decode headers as UTF-8 also in ASGI
- [#2646](https://github.com/sanic-org/sanic/pull/2646) Separate ASGI request and lifespan callables
- [#2659](https://github.com/sanic-org/sanic/pull/2659) Use ``FALLBACK_ERROR_FORMAT`` for handlers that return ``empty()``
- [#2662](https://github.com/sanic-org/sanic/pull/2662) Add basic file browser (HTML page) and auto-index serving
- [#2667](https://github.com/sanic-org/sanic/pull/2667) Nicer traceback formatting (HTML page)
- [#2668](https://github.com/sanic-org/sanic/pull/2668) Smarter error page rendering format selection; more reliant upon header and "common sense" defaults
- [#2680](https://github.com/sanic-org/sanic/pull/2680) Check the status of socket before shutting down with ``SHUT_RDWR``
- [#2687](https://github.com/sanic-org/sanic/pull/2687) Refresh ``Request.accept`` functionality to be more performant and spec-compliant
- [#2696](https://github.com/sanic-org/sanic/pull/2696) Add header accessors as properties
```
Example-Field: Foo, Bar
Example-Field: Baz
```
```python
request.headers.example_field == "Foo, Bar,Baz"
```
- [#2700](https://github.com/sanic-org/sanic/pull/2700) Simpler CLI targets
```sh
$ sanic path.to.module:app # global app instance
$ sanic path.to.module:create_app # factory pattern
$ sanic ./path/to/directory/ # simple serve
```
- [#2701](https://github.com/sanic-org/sanic/pull/2701) API to define a number of workers in managed processes
- [#2704](https://github.com/sanic-org/sanic/pull/2704) Add convenience for dynamic changes to routing
- [#2706](https://github.com/sanic-org/sanic/pull/2706) Add convenience methods for cookie creation and deletion
```python
response = text("...")
response.add_cookie("test", "It worked!", domain=".yummy-yummy-cookie.com")
```
- [#2707](https://github.com/sanic-org/sanic/pull/2707) Simplified ``parse_content_header`` escaping to be RFC-compliant and remove outdated FF hack
- [#2710](https://github.com/sanic-org/sanic/pull/2710) Stricter charset handling and escaping of request URLs
- [#2711](https://github.com/sanic-org/sanic/pull/2711) Consume body on ``DELETE`` by default
- [#2719](https://github.com/sanic-org/sanic/pull/2719) Allow ``password`` to be passed to TLS context
- [#2720](https://github.com/sanic-org/sanic/pull/2720) Skip middleware on ``RequestCancelled``
- [#2721](https://github.com/sanic-org/sanic/pull/2721) Change access logging format to ``%s``
- [#2722](https://github.com/sanic-org/sanic/pull/2722) Add ``CertLoader`` as application option for directly controlling ``SSLContext`` objects
- [#2725](https://github.com/sanic-org/sanic/pull/2725) Worker sync state tolerance on race condition
### Bugfixes
- [#2651](https://github.com/sanic-org/sanic/pull/2651) ASGI websocket to pass thru bytes as is
- [#2697](https://github.com/sanic-org/sanic/pull/2697) Fix comparison between datetime aware and naive in ``file`` when using ``If-Modified-Since``
### Deprecations and Removals
- [#2666](https://github.com/sanic-org/sanic/pull/2666) Remove deprecated ``__blueprintname__`` property
### Improved Documentation
- [#2712](https://github.com/sanic-org/sanic/pull/2712) Improved example using ``'https'`` to create the redirect

View File

@ -0,0 +1,33 @@
## Version 23.6.0 🔶
### Features
- [#2670](https://github.com/sanic-org/sanic/pull/2670) Increase `KEEP_ALIVE_TIMEOUT` default to 120 seconds
- [#2716](https://github.com/sanic-org/sanic/pull/2716) Adding allow route overwrite option in blueprint
- [#2724](https://github.com/sanic-org/sanic/pull/2724) and [#2792](https://github.com/sanic-org/sanic/pull/2792) Add a new exception signal for ALL exceptions raised anywhere in application
- [#2727](https://github.com/sanic-org/sanic/pull/2727) Add name prefixing to BP groups
- [#2754](https://github.com/sanic-org/sanic/pull/2754) Update request type on middleware types
- [#2770](https://github.com/sanic-org/sanic/pull/2770) Better exception message on startup time application induced import error
- [#2776](https://github.com/sanic-org/sanic/pull/2776) Set multiprocessing start method early
- [#2785](https://github.com/sanic-org/sanic/pull/2785) Add custom typing to config and ctx objects
- [#2790](https://github.com/sanic-org/sanic/pull/2790) Add `request.client_ip`
### Bugfixes
- [#2728](https://github.com/sanic-org/sanic/pull/2728) Fix traversals for intended results
- [#2729](https://github.com/sanic-org/sanic/pull/2729) Handle case when headers argument of ResponseStream constructor is None
- [#2737](https://github.com/sanic-org/sanic/pull/2737) Fix type annotation for `JSONREsponse` default content type
- [#2740](https://github.com/sanic-org/sanic/pull/2740) Use Sanic's serializer for JSON responses in the Inspector
- [#2760](https://github.com/sanic-org/sanic/pull/2760) Support for `Request.get_current` in ASGI mode
- [#2773](https://github.com/sanic-org/sanic/pull/2773) Alow Blueprint routes to explicitly define error_format
- [#2774](https://github.com/sanic-org/sanic/pull/2774) Resolve headers on different renderers
- [#2782](https://github.com/sanic-org/sanic/pull/2782) Resolve pypy compatibility issues
### Deprecations and Removals
- [#2777](https://github.com/sanic-org/sanic/pull/2777) Remove Python 3.7 support
### Developer infrastructure
- [#2766](https://github.com/sanic-org/sanic/pull/2766) Unpin setuptools version
- [#2779](https://github.com/sanic-org/sanic/pull/2779) Run keep alive tests in loop to get available port
### Improved Documentation
- [#2741](https://github.com/sanic-org/sanic/pull/2741) Better documentation examples about running Sanic
From that list, the items to highlight in the release notes:

View File

@ -1,128 +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
```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.
```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 })
```
- `raw_args` (dict) - On many cases you would need to access the url arguments in
a less packed dictionary. For same previous URL `?key1=value1&key2=value2`, the
`raw_args` dictionary would look like `{'key1': 'value1', 'key2': 'value2'}`.
- `files` (dictionary of `File` objects) - List of files that have a name, body, and type
```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.
```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.
```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.
```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` or `https`
- `host`: The host associated with the request: `localhost:8080`
- `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=`
## Accessing values using `get` and `getlist`
The request properties which return a dictionary actually return 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*.
```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']
```

View File

@ -1,112 +0,0 @@
# Response
Use functions in `sanic.response` module to create responses.
## Plain Text
```python
from sanic import response
@app.route('/text')
def handle_request(request):
return response.text('Hello world!')
```
## HTML
```python
from sanic import response
@app.route('/html')
def handle_request(request):
return response.html('<p>Hello world!</p>')
```
## JSON
```python
from sanic import response
@app.route('/json')
def handle_request(request):
return response.json({'message': 'Hello world!'})
```
## File
```python
from sanic import response
@app.route('/file')
async def handle_request(request):
return await response.file('/srv/www/whatever.png')
```
## Streaming
```python
from sanic import response
@app.route("/streaming")
async def index(request):
async def streaming_fn(response):
response.write('foo')
response.write('bar')
return response.stream(streaming_fn, content_type='text/plain')
```
## File Streaming
For large files, a combination of File and Streaming above
```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
```python
from sanic import response
@app.route('/redirect')
def handle_request(request):
return response.redirect('/json')
```
## Raw
Response without encoding the body
```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:
```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
)
```

View File

@ -1,335 +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:
```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.
```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.
```python
from sanic.response import text
@app.route('/number/<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('/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))
```
## 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.
```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.
```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:
```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:
```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:
```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:
```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:
```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 support now and will be ignored). For example:
```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 passed argument _server or SERVER_NAME in app.config or 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 one time
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 thrown.
## WebSocket routes
Routes for the WebSocket protocol can be defined with the `@app.websocket`
decorator:
```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:
```python
async def feed(request, ws):
pass
app.add_websocket_route(my_websocket_handler, '/feed')
```
Handlers for a WebSocket route are passed 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.
```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)
```
## User defined route name
You can pass `name` to change the route name to avoid using the default name (`handler.__name__`).
```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
You can use `url_for` for static file url building now.
If it's for file directly, `filename` can be ignored.
```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'
```

View File

@ -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``

View File

@ -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)

View File

@ -1,83 +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.
```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')
# 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 spefic **virtual host** with `host` argument. For example:
```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:
```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:
```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)
```

View File

@ -1,106 +0,0 @@
# Streaming
## Request Streaming
Sanic allows you to get request data by stream, as below. When the request ends, `request.stream.get()` returns `None`. Only post, put and patch decorator have stream argument.
```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.get()
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.get()
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_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8').replace('1', 'A')
return text(result)
async def post_handler(request):
result = ''
while True:
body = await request.stream.get()
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:
```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:
```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)
```

View File

@ -1,127 +0,0 @@
# Testing
Sanic endpoints can be tested locally using the `test_client` object, which
depends on the additional [aiohttp](https://aiohttp.readthedocs.io/en/stable/)
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:
```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 `aiohttp`.
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 aiohttp ClientSession request.
For example, to supply data to a GET request, you would do the following:
```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:
```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 aiohttp can be found
[in the documentation for ClientSession](https://aiohttp.readthedocs.io/en/stable/client_reference.html#client-session).
## 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,
```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.
```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}
```

View File

@ -1,50 +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.
```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:
```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.
```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:
```bash
curl localhost/v1/html
```

View File

@ -1,52 +0,0 @@
WebSocket
=========
Sanic supports websockets, 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 are passed 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.

View File

@ -1,21 +0,0 @@
name: py35
dependencies:
- openssl=1.0.2g=0
- pip=8.1.1=py35_0
- python=3.5.1=0
- readline=6.2=2
- setuptools=20.3=py35_0
- sqlite=3.9.2=0
- tk=8.5.18=0
- wheel=0.29.0=py35_0
- xz=5.0.5=1
- zlib=1.2.8=0
- pip:
- uvloop>=0.5.3
- httptools>=0.0.10
- ujson>=1.35
- aiofiles>=0.3.0
- websockets>=6.0
- sphinxcontrib-asyncio>=0.2.0
- multidict>=4.0,<5.0
- https://github.com/channelcat/docutils-fork/zipball/master

View File

@ -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"]

View File

@ -4,12 +4,14 @@ import asyncio
from sanic import Sanic
app = Sanic()
app = Sanic("Example")
async def notify_server_started_after_five_seconds():
await asyncio.sleep(5)
print('Server successfully started!')
print("Server successfully started!")
app.add_task(notify_server_started_after_five_seconds())

View File

@ -0,0 +1,29 @@
from random import randint
from sanic import Sanic
from sanic.response import text
app = Sanic("Example")
@app.middleware("request")
def append_request(request):
request.ctx.num = randint(0, 100)
@app.get("/pop")
def pop_handler(request):
return text(request.ctx.num)
@app.get("/key_exist")
def key_exist_handler(request):
# Check the key is exist or not
if hasattr(request.ctx, "num"):
return text("num exist in request")
return text("num does not exist in request")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)

View File

@ -1,10 +1,12 @@
# -*- coding: utf-8 -*-
from sanic import Sanic
from functools import wraps
from sanic import Sanic
from sanic.response import json
app = Sanic()
app = Sanic("Example")
def check_request_for_authorization_status(request):
@ -13,30 +15,30 @@ def check_request_for_authorization_status(request):
return flag
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)
def authorized(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
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
@app.route("/")
@authorized()
@authorized
async def test(request):
return json({'status': 'authorized'})
return json({"status": "authorized"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)

View File

@ -0,0 +1,54 @@
from sanic import Blueprint, Sanic
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("Example")
bp = Blueprint("bp_example")
@bp.on_request
def request_middleware_1(request):
print("1")
@bp.on_request
def request_middleware_2(request):
print("2")
@bp.on_request
def request_middleware_3(request):
print("3")
@bp.on_response
def resp_middleware_4(request, response):
print("4")
@bp.on_response
def resp_middleware_5(request, response):
print("5")
@bp.on_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")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True, auto_reload=False)

View File

@ -1,38 +1,41 @@
from sanic import Blueprint, Sanic
from sanic.response import file, json
app = Sanic(__name__)
blueprint = Blueprint('name', url_prefix='/my_blueprint')
blueprint2 = Blueprint('name2', url_prefix='/my_blueprint2')
blueprint3 = Blueprint('name3', url_prefix='/my_blueprint3')
app = Sanic("Example")
blueprint = Blueprint("bp_example", url_prefix="/my_blueprint")
blueprint2 = Blueprint("bp_example2", url_prefix="/my_blueprint2")
blueprint3 = Blueprint("bp_example3", url_prefix="/my_blueprint3")
@blueprint.route('/foo')
@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)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=9999, debug=True)

View File

@ -0,0 +1,22 @@
from asyncio import sleep
from sanic import Sanic, response
app = Sanic("DelayedResponseApp", strict_slashes=True)
app.config.AUTO_EXTEND = False
@app.get("/")
async def handler(request):
return response.redirect("/sleep/3")
@app.get("/sleep/<t:float>")
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)

View File

@ -7,8 +7,10 @@ and pass in an instance of it when we create our Sanic instance. Inside this
class' default handler, we can do anything including sending exceptions to
an external service.
"""
from sanic.handlers import ErrorHandler
from sanic.exceptions import SanicException
from sanic.handlers import ErrorHandler
"""
Imports and code relevant for our CustomHandler class
(Ordinarily this would be in a separate file)
@ -16,7 +18,6 @@ Imports and code relevant for our CustomHandler class
class CustomHandler(ErrorHandler):
def default(self, request, exception):
# Here, we have access to the exception object
# and can do anything with it (log, send to external service, etc)
@ -38,17 +39,17 @@ server's error_handler to an instance of our CustomHandler
from sanic import Sanic
app = Sanic(__name__)
handler = CustomHandler()
app.error_handler = handler
app = Sanic("Example", error_handler=handler)
@app.route("/")
async def test(request):
# Here, something occurs which causes an unexpected exception
# This exception will flow to our custom handler.
raise SanicException('You Broke It!')
raise SanicException("You Broke It!")
if __name__ == '__main__':
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)

View File

@ -1,7 +1,7 @@
from sanic import Sanic
from sanic import response
from sanic import Sanic, response
app = Sanic(__name__)
app = Sanic("Example")
@app.route("/")
@ -9,5 +9,5 @@ async def test(request):
return response.json({"test": True})
if __name__ == '__main__':
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)

73
examples/http_redirect.py Normal file
View File

@ -0,0 +1,73 @@
from sanic import Sanic, response, text
from sanic.handlers import ErrorHandler
from sanic.server.async_server import AsyncioServer
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="https",
)
return response.redirect(url)
@https.main_process_start
async def start(app, _):
http_server = await http.create_server(
port=HTTP_PORT, return_asyncio_server=True
)
app.add_task(runner(http, http_server))
app.ctx.http_server = http_server
app.ctx.http = http
@https.main_process_stop
async def stop(app, _):
await app.ctx.http_server.before_stop()
await app.ctx.http_server.close()
for connection in app.ctx.http_server.connections:
connection.close_if_idle()
await app.ctx.http_server.after_stop()
app.ctx.http = False
async def runner(app: Sanic, app_server: AsyncioServer):
app.is_running = True
try:
app.signalize()
app.finalize()
ErrorHandler.finalize(app.error_handler)
app_server.init = True
await app_server.before_start()
await app_server.after_start()
await app_server.serve_forever()
finally:
app.is_running = False
app.is_stopping = True
if __name__ == "__main__":
https.run(port=HTTPS_PORT, debug=True)

View File

@ -1,26 +1,30 @@
import asyncio
import httpx
from sanic import Sanic
from sanic.response import json
import asyncio
import aiohttp
app = Sanic(__name__)
app = Sanic("Example")
sem = None
@app.listener('before_server_start')
def init(sanic, loop):
@app.before_server_start
def init(sanic, _):
global sem
concurrency_per_worker = 4
sem = asyncio.Semaphore(concurrency_per_worker, loop=loop)
sem = asyncio.Semaphore(concurrency_per_worker)
async def bounded_fetch(session, url):
"""
Use session object to perform 'get' request on url
"""
async with sem, session.get(url) as response:
return await response.json()
async with sem:
response = await session.get(url)
return response.json()
@app.route("/")
@ -28,11 +32,12 @@ async def test(request):
"""
Download and serve example JSON
"""
url = "https://api.github.com/repos/channelcat/sanic"
url = "https://api.github.com/repos/sanic-org/sanic"
async with aiohttp.ClientSession() as session:
async with httpx.AsyncClient() as session:
response = await bounded_fetch(session, url)
return json(response)
app.run(host="0.0.0.0", port=8000, workers=2)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, workers=2)

View File

@ -1,86 +1,74 @@
'''
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
from contextvars import ContextVar
from sanic import Sanic, response
import uvloop
import aiotask_context as context
log = logging.getLogger(__name__)
class RequestIdFilter(logging.Filter):
def filter(self, record):
record.request_id = context.get('X-Request-ID')
try:
record.request_id = app.ctx.request_id.get(None) or "n/a"
except AttributeError:
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 = Sanic("Example", 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())
context.set("X-Request-ID", request_id)
request.app.ctx.request_id.set(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", 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)
loop = asyncio.get_event_loop()
loop.set_task_factory(context.task_factory)
task = asyncio.ensure_future(server)
try:
loop.run_forever()
except:
loop.stop()
@app.before_server_start
def setup(app, loop):
app.ctx.request_id = ContextVar("request_id")
if __name__ == "__main__":
app.run(port=9999, debug=True)

View File

@ -0,0 +1,60 @@
import logging
import socket
from os import getenv
from platform import node
from uuid import getnode as get_mac
from logdna import LogDNAHandler
from sanic import Sanic
from sanic.request import Request
from sanic.response import json
log = logging.getLogger("logdna")
log.setLevel(logging.INFO)
def get_my_ip_address(remote_server="google.com"):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((remote_server, 80))
return s.getsockname()[0]
def get_mac_address():
h = iter(hex(get_mac())[2:].zfill(12))
return ":".join(i + next(h) for i in h)
logdna_options = {
"app": __name__,
"index_meta": True,
"hostname": node(),
"ip": get_my_ip_address(),
"mac": get_mac_address(),
}
logdna_handler = LogDNAHandler(
getenv("LOGDNA_API_KEY"), options=logdna_options
)
logdna = logging.getLogger(__name__)
logdna.setLevel(logging.INFO)
logdna.addHandler(logdna_handler)
app = Sanic("Example")
@app.middleware
def log_request(request: Request):
logdna.info("I was Here with a new Request to URL: {}".format(request.url))
@app.route("/")
def default(request):
return json({"response": "I was here"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=getenv("PORT", 8080))

View File

@ -2,27 +2,29 @@
Modify header or status in response
"""
from sanic import Sanic
from sanic import response
app = Sanic(__name__)
from sanic import Sanic, response
@app.route('/')
app = Sanic("Example")
@app.route("/")
def handle_request(request):
return response.json(
{'message': 'Hello world!'},
headers={'X-Served-By': 'sanic'},
status=200
{"message": "Hello world!"},
headers={"X-Served-By": "sanic"},
status=200,
)
@app.route('/unauthorized')
@app.route("/unauthorized")
def handle_request(request):
return response.json(
{'message': 'You are not authorized'},
headers={'X-Served-By': 'sanic'},
status=404
{"message": "You are not authorized"},
headers={"X-Served-By": "sanic"},
status=404,
)
app.run(host="0.0.0.0", port=8000, debug=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)

Some files were not shown because too many files have changed in this diff Show More