Async Python 3.6+ web server/framework | Build fast. Run fast.

Overview

Sanic | Build fast. Run fast.

Sanic | Build fast. Run fast.

Build
Docs Documentation
Package
Support
Stats

Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allows the usage of the async/await syntax added in Python 3.5, which makes your code non-blocking and speedy.

Sanic is also ASGI compliant, so you can deploy it with an alternative ASGI webserver.

Source code on GitHub | Help and discussion board.

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.

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.

$ 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.

Note

Windows support is currently "experimental" and on a best-effort basis. Multiple workers are also not currently supported on Windows (see Issue #1517), but setting workers=1 should launch the server successfully.

Hello World Example

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)

Sanic can now be easily run using sanic hello.app.

[2018-12-30 11:37:41 +0200] [13564] [INFO] Goin' Fast @ http://0.0.0.0:8000
[2018-12-30 11:37:41 +0200] [13564] [INFO] Starting worker [13564]

And, we can verify it is working: curl localhost:8000 -i

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!

Documentation

Documentation on Readthedocs.

Changelog

Release Changelogs.

Questions and Discussion

Ask a question or join the conversation.

Contribution

We are always happy to have new contributions. We have marked issues good for anyone looking to get started, and welcome questions on the forums. Please take a look at our Contribution guidelines.

