Convert Figma logo to code with AI

sanic-org logosanic

Accelerate your web app development | Build fast. Run fast.

18,046
1,546
18,046
127

Top Related Projects

67,844

The Python micro framework for building web applications.

79,643

The Web framework for perfectionists with deadlines.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

21,707

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

10,027

The little ASGI framework that shines. 🌟

15,061

Asynchronous HTTP client/server framework for asyncio and Python

Quick Overview

Sanic is a Python 3.7+ web server and web framework that's designed for fast HTTP responses via asynchronous request handling. It allows the usage of the async/await syntax added in Python 3.5, making it compatible with asyncio libraries. Sanic is built to be easy to use, production-ready, and scalable.

Pros

  • Fast performance due to its asynchronous nature
  • Built-in support for WebSockets
  • Easy to use and intuitive API
  • Extensible with a growing ecosystem of plugins

Cons

  • Requires Python 3.7+, which may not be suitable for older projects
  • Less mature compared to some other web frameworks like Flask or Django
  • Smaller community and ecosystem compared to more established frameworks
  • Learning curve for developers not familiar with asynchronous programming

Code Examples

  1. Basic Sanic application:
from sanic import Sanic
from sanic.response import json

app = Sanic("MyApp")

@app.route("/")
async def test(request):
    return json({"hello": "world"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)
  1. Using WebSockets:
from sanic import Sanic
from sanic.response import json

app = Sanic("WebSocketExample")

@app.websocket('/feed')
async def feed(request, ws):
    while True:
        data = 'hello!'
        await ws.send(data)
        await asyncio.sleep(1)
  1. Middleware example:
from sanic import Sanic
from sanic.response import json

app = Sanic("MiddlewareExample")

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

@app.route('/')
async def test(request):
    return json({"hello": "world"})

Getting Started

To get started with Sanic, follow these steps:

  1. Install Sanic:

    pip install sanic
    
  2. Create a new file app.py with the following content:

    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic("MyApp")
    
    @app.route("/")
    async def hello_world(request):
        return text("Hello, World!")
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=8000)
    
  3. Run the application:

    python app.py
    
  4. Open a web browser and navigate to http://localhost:8000 to see your Sanic application in action.

Competitor Comparisons

67,844

The Python micro framework for building web applications.

Pros of Flask

  • Extensive documentation and large community support
  • Wide range of extensions available for additional functionality
  • Simpler and more intuitive for beginners

Cons of Flask

  • Slower performance compared to Sanic, especially for high-concurrency scenarios
  • Lacks built-in async support (though can be added with extensions)

Code Comparison

Flask:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

Sanic:

from sanic import Sanic
from sanic.response import text

app = Sanic("MyApp")

@app.route('/')
async def hello(request):
    return text('Hello, World!')

The main differences in the code examples are:

  1. Sanic uses async/await syntax for request handlers
  2. Sanic's route handlers receive a request object as an argument
  3. Sanic uses specific response types (e.g., text()) instead of returning strings directly

Both frameworks offer similar ease of use for basic routing and request handling, but Sanic's async nature becomes more apparent in more complex scenarios, potentially offering better performance for I/O-bound operations.

79,643

The Web framework for perfectionists with deadlines.

Pros of Django

  • Comprehensive ecosystem with built-in admin interface, ORM, and authentication
  • Extensive documentation and large community support
  • Batteries-included approach, providing many features out-of-the-box

Cons of Django

  • Slower performance compared to Sanic, especially for high-concurrency scenarios
  • More opinionated and less flexible for certain use cases
  • Steeper learning curve for beginners due to its large feature set

Code Comparison

Django:

from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello, World!")

Sanic:

from sanic import Sanic
from sanic.response import text

app = Sanic("MyApp")

@app.route("/")
async def hello_world(request):
    return text("Hello, World!")

The code comparison shows that Sanic uses async/await syntax, which can lead to better performance in I/O-bound operations. Django's syntax is more straightforward but lacks built-in asynchronous support. Sanic's routing is similar to other micro-frameworks, while Django follows a more traditional URL configuration approach.

Both frameworks have their strengths, with Django excelling in rapid development of complex applications and Sanic focusing on high-performance, asynchronous web services.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • Built-in support for data validation and serialization using Pydantic models
  • Automatic API documentation with Swagger UI and ReDoc
  • Native async support with modern Python features (async/await)

Cons of FastAPI

  • Slightly steeper learning curve due to dependency on Pydantic
  • Can be slower for simple use cases compared to Sanic's raw performance

Code Comparison

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Sanic:

from sanic import Sanic
from sanic.response import json

app = Sanic("MyApp")

@app.route("/")
async def test(request):
    return json({"message": "Hello World"})