Comments
  • New release on Pypi ?

    New release on Pypi ?

    Hello,

    I was looking for a tool to autoreload my code when I develop and I found this commit : https://github.com/channelcat/sanic/commit/52c2a8484e6aa5fa13aaade49e1f2597dd006e15

    So it seems Sanic already integrates it since December 07, 2017. But the the latest version on Pypi dates from the day before (https://github.com/channelcat/sanic/commit/1ea3ab7fe8ab03a6ddf4d75a3de8cb719f4c584c) : https://pypi.org/project/Sanic/#history

    Is-it possible to release a new version on Pypi please ? Other features (like the UUID support in routes) are also interesting :)

    Thanks in advance !

    opened by ncrocfer 46
  • New websockets

    New websockets

    Resolves #2000

    @aaugustin @ahopkins I've spent another couple of days on it, and its now passing all of the tests, including some other demo applications I've written to stress it out.

    It certainly needs cleaning up, and could probably get some efficiency improvements in places too, but otherwise I'm pretty happy with it.

    This branch also incorporates another change I've written, that splits the existing server.HttpProtocol out into a base SanicProtocol class, that contains just all of the connection-handling and transport-layer stuff, and HttpProtocol that is a subclass of SanicProtocol and adds the HTTP-specific handlers on top of that. I'd like the new WebSocketProtocol to subclass SanicProtocol but for now it still subclasses HttpProtocol.

    opened by ashleysommer 44
  • Random Failures during tox run on Mac

    Random Failures during tox run on Mac

    Describe the bug When running Unit Test in local machine (mac), few test cases randomly fail and re-cover during re-run.

    Error Output

    # Test session starts (platform: darwin, Python 3.5.6, pytest 3.3.2, pytest-sugar 0.9.1)
        def test_default_server_error_request_timeout():
            client = DelayableSanicTestClient(request_timeout_default_app, None, 3)
            request, response = client.get('/1')
    >       assert response.status == 408
    E       assert 200 == 408
    E        +  where 200 = <test_request_timeout.DelayableTCPConnector.RequestContextManager object at 0x10723ccf8>.status
    tests/test_request_timeout.py:194: AssertionError
    
    # Test session starts (platform: darwin, Python 3.7.0, pytest 3.3.2, pytest-sugar 0.9.1)
        def test_default_server_error_request_timeout():
            client = DelayableSanicTestClient(request_timeout_default_app, None, 3)
            request, response = client.get('/1')
    >       assert response.status == 408
    E       assert 200 == 408
    E        +  where 200 = <test_request_timeout.DelayableTCPConnector.RequestContextManager object at 0x112d87470>.status
    tests/test_request_timeout.py:194: AssertionError
    
    # py37-no-ext develop-inst-nodeps: <path>
    # py37-no-ext installed: aiofiles==0.4.0,aiohttp==3.2.1,async-generator==1.10,async-timeout==3.0.1,attrs==18.2.0,beautifulsoup4==4.6.3,chardet==2.3.0,coverage==4.5.1,gunicorn==19.9.0,httptools==0.0.11,idna==2.7,multidict==4.4.2,pluggy==0.6.0,py==1.7.0,pytest==3.3.2,pytest-cov==2.6.0,pytest-sanic==0.1.13,pytest-sugar==0.9.1,-e [email protected]:harshanarayana/sanic.git@e3a27c2cc485d57aa1ff87d9f69098e4ab12727e#egg=sanic,six==1.11.0,termcolor==1.1.0,websockets==6.0,yarl==1.2.6
    # py37-no-ext run-test-pre: PYTHONHASHSEED='27345397'
    # py37-no-ext runtests: commands[0] | pytest tests --cov sanic --cov-report=
    # Test session starts (platform: darwin, Python 3.7.0, pytest 3.3.2, pytest-sugar 0.9.1)E       AssertionError: assert {'Connection'...p-Alive': '2'} == {'Connection':...p-Alive': '2'}
    E         Omitting 3 identical items, use -vv to show
    E         Differing items:
    E         {'Content-Length': '12'} != {'Content-Length': '11'}
    

    Code snippet NA

    Expected behavior Existing Unit Tests to pass in all Virtual env during tox execution.

    Environment (please complete the following information):

    • OS: macOS Mojave
    • Version 10.14 (18A391)

    Additional context NA

    needs investigation 
    opened by harshanarayana 43
  • ASGI refactoring attempt

    ASGI refactoring attempt

    This isn't intended to be graceful at this point, rather just to make a start on getting passing tests, using an ASGI-based app, connected to an ASGI-based test client.

    The application changes are intended to be the dumbest possible thing that could provide the ASGI interface, with the intention that once the test suite was passing or sufficiently passing, then refactoring towards something far more graceful could start.

    There are two changes:

    • The Sanic class has an ASGI based __call__ interface, that calls into a dumb shim layer.
    • The SanicTestClient is replaced from an aiohttp client that makes actual network requests, into a requests based client, that has an adapter to make ASGI requests direct to the application.

    Because the requests interface differs in places to the aiohttp client interface, there's a bit of fiddling around to ensure that API compatibility. Again, this is just the dumbest possible place to start, with a view to moving to something more graceful later.

    opened by tomchristie 42
  • Nicer error handling after eof, warning for second response being created

    Nicer error handling after eof, warning for second response being created

    Trying to solve issue: https://github.com/sanic-org/sanic/issues/2219

    Some doubts I still have:

    1. Whether it's okay to put a response reference in request instance. I recently learned from the memory leak issue; we should not create more reference if not necessary. I am considering replace it with a bool flag.
    2. Should we only allow one response instance for each request? If so, we can consider keep and cache the response reference and return it if request.respond method is called more than 1 time.
    3. I believe that self.response_func is None and self.stage == Stage.IDLE implies the request has been responded and the response stream is ended. Am I correct on this?

    Please let me know your suggestions, thanks! @sanic-org/core-devs

    opened by ChihweiLHBird 32
  • Unicode character parsing

    Unicode character parsing

    Per #539 there may be a continued problem in parsing unicode characters due to a dependency.

    Per @vltr: /中国 or even /jacaré would break on request.py, mostly because of httptools.parse_url that receives bytes and is unable to parse non-ascii chars. I'll need to dig deeper to see if this is a restraint in httptools itself or just in the Python bindings.

    needs investigation 
    opened by sjsadowski 32
  • Doc rework

    Doc rework

    In reference to https://github.com/huge-success/sanic/issues/1691 I have moved all markdown docs to rst. The discussion over why we went for rst vs md can be seen in full in the issue chat.

    There is a minor bug with the table in the configuration page where the top row doesn't seem to have splits, but I am not sure if that is a rst "feature" vs an actual bug. Also, the routing on the left nav bar for some reason seems to be broken and I am unsure as to why.

    I ran a tox check but it skipped due to win32 not in list There are a large number of errors when I build it with sphinx, but those are to do with api_reference and _sanic which are files I have not touched, nor understand.

    opened by Lagicrus 30
  • Templates support

    Templates support

    What do you think about integrate templates (jinja2?) into sanic core? I think the popularity of django and flask largely depends on their ability to write and distribute independent apps, which contains its own routes, handlers, templates and static files. Sanic has all of this except of templates.

    If you agree, I suggest the next api:

    render_string('index.html', context)
    render('index.html', context)
    @app.context_processor
    @bp.context_processor
    @app.template('index.html')
    @bp.template('index.html')
    
    nice to have idea discussion 
    opened by imbolc 29
  • Documentation for Removal of Routes

    Documentation for Removal of Routes

    Although the functions are fairly self-explanatory, they are completely absent from the documentation.

    EDIT: To elaborate, it should be documented that although add_route and routes can add routes with/without trailing slashes, remove_routes has no behavior to account for that.

    help wanted documentation 
    opened by Vleerian 28
  • Call For Contributors - Discussion

    Call For Contributors - Discussion

    Sanic Web Framework - Call for Contributors

    While some industry analysts have observed an increase in activity on open source projects during the current pandemic, unfortunately that is not the case for all open source projects.

    Since its initial public release in 2016, the Sanic Web Framework has had several waves of interest and short bursts of contribution activity, with just a handful of dedicated long-term contributors forming a core-contributors group.

    In January 2020 the Sanic organization announced a new Organization Structure adopting a PEP-8016 model including electing a new Release-Managers team, a new Steering-Council, and writing our S.C.O.P.E.

    Unfortunately since March 2020, both of our release managers, two of the steering council members, and three core contributors have left the project due to pressures from the pandemic and other commitments. While we're disappointed to see them leave, we wish them and their families well and all the best in their future endeavors.

    The Sanic Web Framework is more popular now than ever, with thousands of downloads from PyPI daily, Sanic is used in almost 3500 other open source projects on GitHub.

    The steering council has made a decision to put out a call for contributors. Sanic is a project of, and a product of, the community; everyone has a voice and the ability to help make decisions. The goal of the Sanic project is to be community built. The strength and direction of the project is decision by consensus as laid out in the S.C.O.P.E.

    Doesn't matter if you have a masters in computer science, are a senior software engineer, an intern, or are a high school student. The great thing about open source is anybody can contribute.

    Where can I chat to the team about this?

    We have a pretty active Community Forum as well as the Gitter chatroom. If you prefer to use Github, you can reply to this issue.

    Why should I contribute? I don't know how to contribute! What can I even offer?

    Working on a bleeding edge web framework is excellent material for your resume and you learn a lot. Many of us got awesome jobs because of our open source commitments. See the Opensource Guide's article on Why Contribute to Open Source?

    TL;DR?

    A large portion of the contributors to the Sanic project are no longer able to help, we need your help.

    stale 
    opened by ashleysommer 27
  • Socket binding implemented properly for IPv6 and UNIX sockets.

    Socket binding implemented properly for IPv6 and UNIX sockets.

    • app.run("::1") for IPv6
    • ~~app.run("unix:/tmp/server.sock")~~ app.run(unix="/tmp/server.sock") for UNIX sockets
    • app.run("localhost") retains old functionality (randomly either IPv4 or IPv6, or with workers=1 might be both)

    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.

    opened by Tronic 27
  • Enforce unique route names

    Enforce unique route names

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Is your feature request related to a problem? Please describe.

    No response

    Describe the solution you'd like

    In v23.3 we will begin enforcing unique route names. We will need to force routes with multiple hosts to have a unique name with something like this:

    diff --git a/sanic/router.py b/sanic/router.py
    index b68fde3b..b2e0fc69 100644
    --- a/sanic/router.py
    +++ b/sanic/router.py
    @@ -139,6 +139,9 @@ class Router(BaseRouter):
                 route.extra.static = static
                 route.extra.error_format = error_format
     
    +            if len(hosts) > 1 and host:
    +                route.name = f"{route.name}__host_{host.replace('.', '_')}"
    +
                 if error_format:
                     check_error_format(route.extra.error_format)
    

    Additional context

    No response

    feature request 
    opened by ahopkins 0
  • Sanic closes connection prematurely

    Sanic closes connection prematurely

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Describe the bug

    When a client downloads data slowly from a Sanic server, Sanic terminates the connection before all data has been downloaded. Specifically, the connection is terminated before all of the data specified by the content-length header has been downloaded.

    I previously raised this as #2613, but that was closed. I'm raising this again because I'm pretty sure this is a bug.

    Code snippet

    Run the following Sanic server:

    from sanic import Sanic
    from sanic.response import raw
    
    app = Sanic("MyHelloWorldApp")
    app.config.REQUEST_TIMEOUT = 2000
    app.config.RESPONSE_TIMEOUT = 2000
    
    
    @app.get("/foo")
    async def foo_handler(request):
        print(f"HEADERS: {request.headers}")
        data = bytearray(500 * 1024 * 1024)
        return raw(data)
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    In a separate process, run this client application:

    from time import sleep
    
    import requests
    import logging
    
    logging.basicConfig(level=logging.DEBUG)
    
    url = 'http://127.0.0.1:8000/foo'
    s = requests.Session()
    r = s.get(url, stream=True)
    content_length = int(r.headers["content-length"])
    print(f"Content length: {content_length}")
    total = 0
    for chunk in r.iter_content(chunk_size=1024 * 1024):
        total += len(chunk)
        sleep(0.1)
        print(f"Total downloaded: {total}")
    
    assert total == content_length, f"Expected {content_length} bytes, but got {total} bytes"
    

    Expected Behavior

    I would expect the amount of data specified by the content-length header to be downloaded. However, the client fails with an error like this:

    AssertionError: Expected 524288000 bytes, but got 222742503 bytes
    

    Note that the amount of data downloaded is not always the same, but is reliably less than the length specified by the content-length header on my machine.

    A Wireshark capture appears to show the server sending a FIN while the client is still downloading data.

    Screenshot 2022-12-07 at 10 45 56

    How do you run Sanic?

    As a script (app.run or Sanic.serve)

    Operating System

    Mac OS 12.2.1 (also appears to happen on Linux in our production system)

    Sanic Version

    22.9.1 (also tried 21.12.1 and it happens there too)

    Additional context

    This does not happen on the old version of Sanic we were using previously (19.12.5).

    The behaviour can be changed, but not solved, by changing Sanic's KEEP_ALIVE_TIMEOUT to a larger value. However, it's still possible to reproduce the issue by downloading the data slightly more slowly. For example setting KEEP_ALIVE_TIMEOUT to 75 seconds, and the sleep time in the client to 0.5 seconds still reproduces the issue.

    necessary 
    opened by nfergu 6
  • HTTP 1 request headers decoded using default encoding instead of ISO-8859-1

    HTTP 1 request headers decoded using default encoding instead of ISO-8859-1

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Describe the bug

    headers are decoded here without specifying their encoding:

    https://github.com/sanic-org/sanic/blob/ad4e526c775fc3ce950503d6476d9d344492b0dd/sanic/http/http1.py#L205

    On my system (osx using python 3.10.8 installed via homebrew) this causes bytes that are valid characters in ISO-8859-1 but not in UTF-8 to be decoded as surrogate escape characters, e.g. b"\x80" becomes "\udf80" instead of "\x80"

    Code snippet

    No response

    Expected Behavior

    headers encoded as ISO-8859-1 with no MIME type to be decoded correctly without using UTF-8 surrogate escape characters.

    How do you run Sanic?

    As a script (app.run or Sanic.serve)

    Operating System

    linux

    Sanic Version

    22.9.1

    Additional context

    this used to work as expected in Sanic<=20.12.7

    bug on hold 
    opened by relud 13
  • Sanic on pypy

    Sanic on pypy

        Looks like Sanic is again not installable with pypy, tested with Dockerfile like this:
    
    FROM pypy:3.9-slim-buster
    ENV SANIC_NO_UVLOOP=true
    ENV SANIC_NO_UJSON=true
    RUN pip install sanic
    

    Originally posted by @laurivosandi in https://github.com/sanic-org/sanic/issues/747#issuecomment-1304905651

    opened by ahopkins 0
  • SanicException.message is always None

    SanicException.message is always None

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Describe the bug

    Raising SanicException with a custom message does not assign it to the message attribute. It's always empty.

    Code snippet

    import logging
    
    from sanic import Sanic
    from sanic.exceptions import Forbidden, NotFound, SanicException
    from sanic.request import Request
    from sanic.response import json
    
    app = Sanic(__name__)
    
    
    @app.route('/unauthorized')
    async def unauthorized(request: Request):
        raise SanicException(message="Unauthorized!!!", status_code=401)
    
    
    @app.route('/forbidden')
    async def forbidden(request: Request):
        raise Forbidden(message="Forbidden!!!")
    
    
    @app.route('/not-found')
    async def not_found(request: Request):
        raise NotFound()
    
    
    @app.exception(SanicException)
    async def error_handler(req: Request, err: SanicException):
        logging.error(f"err: {err.message}", exc_info=err)
        return json({"response_code": err.status_code, "error": err.message})
    
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=8080, dev=True)
    

    Expected Behavior

    No response

    How do you run Sanic?

    ASGI

    Operating System

    Mac

    Sanic Version

    22.9.1

    Additional context

    No response

    bug 
    opened by Thirumalai 1
Releases(v22.12.0)
  • v22.12.0(Dec 27, 2022)

    Features

    • #2569 Add JSONResponse class with some convenient methods when updating a response object
    • #2598 Change uvloop requirement to >=0.15.0
    • #2609 Add compatibility with websockets v11.0
    • #2610 Kill server early on worker error
      • Raise deadlock timeout to 30s
    • #2617 Scale number of running server workers
    • #2621 #2634 Send SIGKILL on subsequent ctrl+c to force worker exit
    • #2622 Add API to restart all workers from the multiplexer
    • #2624 Default to spawn for all subprocesses unless specifically set:
      from sanic import Sanic
      
      Sanic.start_method = "fork"
      
    • #2625 Filename normalisation of form-data/multipart file uploads
    • #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 Control order of restart operations
    • #2633 Move reload interval to class variable
    • #2636 Add priority to register_middleware method
    • #2639 Add unquote to add_route method
    • #2640 ASGI websockets to receive text or bytes

    Bugfixes

    • #2607 Force socket shutdown before close to allow rebinding
    • #2590 Use actual StrEnum in Python 3.11+
    • #2615 Ensure middleware executes only once per request timeout
    • #2627 Crash ASGI application on lifespan failure
    • #2635 Resolve error with low-level server creation on Windows

    Deprecations and Removals

    • #2608 #2630 Signal conditions and triggers saved on signal.extra
    • #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 Replace deprecated distutils.strtobool

    Developer infrastructure

    • #2612 Add CI testing for Python 3.11

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.9.1...v22.12.0

    Source code(tar.gz)
    Source code(zip)
  • v22.9.1(Oct 31, 2022)

    What's Changed

    • docs: sanic now supports windows by @SaidBySolo in https://github.com/sanic-org/sanic/pull/2582
    • Upgrade markdown templates to issue forms by @ahopkins in https://github.com/sanic-org/sanic/pull/2588
    • improve error message if no apps found in registry by @scardozos in https://github.com/sanic-org/sanic/pull/2585
    • fix: sideeffects created by changing fork to spawn by @SaidBySolo in https://github.com/sanic-org/sanic/pull/2591
    • 22.9 Docs by @ahopkins in https://github.com/sanic-org/sanic/pull/2556
    • Add interval sleep in reloader by @ahopkins in https://github.com/sanic-org/sanic/pull/2595
    • Resolve edge case in nested BP Groups by @ahopkins in https://github.com/sanic-org/sanic/pull/2592
    • Add GenericCreator for loading SSL certs in processes by @ahopkins in https://github.com/sanic-org/sanic/pull/2578

    New Contributors

    • @scardozos made their first contribution in https://github.com/sanic-org/sanic/pull/2585

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.9.0...v22.9.1

    Source code(tar.gz)
    Source code(zip)
  • v22.9.0(Sep 29, 2022)

    Features

    • #2445 Add custom loads function
    • #2490 Make WebsocketImplProtocol async iterable
    • #2499 Sanic Server WorkerManager refactor
    • #2506 Use pathlib for path resolution (for static file serving)
    • #2508 Use path.parts instead of match (for static file serving)
    • #2513 Better request cancel handling
    • #2516 Add request properties for HTTP method info:
      • request.is_safe
      • request.is_idempotent
      • request.is_cacheable
      • See MDN docs for more information about when these apply
    • #2522 Always show server location in ASGI
    • #2526 Cache control support for static files for returning 304 when appropriate
    • #2533 Refactor _static_request_handler
    • #2540 Add signals before and after handler execution
      • http.handler.before
      • http.handler.after
    • #2542 Add [redacted] to CLI :)
    • #2546 Add deprecation warning filter
    • #2550 Middleware priority and performance enhancements

    Bugfixes

    • #2495 Prevent directory traversion with static files
    • #2515 Do not apply double slash to paths in certain static dirs in Blueprints

    Deprecations and Removals

    • #2525 Warn on duplicate route names, will be prevented outright in v23.3
    • #2537 Raise warning and deprecation notice on duplicate exceptions, will be prevented outright in v23.3

    Developer infrastructure

    • #2504 Cleanup test suite
    • #2505 Replace Unsupported Python Version Number from the Contributing Doc
    • #2530 Do not include tests folder in installed package resolver

    Improved Documentation


    New Contributors

    • @huntzhan made their first contribution in https://github.com/sanic-org/sanic/pull/2530
    • @monosans made their first contribution in https://github.com/sanic-org/sanic/pull/2536

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.6.0...v22.9.0

    Source code(tar.gz)
    Source code(zip)
  • v22.6.2(Aug 11, 2022)

  • v22.6.1(Jul 31, 2022)

    Resolves #2477 and #2478 See also #2495 and https://github.com/sanic-org/sanic/security/advisories/GHSA-8cw9-5hmv-77w6

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.6.0...v22.6.1

    Source code(tar.gz)
    Source code(zip)
  • v21.12.2(Jul 31, 2022)

    Resolves #2477 and #2478 See also #2495 and https://github.com/sanic-org/sanic/security/advisories/GHSA-8cw9-5hmv-77w6

    Full Changelog: https://github.com/sanic-org/sanic/compare/v21.12.1...v21.12.2

    Source code(tar.gz)
    Source code(zip)
  • v20.12.7(Jul 31, 2022)

    Resolves #2477 and #2478 See also #2495 and https://github.com/sanic-org/sanic/security/advisories/GHSA-8cw9-5hmv-77w6

    Full Changelog: https://github.com/sanic-org/sanic/compare/v20.12.6...v20.12.7

    Source code(tar.gz)
    Source code(zip)
  • v22.6.0(Jun 30, 2022)

    Features

    • #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.
      • 📦 EXTRA REQUIREMENT: In order to use TLS autogeneration, you must install either mkcert or trustme.
    • #2416 Add message to task.cancel
    • #2420 Add exception aliases for more consistent naming with standard HTTP response types (BadRequest, MethodNotAllowed, RangeNotSatisfiable)
    • #2432 Expose ASGI scope as a property on the Request object
    • #2438 Easier access to websocket class for annotation: from sanic import Websocket
    • #2439 New API for reading form values with options: Request.get_form
    • #2445 Add custom loads function
    • #2447, #2486 Improved API to support setting cache control headers
    • #2453 Move verbosity filtering to logger
    • #2475 Expose getter for current request using Request.get_current()

    Bugfixes

    • #2448 Fix to allow running with pythonw.exe or places where there is no sys.stdout
    • #2451 Trigger http.lifecycle.request signal in ASGI mode
    • #2455 Resolve typing of stacked route definitions
    • #2463 Properly catch websocket CancelledError in websocket handler in Python 3.7

    Deprecations and Removals

    • #2487 v22.6 deprecations and changes
      1. Optional application registry
      2. Execution of custom handlers after some part of response was sent
      3. Configuring fallback handlers on the ErrorHandler
      4. Custom LOGO setting
      5. sanic.response.stream
      6. AsyncioServer.init

    Developer infrastructure

    • #2449 Clean up black and isort config
    • #2479 Fix some flappy tests

    Improved Documentation

    • #2461 Update example to match current application naming standards
    • #2466 Better type annotation for Extend
    • #2485 Improved help messages in CLI

    New Contributors

    • @azimovMichael made their first contribution in https://github.com/sanic-org/sanic/pull/2432
    • @amitay87 made their first contribution in https://github.com/sanic-org/sanic/pull/2461
    • @zozzz made their first contribution in https://github.com/sanic-org/sanic/pull/2451
    • @kijk2869 made their first contribution in https://github.com/sanic-org/sanic/pull/2466
    • @timmo001 made their first contribution in https://github.com/sanic-org/sanic/pull/2448

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.3.1...v22.6.0

    Source code(tar.gz)
    Source code(zip)
  • v22.3.2(May 11, 2022)

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.3.1...v22.3.2

    • Resolve warning issue with error handler mismatch warning https://github.com/sanic-org/sanic/commit/3a1a9f071df24e2fe0ff5aac7d529019034fe898
    Source code(tar.gz)
    Source code(zip)
  • v22.3.1(Apr 17, 2022)

    What's Changed

    • Add fall back for Windows even loop fetching by @ahopkins in https://github.com/sanic-org/sanic/pull/2421

    Full Changelog: https://github.com/sanic-org/sanic/compare/v22.3.0...v22.3.1

    Source code(tar.gz)
    Source code(zip)
  • v22.3.0(Mar 31, 2022)

    Version 22.3.0

    Features

    • #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.
      • 🧁 SIDE EFFECT: Named background tasks are now supported, even in Python 3.7
    • #2357 Parse Authorization header as Request.credentials
    • #2361 Add config option to skip Touchup step in application startup
    • #2372 Updates to CLI help messaging
    • #2382 Downgrade warnings to backwater debug messages
    • #2396 Allow for multidict v0.6
    • #2401 Upgrade CLI catching for alternative application run types
    • #2402 Conditionally inject CLI arguments into factory
    • #2413 Add new start and stop event listeners to reloader process
    • #2414 Remove loop as required listener arg
    • #2415 Better exception for bad URL parsing
    • sanic-routing#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 Change register_pattern to accept a str or Pattern
    • sanic-routing#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 Remove error_logger on websockets
    • #2381 Fix newly assigned None in task registry
    • sanic-routing#52 Add type casting to regex route matching
    • sanic-routing#60 Add requirements check on regex routes (this resolves, for example, multiple static directories with differing host values)

    Deprecations and Removals

    • #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 Deprecate loading of lowercase environment variables

    Developer infrastructure

    Improved Documentation

    • #2350 Fix link in README for ASGI
    • #2398 Document middleware on_request and on_response
    • #2409 Add missing documentation for Request.respond

    Miscellaneous

    • #2376 Fix typing for ListenerMixin.listener
    • #2383 Clear deprecation warning in asyncio.wait
    • #2387 Cleanup __slots__ implementations
    • #2390 Clear deprecation warning in asyncio.get_event_loop
    Source code(tar.gz)
    Source code(zip)
  • v20.12.6(Feb 16, 2022)

    What's Changed

    • Potential server crash if running Python 3.10 w/ Sanic 20.12 by @ahopkins in https://github.com/sanic-org/sanic/pull/2400

    Full Changelog: https://github.com/sanic-org/sanic/compare/v20.12.5...v20.12.6

    Source code(tar.gz)
    Source code(zip)
  • v20.12.5(Jan 16, 2022)

  • v21.12.1(Jan 6, 2022)

  • v21.12.0(Dec 26, 2021)

    Features

    • #2260 Allow early Blueprint registrations to still apply later added objects
    • #2262 Noisy exceptions - force logging of all exceptions
    • #2264 Optional uvloop by configuration
    • #2270 Vhost support using multiple TLS certificates
    • #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 Add contextual exceptions
    • #2291 Increase join concat performance
    • #2295, #2316, #2331 Restructure of CLI and application state with new displays and more command parity with app.run
    • #2302 Add route context at definition time
    • #2304 Named tasks and new API for managing background tasks
    • #2307 On app auto-reload, provide insight of changed files
    • #2308 Auto extend application with Sanic Extensions if it is installed, and provide first class support for accessing the extensions
    • #2309 Builtin signals changed to Enum
    • #2313 Support additional config implementation use case
    • #2321 Refactor environment variable hydration logic
    • #2327 Prevent sending multiple or mixed responses on a single request
    • #2330 Custom type casting on environment variables
    • #2332 Make all deprecation notices consistent
    • #2335 Allow underscore to start instance names

    Bugfixes

    • #2273 Replace assignation by typing for websocket_handshake
    • #2285 Fix IPv6 display in startup logs
    • #2299 Dispatch http.lifecyle.response from exception handler

    Deprecations and Removals

    • #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 Remove app instance from Config for error handler setting

    Developer infrastructure

    • #2251 Change dev install command
    • #2286 Change codeclimate complexity threshold from 5 to 10
    • #2287 Update host test function names so they are not overwritten
    • #2292 Fail CI on error
    • #2311, #2324 Do not run tests for draft PRs
    • #2336 Remove paths from coverage checks
    • #2338 Cleanup ports on tests

    Improved Documentation

    Miscellaneous

    Source code(tar.gz)
    Source code(zip)
  • v21.9.3(Nov 21, 2021)

  • v21.9.2(Nov 21, 2021)

    • #2268 Make HTTP connections start in IDLE stage, avoiding delays and error messages
    • #2310 More consistent config setting with post-FALLBACK_ERROR_FORMAT apply
    Source code(tar.gz)
    Source code(zip)
  • v21.9.1(Oct 2, 2021)

  • v20.12.4(Oct 2, 2021)

  • v21.9.0(Sep 30, 2021)

    Version 21.9

    Release Notes

    Features

    • #2158, #2248 Complete overhaul of I/O to websockets
    • #2160 Add new 17 signals into server and request lifecycles
    • #2162 Smarter auto fallback formatting upon exception
    • #2184 Introduce implementation for copying a Blueprint
    • #2200 Accept header parsing
    • #2207 Log remote address if available
    • #2209 Add convenience methods to BP groups
    • #2216 Add default messages to SanicExceptions
    • #2225 Type annotation convenience for annotated handlers with path parameters
    • #2236 Allow Falsey (but not-None) responses from route handlers
    • #2238 Add exception decorator to Blueprint Groups
    • #2244 Explicit static directive for serving file or dir (ex: static(..., resource_type="file"))
    • #2245 Close HTTP loop when connection task cancelled

    Bugfixes

    • #2188 Fix the handling of the end of a chunked request
    • #2195 Resolve unexpected error handling on static requests
    • #2208 Make blueprint-based exceptions attach and trigger in a more intuitive manner
    • #2211 Fixed for handling exceptions of asgi app call
    • #2213 Fix bug where ws exceptions not being logged
    • #2231 Cleaner closing of tasks by using abort() in strategic places to avoid dangling sockets
    • #2247 Fix logging of auto-reload status in debug mode
    • #2246 Account for BP with exception handler but no routes

    Developer infrastructure

    • #2194 HTTP unit tests with raw client
    • #2199 Switch to codeclimate
    • #2214 Try Reopening Windows Tests
    • #2229 Refactor HttpProtocol into a base class
    • #2230 Refactor server.py into multi-file module

    Miscellaneous

    • #2173 Remove Duplicated Dependencies and PEP 517 Support
    • #2193, #2196, #2217 Type annotation changes
    Source code(tar.gz)
    Source code(zip)
  • v21.6.2(Aug 2, 2021)

  • v21.6.1(Jul 28, 2021)

    Bugfixes

    • #2178 Update sanic-routing to allow for better splitting of complex URI templates
    • #2183 Proper handling of chunked request bodies to resolve phantom 503 in logs
    • #2181 Resolve regression in exception logging
    • #2201 Cleanup request info in pipelined requests
    Source code(tar.gz)
    Source code(zip)
  • v21.6.0(Jun 27, 2021)

    Features

    • #2094 Add response.eof() method for closing a stream in a handler
    • #2097 Allow case-insensitive HTTP Upgrade header
    • #2104 Explicit usage of CIMultiDict getters
    • #2109 Consistent use of error loggers
    • #2114 New client_ip access of connection info instance
    • #2119 Alternatate classes on instantiation for Config and Sanic.ctx
    • #2133 Implement new version of AST router
      • Proper differentiation between alpha and string param types
      • Adds a slug param type, example: <foo:slug>
      • Deprecates <foo:string> in favor of <foo:str>
      • Deprecates <foo:number> in favor of <foo:float>
      • Adds a route.uri accessor
    • #2136 CLI improvements with new optional params
    • #2137 Add version_prefix to URL builders
    • #2140 Event autoregistration with EVENT_AUTOREGISTER
    • #2146, #2147 Require stricter names on Sanic() and Blueprint()
    • #2150 Infinitely reusable and nestable Blueprint and BlueprintGroup
    • #2154 Upgrade websockets dependency to min version
    • #2155 Allow for maximum header sizes to be increased: REQUEST_MAX_HEADER_SIZE
    • #2157 Allow app factory pattern in CLI
    • #2165 Change HTTP methods to enums
    • #2167 Allow auto-reloading on additional directories
    • #2168 Add simple HTTP server to CLI
    • #2170 Additional methods for attaching HTTPMethodView

    Bugfixes

    • #2091 Fix UserWarning in ASGI mode for missing __slots__
    • #2099 Fix static request handler logging exception on 404
    • #2110 Fix request.args.pop removes parameters inconsistently
    • #2107 Fix type hinting for load_env
    • #2127 Make sure ASGI ws subprotocols is a list
    • #2128 Fix issue where Blueprint exception handlers do not consistently route to proper handler

    Deprecations and Removals

    • #2156 Remove config value REQUEST_BUFFER_QUEUE_SIZE
    • #2170 CompositionView deprecated and marked for removal in 21.12
    • #2172 Deprecate StreamingHTTPResponse

    Developer infrastructure

    • #2149 Remove Travis CI in favor of GitHub Actions

    Improved Documentation

    • #2164 Fix typo in documentation
    • #2100 Remove documentation for non-existent arguments
    Source code(tar.gz)
    Source code(zip)
  • v21.3.4(Apr 19, 2021)

    Bugfixes

    #2117 Add sanic-routing==0.6 with RouteGroup and resolve:

    • #2116 Access logs not properly displaying body size
    • #2103 Request body not automatically loading
    • #2101 ASGI routes not extracting body
    • #2090 Edge case on router with overloading
    Source code(tar.gz)
    Source code(zip)
  • v21.3.3(Apr 19, 2021)

  • v21.3.2(Mar 23, 2021)

    Bugfixes

    • #2081 Disable response timeout on websocket connections
    • #2085 Make sure that blueprints with no slash is maintained when applied
    Source code(tar.gz)
    Source code(zip)
  • v21.3.1(Mar 21, 2021)

  • v21.3.0(Mar 21, 2021)

    Release Notes

    Features

    • #1876 Unified streaming server
    • #2005 New Request.id property
    • #2008 Allow Pathlib Path objects to be passed to app.static() helper
    • #2010 #2031 New startup-optimized router
    • #2018 #2064 Listeners for main server process
    • #2032 Add raw header info to request object
    • #2042 #2060 #2061 Introduce Signals API
    • #2043 Add __str__ and __repr__ to Sanic and Blueprint
    • #2047 Enable versioning and strict slash on BlueprintGroup
    • #2053 Make get_app name argument optional
    • #2055 JSON encoder change via app
    • #2063 App and connection level context objects

    Bugfixes and issues resolved

    • Resolve #1420 url_for where strict_slashes are on for a path ending in /
    • Resolve #1525 Routing is incorrect with some special characters
    • Resolve #1653 ASGI headers in body
    • Resolve #1722 Using curl in chunk mode
    • Resolve #1730 Extra content in ASGI streaming response
    • Resolve #1749 Restore broken middleware edge cases
    • Resolve #1785 #1804 Synchronous error handlers
    • Resolve #1790 Protocol errors did not support async error handlers #1790
    • Resolve #1824 Timeout on specific methods
    • Resolve #1875 Response timeout error from all routes after returning several timeouts from a specific route
    • Resolve #1988 Handling of safe methods with body
    • #2001 Raise ValueError when cookie max-age is not an integer

    Deprecations and Removals

    • #2007
      • Config using from_envvar
      • Config using from_pyfile
      • Config using from_object
    • #2009 Remove Sanic test client to its own package
    • #2036 #2037 Drop Python 3.6 support
    • Request.endpoint deprecated in favor of Request.name
    • handler type name prefixes removed (static, websocket, etc)

    Developer infrastructure

    • #1995 Create FUNDING.yml
    • #2013 Add codeql to CI pipeline
    • #2038 Codecov configuration updates
    • #2049 Updated setup.py to use find_packages

    Improved Documentation

    • #1218 Documentation for sanic.log.* is missing
    • #1608 Add documentation on calver and LTS
    • #1731 Support mounting application elsewhere than at root path
    • #2006 Upgraded type annotations and improved docstrings and API documentation
    • #2052 Fix some examples and docs

    Miscellaneous

    • Request.route property
    • Better websocket subprotocols support
    • Resolve bug with middleware in Blueprint Group when passed callable
    • Moves common logic between Blueprint and Sanic into mixins
    • Route naming changed to be more consistent
      • request endpoint is the route name
      • route names are fully namespaced
    • Some new convenience decorators:
      • @app.main_process_start
      • @app.main_process_stop
      • @app.before_server_start
      • @app.after_server_start
      • @app.before_server_stop
      • @app.after_server_stop
      • @app.on_request
      • @app.on_response
    • Fixes Allow header that did not include HEAD
    • Using "name" keyword in url_for for a "static" route where name does not exist
    • Cannot have multiple app.static() without using the named param
    • Using "filename" keyword in url_for on a file route
    • unquote in route def (not automatic)
    • routes_all is tuples
    • Handler arguments are kwarg only
    • request.match_info is now a cached (and not computed) property
    • Unknown static file mimetype is sent as application/octet-stream
    • _host keyword in url_for
    • Add charset default to utf-8 for text and js content types if not specified
    • Version for a route can be str, float, or int
    • Route has ctx property
    • App has routes_static, routes_dynamic, routes_regex
    • #2044 Code cleanup and refactoring
    • #2072 Remove BaseSanic metaclass
    • #2074 Performance adjustments in handle_request_
    Source code(tar.gz)
    Source code(zip)
  • v20.12.3(Mar 21, 2021)

  • v20.12.2(Feb 16, 2021)

    Dependencies

    • #2026 Fix uvloop to 0.14 because 0.15 drops Python 3.6 support
    • #2029 Remove old chardet requirement, add in hard multidict requirement
    Source code(tar.gz)
    Source code(zip)