Both frameworks offer similar syntax for defining routes and handling requests. FastAPI leverages type hints and Pydantic models for request/response validation, while Sanic focuses on simplicity and raw performance.

FastAPI excels in automatic documentation generation and data validation, making it ideal for complex APIs. Sanic, on the other hand, is known for its speed and simplicity, making it a good choice for high-performance microservices or when raw speed is a priority.

21,707

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Pros of Tornado

  • More mature and battle-tested, with a longer history of production use
  • Supports both synchronous and asynchronous programming models
  • Includes built-in support for WebSockets and long polling

Cons of Tornado

  • Generally slower performance compared to Sanic
  • Less active development and community support
  • More complex API and steeper learning curve for beginners

Code Comparison

Sanic:

from sanic import Sanic
from sanic.response import json

app = Sanic("MyApp")

@app.route("/")
async def test(request):
    return json({"hello": "world"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Tornado:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write({"hello": "world"})

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8000)
    tornado.ioloop.IOLoop.current().start()

Both frameworks offer asynchronous web server capabilities, but Sanic's syntax is more concise and modern. Tornado requires more boilerplate code and uses a class-based approach for request handling.

10,027

The little ASGI framework that shines. 🌟

Pros of Starlette

  • More lightweight and flexible, allowing developers to choose their preferred components
  • Better support for WebSocket and GraphQL applications
  • Excellent integration with ASGI servers like Uvicorn for high-performance deployments

Cons of Starlette

  • Less opinionated, requiring more setup and configuration for full-featured applications
  • Smaller community and ecosystem compared to Sanic
  • Fewer built-in features, potentially leading to more third-party dependencies

Code Comparison

Sanic:

from sanic import Sanic
from sanic.response import json

app = Sanic("MyApp")

@app.route("/")
async def hello_world(request):
    return json({"hello": "world"})

Starlette:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def hello_world(request):
    return JSONResponse({"hello": "world"})

app = Starlette(routes=[
    Route("/", hello_world)
])

Both frameworks offer similar functionality for creating asynchronous web applications, but Starlette's approach is more modular and explicit in its routing configuration. Sanic provides a more familiar Flask-like syntax with decorators for route definitions.

15,061

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • More mature and stable project with a larger ecosystem
  • Supports both client and server-side HTTP operations
  • Flexible and feature-rich, suitable for complex applications

Cons of aiohttp

  • Generally slower performance compared to Sanic
  • More verbose syntax and configuration required
  • Steeper learning curve for beginners

Code Comparison

aiohttp example:

from aiohttp import web

async def hello(request):
    return web.Response(text="Hello, World!")

app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)

Sanic example:

from sanic import Sanic
from sanic.response import text

app = Sanic("MyApp")

@app.route("/")
async def hello(request):
    return text("Hello, World!")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Both aiohttp and Sanic are popular asynchronous web frameworks for Python. aiohttp offers a more comprehensive set of features and a larger ecosystem, making it suitable for complex applications. However, Sanic provides better performance and a simpler API, making it easier for beginners to get started. The choice between the two depends on the specific requirements of your project and your familiarity with asynchronous programming in Python.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://raw.githubusercontent.com/sanic-org/sanic-assets/master/png/sanic-framework-logo-400x97.png :alt: Sanic | Build fast. Run fast.

Sanic | Build fast. Run fast.

.. start-badges

.. list-table:: :widths: 15 85 :stub-columns: 1

* - Build
  - | |Tests|
* - Docs
  - | |UserGuide| |Documentation|
* - Package
  - | |PyPI| |PyPI version| |Wheel| |Supported implementations| |Code style ruff|
* - Support
  - | |Forums| |Discord| |Awesome|
* - Stats
  - | |Monthly Downloads| |Weekly Downloads| |Conda downloads|

.. |UserGuide| image:: https://img.shields.io/badge/user%20guide-sanic-ff0068 :target: https://sanic.dev/ .. |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&label=Discord&color=5865F2 :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 ruff| image:: https://img.shields.io/badge/code%20style-ruff-000000.svg :target: https://docs.astral.sh/ruff/ .. |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

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

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.

Hello World Example

.. code:: python

from sanic import Sanic
from sanic.response import json

app = Sanic("my-hello-world-app")

@app.route('/')
async def test(request):
    return json({'hello': 'world'})

if __name__ == '__main__':
    app.run()

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

.. code::

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

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

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

User Guide, Changelog, and API Documentation can be found at sanic.dev <https://sanic.dev>__.

Questions and Discussion

Ask a question or join the conversation <https://community.sanicframework.org/>__.

Contribution

We are always happy to have new contributions. We have marked issues good for anyone looking to get started <https://github.com/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>_.