Owner
Sanic Community Organization
Build fast. Run fast.
Sanic Community Organization
a web-remote minecraft server wrapper with some unique features

Canceled here, continued as Semoxy MCWeb - a Minecraft Server Web Interface MCWeb is a web-remote Minecraft Server Wrapper for controlling your Minecr

Anton Vogelsang 1 Jul 12, 2021
Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.

?? Fast, Async-ready, Openapi, type hints based framework for building APIs

Vitaliy Kucheryaviy 3.8k Jan 4, 2023
Build a Backend REST API with Python & Django

Build a Backend REST API with Python & Django Skills Python Django djangorestframework Aws Git Use the below Git commands in the Windows Command Promp

JeonSoohyun a.k.a Edoc.. 1 Jan 25, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.3k Jan 4, 2023
Document Web APIs made with Django Rest Framework

DRF Docs Document Web APIs made with Django Rest Framework. View Demo Contributors Wanted: Do you like this project? Using it? Let's make it better! S

Manos Konstantinidis 626 Nov 20, 2022
FastAPI framework, high performance, easy to learn, fast to code, ready for production

FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https:

Sebastián Ramírez 53.1k Jan 6, 2023
Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.8k Jan 5, 2023
Browsable web APIs for Flask.

Flask API Browsable web APIs for Flask. Status: This project is in maintenance mode. The original author (Tom Christie) has shifted his focus to API S

Flask API 1.3k Dec 27, 2022
The Web API toolkit. 🛠

?? The Web API toolkit. ?? Community: https://discuss.apistar.org ?? ?? ?? ?? ?? Documentation: https://docs.apistar.com ?? Requirements: Python 3.6+

Encode 5.6k Dec 27, 2022
Web APIs for Django. 🎸

Django REST framework Awesome web-browsable Web APIs. Full documentation for the project is available at https://www.django-rest-framework.org/. Fundi

Encode 24.7k Jan 4, 2023
BreakFastApi 🍣 🍔 🍕 The most delicious API on the web

BreakFastApi ?? ?? ?? The most delicious API on the web. Just send a request and you'll receive the most mouth watering dish recipe with estimated coo

Mariia Sizova 156 Nov 19, 2022
The no-nonsense, minimalist REST and app backend framework for Python developers, with a focus on reliability, correctness, and performance at scale.

The Falcon Web Framework Falcon is a reliable, high-performance Python web framework for building large-scale app backends and microservices. It encou

Falconry 9k Jan 3, 2023
A simple API example in Python (Flask framework)

API-Example A simple API in Python(Flask) ✨ Features An API i guess? ??‍♀️ How to use first download the main.py install python then install flask fra

Portgas D Ace 2 Jan 6, 2022
REST API framework designed for human beings

Eve Eve is an open source Python REST API framework designed for human beings. It allows to effortlessly build and deploy highly customizable, fully f

eve 6.6k Jan 4, 2023
Restful API framework wrapped around MongoEngine

Flask-MongoRest A Restful API framework wrapped around MongoEngine. Setup from flask import Flask from flask_mongoengine import MongoEngine from flask

Close 525 Jan 1, 2023
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Dec 28, 2022
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Jan 6, 2023
Introduction to Django Rest Framework

Introduction to Django Rest Framework This is the repository of the video series Introduction to Django Rest Framework published on YouTube. It is a s

Simple is Better Than Complex 20 Jul 14, 2022