### Install Sanic Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/getting-started.md Installs the Sanic asynchronous web framework using pip. ```sh pip install sanic ``` -------------------------------- ### Install Sanic with Extensions (Extras) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/getting-started.md Installs Sanic along with the official Sanic Extensions plugin using the extras syntax. ```sh pip install sanic[ext] ``` -------------------------------- ### Install Sanic and Extensions Separately Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/getting-started.md Installs the Sanic framework and the official Sanic Extensions plugin as separate packages. ```sh pip install sanic sanic-ext ``` -------------------------------- ### Install Sanic with Extensions (Recommended) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/getting-started.md Installs Sanic along with the Sanic Extensions plugin using the recommended extra dependency syntax. ```bash pip install sanic[ext] ``` -------------------------------- ### Installing Sanic with Extensions (Extra) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/getting-started.md Installs the Sanic framework along with the official Sanic Extensions package using Python's extra installation syntax. This is a convenient way to get both packages. ```Bash pip install sanic[ext] ``` -------------------------------- ### Install Sanic Extensions Separately Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/getting-started.md Installs only the Sanic Extensions plugin without installing Sanic itself. Useful if Sanic is already installed. ```bash pip install sanic-ext ``` -------------------------------- ### Basic Sanic App with Implicit Extensions Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/getting-started.md A standard Sanic 'Hello, world' application. When Sanic Extensions is installed in the environment, it is automatically enabled without requiring explicit setup code (v21.12+). ```python from sanic import Sanic from sanic.response import text app = Sanic("MyHelloWorldApp") @app.get("/") async def hello_world(request): return text("Hello, world.") ``` -------------------------------- ### Installing Sanic and Extensions Separately Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/getting-started.md Installs the Sanic framework and the official Sanic Extensions package as two distinct packages using pip. This achieves the same result as the extra syntax but lists them explicitly. ```Bash pip install sanic sanic-ext ``` -------------------------------- ### Installing Sanic via pip Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/getting-started.md Installs the Sanic asynchronous web framework using the pip package manager. This is the standard way to add Sanic to your Python environment. ```Bash pip install sanic ``` -------------------------------- ### Install Sanic Testing Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/getting-started.md Install the Sanic Testing package from PyPI using pip. This command adds the necessary library to your Python environment. ```shell pip install sanic-testing ``` -------------------------------- ### Create Sanic Hello World App Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/getting-started.md Defines a basic Sanic application with a single route ('/') that returns 'Hello, world.' using an asynchronous request handler. ```python from sanic import Sanic from sanic.response import text app = Sanic("MyHelloWorldApp") @app.get("/") async def hello_world(request): return text("Hello, world.") ``` -------------------------------- ### Run Sanic Application Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/getting-started.md Launches the Sanic application defined in 'server.py' using the built-in production-ready server. ```sh sanic server ``` -------------------------------- ### Creating a Sanic Hello World App Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/getting-started.md Defines a basic Sanic application. It imports necessary components, creates a Sanic instance, and defines an asynchronous route handler for the root path ('/') that returns 'Hello, world.' as plain text. ```Python from sanic import Sanic from sanic.response import text app = Sanic("MyHelloWorldApp") @app.get("/") async def hello_world(request): return text("Hello, world.") ``` -------------------------------- ### Running a Sanic Application Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/getting-started.md Executes the Sanic application defined in a Python file (assumed to be 'server.py' with an app instance named 'app'). This command starts the Sanic server. ```Bash sanic server.app ``` -------------------------------- ### Write a Sync Test with Sanic Test Client Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/getting-started.md This example demonstrates writing a synchronous test for a Sanic application using pytest. It defines a Sanic app fixture and a test function that uses `app.test_client.get()` to make a request and assert the response. ```python import pytest from sanic import Sanic, response @pytest.fixture def app(): sanic_app = Sanic("TestSanic") @sanic_app.get("/") def basic(request): return response.text("foo") return sanic_app def test_basic_test_client(app): request, response = app.test_client.get("/") assert request.method.lower() == "get" assert response.body == b"foo" assert response.status == 200 ``` -------------------------------- ### Install pytest-asyncio for Async Tests Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/getting-started.md To write asynchronous tests with pytest and Sanic's ASGI client, install the pytest-asyncio plugin. This allows pytest to run async test functions. ```shell pip install pytest-asyncio ``` -------------------------------- ### Using Default SanicTestClient Get Request (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/clients.md Shows the simplest way to make a GET request using the default SanicTestClient instance provided by the Sanic application object after installing sanic-testing. This requires no explicit client instantiation and spins up a server for the request. ```python app.test_client.get("/path/to/endpoint") ``` -------------------------------- ### Write an Async Test with Sanic ASGI Client Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/getting-started.md This example shows how to write an asynchronous test for a Sanic application using pytest with the pytest-asyncio plugin. It uses the `app.asgi_client.get()` method, which is awaitable, to make a request and assert the response. ```python import pytest from sanic import Sanic, response @pytest.fixture def app(): sanic_app = Sanic(__name__) @sanic_app.get("/") def basic(request): return response.text("foo") return sanic_app @pytest.mark.asyncio async def test_basic_asgi_client(app): request, response = await app.asgi_client.get("/") assert request.method.lower() == "get" assert response.body == b"foo" assert response.status == 200 ``` -------------------------------- ### Basic Sanic App with Explicit Extensions (Deprecated) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/getting-started.md Shows the older, deprecated method (v21.9) of explicitly initializing Sanic Extensions by instantiating the `Extend` class and passing the Sanic app instance. ```python from sanic import Sanic from sanic.response import text from sanic_ext import Extend app = Sanic("MyHelloWorldApp") Extend(app) @app.get("/") async def hello_world(request): return text("Hello, world.") ``` -------------------------------- ### Instantiating SanicTestClient and Making Get Request (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/clients.md Demonstrates how to explicitly import and instantiate the SanicTestClient by passing the Sanic application instance. It then shows how to use the instantiated client to make a GET request to a specific endpoint, which still involves spinning up a server per request. ```python from sanic_testing.testing import SanicTestClient test_client = SanicTestClient(app) test_client.get("/path/to/endpoint") ``` -------------------------------- ### Start Sanic HTTP/3 Server via CLI Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v22.6.md Starts the Sanic server using the HTTP/3 protocol via the command line interface. Requires aioquic to be installed and a TLS certificate to be configured. ```shell $ sanic path.to.server:app --http=3 ``` ```shell $ sanic path.to.server:app -3 ``` -------------------------------- ### Defining a Basic Sanic App (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Provides a minimal example of a Sanic application in Python. It shows how to import necessary components, create a Sanic instance, and define a simple GET route that returns JSON. ```python # ./path/to/server.py from sanic import Sanic, Request, json app = Sanic("TestApp") @app.get("/") async def handler(request: Request): return json({"foo": "bar"}) ``` -------------------------------- ### Creating and Running a Basic Sanic App Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/README.md This snippet demonstrates how to create a minimal Sanic application with a single route and the shell command to run it. It shows the basic structure of a Sanic app and the output when the server starts. ```python from sanic import Sanic from sanic.response import text app = Sanic("MyHelloWorldApp") @app.get("/") async def hello_world(request): return text("Hello, world.") ``` ```sh sanic path.to.server:app [2023-01-31 12:34:56 +0000] [999996] [INFO] Sanic v22.12.0 [2023-01-31 12:34:56 +0000] [999996] [INFO] Goin' Fast @ http://127.0.0.1:8000 [2023-01-31 12:34:56 +0000] [999996] [INFO] mode: production, single worker [2023-01-31 12:34:56 +0000] [999996] [INFO] server: sanic, HTTP/1.1 [2023-01-31 12:34:56 +0000] [999996] [INFO] python: 3.10.9 [2023-01-31 12:34:56 +0000] [999996] [INFO] platform: SomeOS-9.8.7 [2023-01-31 12:34:56 +0000] [999996] [INFO] packages: sanic-routing==22.8.0, sanic-testing==22.12.0, sanic-ext==22.12.0 [2023-01-31 12:34:56 +0000] [999997] [INFO] Sanic Extensions: [2023-01-31 12:34:56 +0000] [999997] [INFO] > injection [12 dependencies; 7 constants] [2023-01-31 12:34:56 +0000] [999997] [INFO] > openapi [http://127.0.0.1:8000/docs] [2023-01-31 12:34:56 +0000] [999997] [INFO] > http [2023-01-31 12:34:56 +0000] [999997] [INFO] > templating [jinja2==3.1.2] [2023-01-31 12:34:56 +0000] [999997] [INFO] Starting worker [999997] ``` -------------------------------- ### Start Services with Docker Compose Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/docker.md Shell command to start the services defined in the docker-compose.yml file in detached mode (-d). This will build/pull images if necessary and start the 'mysanic' and 'mynginx' containers. ```shell docker-compose up -d ``` -------------------------------- ### Running Sanic App via CLI (Bash) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ja/guide/deployment/running.md Demonstrates how to start a Sanic application using the `sanic` command-line tool, specifying the application module, host, port, and number of workers. Requires the Sanic CLI to be installed and the application defined in `server.py` as `server.app`. ```bash sanic server.app --host=0.0.0.0 --port=1337 --workers=4 ``` -------------------------------- ### Start Sanic HTTP/3 Server via Python API Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v22.6.md Starts the Sanic server using the HTTP/3 protocol programmatically. Requires aioquic to be installed and a TLS certificate to be configured. ```python app.run(version=3) ``` -------------------------------- ### Creating a Basic Sanic App (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/development.md This snippet shows how to create a minimal Sanic application. It imports the necessary classes, initializes the Sanic app, and defines a route that returns a JSON response. This is a standard starting point for building Sanic web services. ```python from sanic import Sanic from sanic.response import json app = Sanic(__name__) @app.route("/") async def hello_world(request): return json({"hello": "world"}) ``` -------------------------------- ### Send Example Requests (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/orm.md Provides example `curl` commands to test the Sanic application endpoints. The first command sends a POST request to create a user, and the second sends a GET request to retrieve the created user by their ID. Expected JSON responses are shown below each command in the original text. ```sh curl --location --request POST 'http://127.0.0.1:8000/user' ``` ```sh curl --location --request GET 'http://127.0.0.1:8000/user/1' ``` -------------------------------- ### Example Sanic Worker State Output JSON Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/manager.md This JSON object shows an example structure of the output from `request.app.m.workers`, detailing the state, PID, start time, and other information for the main process, server workers, and reloader. ```json { 'Sanic-Main': {'pid': 99997}, 'Sanic-Server-0-0': { 'server': True, 'state': 'ACKED', 'pid': 9999, 'start_at': datetime.datetime(2022, 10, 1, 0, 0, 0, 0, tzinfo=datetime.timezone.utc), 'starts': 2, 'restart_at': datetime.datetime(2022, 10, 1, 0, 0, 12, 861332, tzinfo=datetime.timezone.utc) }, 'Sanic-Reloader-0': { 'server': False, 'state': 'STARTED', 'pid': 99998, 'start_at': datetime.datetime(2022, 10, 1, 0, 0, 0, 0, tzinfo=datetime.timezone.utc), 'starts': 1 } } ``` -------------------------------- ### Basic Sanic Application (server.py) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/docker.md A minimal Sanic application that listens on 0.0.0.0:8000 and responds with 'OK!' to GET requests on the root path. Note that the host is set to 0.0.0.0 for accessibility within a Docker container. ```python app = Sanic("MySanicApp") @app.get('/') async def hello(request): return text("OK!") if __name__ == '__main__': app.run(host='0.0.0.0', port=8000) ``` -------------------------------- ### Usage Example: Sanic Decorator (With Args) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/best-practices/decorators.md Shows how to apply a Sanic decorator that supports optional arguments, illustrating the syntax @foobar(arg1=1, arg2=2). ```python @app.get("/") @foobar(arg1=1, arg2=2) async def handler(request: Request): return text("hi") ``` -------------------------------- ### Running Sanic App (Python - prepare/serve) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Start the Sanic server by explicitly calling `app.prepare()` to configure listeners and then `Sanic.serve()` to start the server process. This is equivalent to `app.run()`. ```Python if __name__ == "__main__": app.prepare(host='0.0.0.0', port=1337, access_log=False) Sanic.serve() ``` -------------------------------- ### Starting Sanic Simple Static Server (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Use the Sanic command-line interface with the `--simple` flag to quickly serve static files from a specified directory. ```Shell sanic ./path/to/dir --simple ``` -------------------------------- ### Dockerfile for Sanic Application Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/docker.md Defines the steps to build a Docker image for the Sanic application. It uses a Sanic base image, sets the working directory, copies application files, installs dependencies from requirements.txt, exposes port 8000, and specifies the command to run the server. ```dockerfile FROM sanicframework/sanic:3.8-latest WORKDIR /sanic COPY . . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "server.py"] ``` -------------------------------- ### Starting Docker Compose and Sanic Server Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ja/guide/how-to/mounting.md These Bash commands show how to start the services defined in the Docker Compose file in detached mode (`-d`) and how to run the Sanic application server, specifying the application module, port, and host. ```bash $ docker-compose up -d $ sanic server.app --port=9999 --host=0.0.0.0 ``` -------------------------------- ### Example Jinja HTML Template Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/templating.md An example HTML file (`foo.html`) demonstrating basic HTML structure and a Jinja `for` loop to iterate over a sequence. ```html My Webpage

Hello, world!!!!

``` -------------------------------- ### Usage Example: Sanic Decorator (Without Args) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/best-practices/decorators.md Shows how to apply a Sanic decorator that supports optional arguments, illustrating the syntax @foobar when no arguments are provided. ```python @app.get("/") @foobar async def handler(request: Request): return text("hi") ``` -------------------------------- ### Using Default SanicASGITestClient Async Get Request (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/clients.md Demonstrates making an asynchronous GET request using the default SanicASGITestClient instance available on the Sanic application object. This client runs the application as an ASGI app, does not spin up a separate server per request, and requires 'await' before the method call. ```python await app.asgi_client.get("/path/to/endpoint") ``` -------------------------------- ### Sanic Application Setup with Autodiscovery Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/autodiscovery.md This snippet shows the main application file (`server.py`) that initializes a Sanic app and uses the `autodiscover` utility function to find and register components from specified modules and packages. It also includes example console output demonstrating the execution of registered listeners. ```python from sanic import Sanic from sanic.response import empty import blueprints from utility import autodiscover app = Sanic("auto", register=True) autodiscover( app, blueprints, "parent.child", "listeners.something", recursive=True, ) app.route("/")(lambda _: empty()) ``` ```bash [2021-03-02 21:37:02 +0200] [880451] [INFO] Goin' Fast @ http://127.0.0.1:9999 [2021-03-02 21:37:02 +0200] [880451] [DEBUG] something [2021-03-02 21:37:02 +0200] [880451] [DEBUG] something @ nested [2021-03-02 21:37:02 +0200] [880451] [DEBUG] something @ level1 [2021-03-02 21:37:02 +0200] [880451] [DEBUG] something @ level3 [2021-03-02 21:37:02 +0200] [880451] [DEBUG] something inside __init__.py [2021-03-02 21:37:02 +0200] [880451] [INFO] Starting worker [880451] ``` -------------------------------- ### Sanic Signals API Example Python Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v21.3.md Illustrates the usage of the new Sanic Signals API. This example defines a signal handler, a background task that waits for a signal event, and a route that dispatches the signal. ```python @app.signal("foo.bar.") async def signal_handler(thing, **kwargs): print(f"[signal_handler] {thing=}", kwargs) async def wait_for_event(app): while True: print("> waiting") await app.event("foo.bar.*") print("> event found\n") @app.after_server_start async def after_server_start(app, loop): app.add_task(wait_for_event(app)) @app.get("/") async def trigger(request): await app.dispatch("foo.bar.baz") return response.text("Done.") ``` -------------------------------- ### Usage Example: Sanic Decorator (Always With Args) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/best-practices/decorators.md Shows how to apply a Sanic decorator that requires arguments to a route handler, illustrating the syntax @foobar(1, 2). ```python @app.get("/") @foobar(1, 2) async def handler(request: Request): return text("hi") ``` -------------------------------- ### Defining a Sanic Docker Image (Dockerfile) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/deployment/docker.md Specifies the steps to build a Docker image for the Sanic application. It starts from a Sanic base image, sets the working directory, copies application files, installs dependencies from requirements.txt, exposes port 8000, and defines the command to run the server. ```dockerfile FROM sanicframework/sanic:3.8-latest WORKDIR /sanic COPY . . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "server.py"] ``` -------------------------------- ### Installing Sanic HTTP/3 Dependency (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Install the necessary `aioquic` library required for Sanic's experimental HTTP/3 support using pip. ```Shell pip install sanic aioquic ``` ```Shell pip install sanic[http3] ``` -------------------------------- ### Start Docker and Sanic Server (Bash) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/mounting.md Commands to start the Nginx container using Docker Compose and then start the Sanic application server, listening on all interfaces on port 9999. ```bash $ docker-compose up -d ``` ```bash $ sanic server.app --port=9999 --host=0.0.0.0 ``` -------------------------------- ### Running Custom Inspector Commands (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/README.md The Sanic inspector allows defining and running custom commands tailored to your application's needs. This example shows executing a hypothetical `migrations` command via the inspector. ```sh sanic inspect migrations ``` -------------------------------- ### Usage Example: Sanic Decorator (Without Args) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/best-practices/decorators.md Shows how to apply a Sanic decorator that does not take arguments to a route handler, illustrating the syntax @foobar. ```python @app.get("/") @foobar async def handler(request: Request): return text("hi") ``` -------------------------------- ### Testing Multiple Dependency Injection (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/injection.md Example curl command to test the Sanic route that injects both `PersonID` and `Person` using a custom constructor. ```shell $ curl localhost:8000/person/123 PersonID(person_id=123) Person(person_id=PersonID(person_id=123), name='noname', age=111) ``` -------------------------------- ### Defining Sanic Application Factory Function Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Provides a Python example of creating a function that returns a Sanic application instance, which is a recommended pattern for managing application configuration and dependencies. ```python from sanic import Sanic def create_app() -> Sanic: app = Sanic("MyApp") return app ``` -------------------------------- ### Testing Basic Dataclass Injection (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/injection.md Example curl command to test the Sanic route that injects the `IceCream` dataclass based on the path parameter. ```shell $ curl localhost:8000/chocolate You chose Chocolate (Yum!) ``` -------------------------------- ### Creating a Basic Async Sanic Handler with Routing (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ko/guide/basics/handlers.md Shows a practical example of defining an asynchronous Sanic handler. It uses the `@app.get()` decorator to route GET requests to the `/foo` endpoint and the `text()` helper function from `sanic.response` to create a simple text response. ```python from sanic.response import text @app.get("/foo") async def foo_handler(request): return text("I said foo!") ``` -------------------------------- ### Correctly Attaching Blueprint in Sanic Multi-Process (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md This example demonstrates the correct pattern for attaching application setup logic (like blueprints) in a Sanic application designed for multi-process execution. Logic intended for workers should be outside the if __name__ == "__main__": block, potentially using __mp_main__ or other Sanic lifecycle events if needed, while app.run() remains in __main__. ```python from sanic import Sanic from my.other.module import bp app = Sanic("MyApp") if __name__ == "__mp_main__": app.blueprint(bp) elif __name__ == "__main__": app.run() ``` -------------------------------- ### Start Sanic HTTP/3 and HTTP/1.1 Servers via CLI Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v22.6.md Starts Sanic servers listening on both HTTP/3 and HTTP/1.1 protocols simultaneously via the command line interface. Requires aioquic and TLS configuration for HTTP/3. ```shell $ sanic path.to.server:app --http=3 --http=1 ``` ```shell $ sanic path.to.server:app -3 -1 ``` -------------------------------- ### Starting Sanic Simple Static Server with Reload (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Start the Sanic simple static server with automatic code reloading enabled, monitoring the specified directory for changes. ```Shell sanic ./path/to/dir --simple --reload --reload-dir=./path/to/dir ``` -------------------------------- ### Running Sanic App (Python - app.run) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Start the Sanic server using the convenient `app.run()` method, specifying host, port, and access log settings. ```Python if __name__ == "__main__": app.run(host='0.0.0.0', port=1337, access_log=False) ``` -------------------------------- ### Scaling Sanic Workers via Inspector (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/README.md Issue commands to a running Sanic application via the inspector, such as scaling the number of worker processes. This example demonstrates scaling the application to 4 workers using the `scale` command. ```sh sanic inspect scale 4 ``` -------------------------------- ### Initializing a Sanic Application Instance (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/basics/app.md Explains how to create a basic Sanic application instance using the `Sanic()` class. Mentions the common practice of placing this in `server.py`. ```python # /path/to/server.py from sanic import Sanic app = Sanic("MyHelloWorldApp") ``` -------------------------------- ### File Streaming with Content-Length Header in Sanic Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/advanced/streaming.md This example shows how to disable chunked transfer encoding for file streaming and manually add the `Content-Length` header. It uses `aiofiles.os.stat` to get the file size and includes it in the headers passed to `response.file_stream`. ```python from aiofiles import os as async_os from sanic.response import file_stream @app.route("/") async def index(request): file_path = "/srv/www/whatever.png" file_stat = await async_os.stat(file_path) headers = {"Content-Length": str(file_stat.st_size)} return await file_stream( file_path, headers=headers, ) ``` -------------------------------- ### Using ReusableClient within Context Manager (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-testing/clients.md Illustrates using the ReusableClient within a 'with' statement, which acts as a context manager to control the server's lifecycle. The server starts upon entering the 'with' block and stops upon exiting, allowing multiple requests to be made to the same running instance efficiently. ```python from sanic_testing.reusable import ReusableClient def test_multiple_endpoints_on_same_server(app): client = ReusableClient(app) with client: _, response = client.get("/path/to/1") assert response.status == 200 _, response = client.get("/path/to/2") assert response.status == 200 ``` -------------------------------- ### Sanic Class-Based View with Path Parameters Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/advanced/class-based-views.md This example illustrates how to handle path parameters within a Sanic class-based view. The path parameter `name` is defined in the route string (`/`) and is automatically passed as an argument to the corresponding HTTP method (`get`) when a request matching the route is received. ```python class NameView(HTTPMethodView): def get(self, request, name): return text("Hello {}".format(name)) app.add_route(NameView.as_view(), "/") ``` -------------------------------- ### Install Uvicorn for Sanic Deployment (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/release-notes/v22.3.md Provides the command to install the uvicorn library, which is recommended for deploying Sanic applications with gunicorn. ```shell pip install uvicorn ``` -------------------------------- ### Running Sanic App with HTTP/3 and HTTP/1.1 (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Start the Sanic server from the command line, enabling both HTTP/3 and HTTP/1.1 simultaneously using the respective flags. ```Shell sanic path.to.server:app --http=3 --http=1 ``` ```Shell sanic path.to.server:app -3 -1 ``` -------------------------------- ### Example Sanic Config File Content - Python Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ja/guide/deployment/configuration.md Shows the simple key-value structure typically used in a Python file intended to be loaded as Sanic configuration. ```python # my_config.py A = 1 B = 2 ``` -------------------------------- ### Sanic CLI Help Output (Text) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ja/guide/deployment/running.md Displays the full help output for the `sanic` command-line interface, listing all available options for running applications, simple servers, configuring TLS, workers, development modes, and output verbosity. Useful for understanding CLI capabilities. ```text $ sanic --help usage: sanic [-h] [--version] [--factory] [-s] [-H HOST] [-p PORT] [-u UNIX] [--cert CERT] [--key KEY] [--tls DIR] [--tls-strict-host] [-w WORKERS | --fast] [--access-logs | --no-access-logs] [--debug] [-d] [-r] [-R PATH] [--motd | --no-motd] [-v] [--noisy-exceptions | --no-noisy-exceptions] module ▄███ █████ ██ ▄█▄ ██ █ █ ▄██████████ ██ █ █ █ ██ █ █ ██ ▀███████ ███▄ ▀ █ █ ██ ▄ █ ██ ██ █████████ █ ██ █ █ ▄▄ ████ ████████▀ █ █ █ ██ █ ▀██ ███████ To start running a Sanic application, provide a path to the module, where app is a Sanic() instance: $ sanic path.to.server:app Or, a path to a callable that returns a Sanic() instance: $ sanic path.to.factory:create_app --factory Or, a path to a directory to run as a simple HTTP server: $ sanic ./path/to/static --simple Required ======== Positional: module Path to your Sanic app. Example: path.to.server:app If running a Simple Server, path to directory to serve. Example: ./ Optional ======== General: -h, --help show this help message and exit --version show program's version number and exit Application: --factory Treat app as an application factory, i.e. a () -> callable -s, --simple Run Sanic as a Simple Server, and serve the contents of a directory (module arg should be a path) Socket binding: -H HOST, --host HOST Host address [default 127.0.0.1] -p PORT, --port PORT Port to serve on [default 8000] -u UNIX, --unix UNIX location of unix socket TLS certificate: --cert CERT Location of fullchain.pem, bundle.crt or equivalent --key KEY Location of privkey.pem or equivalent .key file --tls DIR TLS certificate folder with fullchain.pem and privkey.pem May be specified multiple times to choose multiple certificates --tls-strict-host Only allow clients that send an SNI matching server certs Worker: -w WORKERS, --workers WORKERS Number of worker processes [default 1] --fast Set the number of workers to max allowed --access-logs Display access logs --no-access-logs No display access logs Development: --debug Run the server in debug mode -d, --dev Currently is an alias for --debug. But starting in v22.3, --debug will no longer automatically trigger auto_restart. However, --dev will continue, effectively making it the same as debug + auto_reload. -r, --reload, --auto-reload Watch source directory for file changes and reload on changes -R PATH, --reload-dir PATH Extra directories to watch and reload on changes Output: --motd Show the startup display --no-motd No show the startup display -v, --verbosity Control logging noise, eg. -vv or --verbosity=2 [default 0] --noisy-exceptions Output stack traces for all exceptions --no-noisy-exceptions No output stack traces for all exceptions ``` -------------------------------- ### Sanic Class-Based View with Multiple HTTP Methods Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/advanced/class-based-views.md This snippet provides a comprehensive example of a Sanic `HTTPMethodView` subclass implementing various HTTP methods (`get`, `post`, `put`, `patch`, `delete`). It shows how to define both synchronous and asynchronous methods within the class and how to register the class-based view using `app.add_route`. ```python from sanic.views import HTTPMethodView from sanic.response import text class SimpleView(HTTPMethodView): def get(self, request): return text("I am get method") # You can also use async syntax async 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(), "/") ``` -------------------------------- ### Installing Sanic Extensions Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v21.12.md Provides the commands to install Sanic Extensions, which offers additional features for API development like CORS, OpenAPI docs, and dependency injection. The preferred method is installing it as an extra with Sanic. ```shell $ pip install sanic[ext] ``` ```shell $ pip install sanic sanic-ext ``` -------------------------------- ### Example Curl Command with Query Parameters (Bash) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/basics/request.md A command-line example using `curl` to demonstrate sending multiple query parameters with the same key to a Sanic application. This shows the input format that Sanic's request object parses. ```bash $ curl http://localhost:8000\?key1\=val1\&key2\=val2\&key1\=val3 ``` -------------------------------- ### Implementing a Basic Sanic Class-Based View Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/advanced/class-based-views.md This example demonstrates how to create a basic class-based view in Sanic by subclassing `HTTPMethodView`. Different HTTP methods (`get`, `post`, `put`) are implemented as methods within the class, providing a structured way to handle requests for a single endpoint. The view is registered using `app.add_route` with `FooBar.as_view()`. ```python from sanic.views import HTTPMethodView class FooBar(HTTPMethodView): async def get(self, request): ... async def post(self, request): ... async def put(self, request): ... app.add_route(FooBar.as_view(), "/foobar") ``` -------------------------------- ### Install Jinja2 Dependency Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/templating.md Install the Jinja2 library using pip, which is required for Sanic Extensions templating support. ```bash pip install Jinja2 ``` -------------------------------- ### Managing Sanic systemd Service with systemctl Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/nginx.md Provides bash commands to manage the Sanic systemd service. `daemon-reload` reloads the systemd configuration, `start` begins the service execution, and `enable` configures the service to start automatically on boot. ```bash systemctl daemon-reload systemctl start sanicexample systemctl enable sanicexample ``` -------------------------------- ### Managing Sanic Systemd Service Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/deployment/nginx.md These commands are used to manage the Sanic systemd service: reloading the daemon, starting the service, and enabling it to start automatically on boot. ```bash sudo systemctl daemon-reload sudo systemctl start sanicexample sudo systemctl enable sanicexample ``` -------------------------------- ### Test Forwarded Header Starting with Malformed Field (Example 10) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/advanced/proxy-headers.md Uses curl to send a request with a 'Forwarded' header starting with a malformed field ('b0rked'), piping the output to jq. ```bash $ curl localhost:8000/fwd \ -H 'Forwarded: b0rked;secret=mySecret;proto=wss' | jq ``` -------------------------------- ### Running Sanic Simple Server (Bash) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ja/guide/deployment/running.md Illustrates how to use the Sanic Simple Server feature via the CLI to serve static files from a specified directory. Useful for quickly setting up a local HTTP server for static content. ```bash sanic ./path/to/dir --simple ``` -------------------------------- ### Running Sanic App with HTTP/3 (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Start the Sanic server from the command line, explicitly enabling HTTP/3 support using the `--http=3` or `-3` flag. ```Shell sanic path.to.server:app --http=3 ``` ```Shell sanic path.to.server:app -3 ``` -------------------------------- ### Defining a basic Sanic GET route Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/http/methods.md Defines a simple asynchronous GET route at the root path "/" that returns "Hello, world." text. This route serves as the base for automatically generated HEAD and OPTIONS endpoints by Sanic Extensions. ```Python @app.get("/") async def hello_world(request): return text("Hello, world.") ``` -------------------------------- ### Send GET Request to Get User by ID (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/orm.md Uses the 'curl' command-line tool to send an explicit GET request to the '/user/1' endpoint on the local server (http://127.0.0.1:8000). This example demonstrates fetching a specific user by their ID, matching the typical HTTP method for this type of resource retrieval. ```sh curl --location --request GET 'http://127.0.0.1:8000/user/1' {"user": "I am foo"} ``` -------------------------------- ### Example Response from Sanic App Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/orm.md An example of the JSON response received from the Sanic application after executing the query via Mayim, showing a list of country objects. ```JSON {"countries":[{"code":"AFG","name":"Afghanistan","continent":"Asia","region":"Southern and Central Asia","capital":{"id":1,"name":"Kabul","district":"Kabol","population":1780000}},{"code":"ALB","name":"Albania","continent":"Europe","region":"Southern Europe","capital":{"id":34,"name":"Tirana","district":"Tirana","population":270000}},{"code":"DZA","name":"Algeria","continent":"Africa","region":"Northern Africa","capital":{"id":35,"name":"Alger","district":"Alger","population":2168000}},{"code":"ASM","name":"American Samoa","continent":"Oceania","region":"Polynesia","capital":{"id":54,"name":"Fagatogo","district":"Tutuila","population":2323}}]} ``` -------------------------------- ### Starting Docker Compose Services (Shell) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/zh/guide/deployment/docker.md Executes the Docker Compose command to build (if necessary) and start the services defined in the docker-compose.yml file in detached mode (-d). ```shell docker-compose up -d ``` -------------------------------- ### Install Mayim Dependencies Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/orm.md Install the necessary Python packages for using Mayim with Sanic Extensions, including the Sanic Extensions library and Mayim with the PostgreSQL driver. ```Shell pip install sanic-ext pip install mayim[postgres] ``` -------------------------------- ### Preparing and Serving Multiple Sanic Applications - Python Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v22.3.md Shows how to instantiate multiple Sanic applications or prepare a single application to listen on multiple ports using the app.prepare() method. The applications are then served concurrently in the same process by calling Sanic.serve(). This is an alternative to app.run(). ```Python app = Sanic("One") app2 = Sanic("Two") app.prepare(port=9999) app.prepare(port=9998) app.prepare(port=9997) app2.prepare(port=8888) app2.prepare(port=8887) Sanic.serve() ``` -------------------------------- ### Setup Sanic App with Mayim Extension Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/orm.md Initialize a Sanic application and register the SanicMayimExtension. Configure the extension with a Mayim executor class and the database connection string (DSN). ```Python # ./server.py from sanic import Sanic, Request, json from sanic_ext import Extend from mayim.executor import PostgresExecutor from mayim.extensions import SanicMayimExtension from models import Country class CountryExecutor(PostgresExecutor): async def select_all_countries( self, limit: int = 4, offset: int = 0 ) -> list[Country]: ... app = Sanic("Test") Extend.register( SanicMayimExtension( executors=[CountryExecutor], dsn="postgres://...", ) ) ``` -------------------------------- ### Start Sanic HTTP/3 and HTTP/1.1 Servers via Python API Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v22.6.md Configures and starts Sanic servers listening on both HTTP/3 and HTTP/1.1 protocols simultaneously using the multi-serve feature in the Python API. Requires aioquic and TLS configuration for HTTP/3. ```python app.prepre(version=3) app.prepre(version=1) Sanic.serve() ``` -------------------------------- ### Install Specific Sanic Version Bash Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/release-notes/v21.3.md Demonstrates how to install a specific version range of Sanic using pip and freeze the dependencies to a requirements file. This is useful for staying on an older LTS version like 20.12. ```bash pip install "sanic>=20.12,<20.13" pip freeze > requirements.txt ``` -------------------------------- ### Sanic OPTIONS Request Handler Setup (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/how-to/cors.md Provides functions to identify routes missing an OPTIONS handler and dynamically add a generic handler that returns the appropriate CORS headers using the `_add_cors_headers` function from `cors.py`. This setup is registered to run before the server starts. ```python from collections import defaultdict from typing import Dict, FrozenSet from sanic import Sanic, response from sanic.router import Route from cors import _add_cors_headers def _compile_routes_needing_options( routes: Dict[str, Route] ) -> Dict[str, FrozenSet]: needs_options = defaultdict(list) # This is 21.12 and later. You will need to change this for older versions. for route in routes.values(): if "OPTIONS" not in route.methods: needs_options[route.uri].extend(route.methods) return { uri: frozenset(methods) for uri, methods in dict(needs_options).items() } def _options_wrapper(handler, methods): def wrapped_handler(request, *args, **kwargs): nonlocal methods return handler(request, methods) return wrapped_handler async def options_handler(request, methods) -> response.HTTPResponse: resp = response.empty() _add_cors_headers(resp, methods) return resp def setup_options(app: Sanic, _): app.router.reset() needs_options = _compile_routes_needing_options(app.router.routes_all) for uri, methods in needs_options.items(): app.add_route( _options_wrapper(options_handler, methods), uri, methods=["OPTIONS"], ) app.router.finalize() ``` -------------------------------- ### Example: Listing Users via cURL - Shell Source: https://github.com/sanic-org/sanic-guide/blob/main/src/ja/guide/how-to/orm.md This cURL command demonstrates how to interact with the `/user` endpoint. The example uses a POST request, although the Python code defines this route as a GET endpoint. It shows the expected JSON response containing a list of users. ```Shell curl --location --request POST 'http://127.0.0.1:8000/user' {"users":["I am foo", "I am bar"]} ``` -------------------------------- ### Running Basic Sanic App (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md A minimal example demonstrating how to initialize a Sanic application and run it using the default app.run() method within the standard __main__ block. This is suitable for simple cases or single-process execution. ```python app = Sanic("MyApp") if __name__ == "__main__": app.run() ``` -------------------------------- ### Example Usage of Custom Serializer - Sanic Extensions - Shell Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/plugins/sanic-ext/convenience.md Provides a command-line example using `curl` to demonstrate the output produced by the route handler using the custom `message` serializer defined previously. It shows the resulting JSON structure. ```Shell $ curl localhost:8000/eat_cookies -X POST { "request_id": "ef81c45b-235c-46dd-9dbd-b550f8fa77f9", "action": "eat_cookies", "message": "This is a message" } ``` -------------------------------- ### Simple Caddyfile Configuration - Caddyfile Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/caddy.md The equivalent Caddyfile configuration for the simple reverse proxy setup. It defines a site block for 'example.com' and uses the 'reverse_proxy' directive to forward all incoming requests for this domain to the Sanic application running on localhost port 8001. ```caddyfile example.com { reverse_proxy localhost:8001 } ``` -------------------------------- ### Running Sanic Application as Python Module Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Demonstrates how to start a Sanic application using the `python -m sanic` command, specifying the application module path and common server options like host, port, and number of workers. ```bash python -m sanic server.app --host=0.0.0.0 --port=1337 --workers=4 ``` -------------------------------- ### Viewing Sanic CLI Help Options Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Displays the comprehensive list of command-line arguments and options available for configuring and running a Sanic server directly from the terminal. ```text $ sanic --help ▄███ █████ ██ ▄█▄ ██ █ █ ▄██████████ ██ █ █ █ ██ █ █ ██ ▀███████ ███▄ ▀ █ █ ██ ▄ █ ██ ██ █████████ █ ██ █ █ ▄▄ ████ ████████▀ █ █ █ ██ █ ▀██ ███████ To start running a Sanic application, provide a path to the module, where app is a Sanic() instance: $ sanic path.to.server:app Or, a path to a callable that returns a Sanic() instance: $ sanic path.to.factory:create_app --factory Or, a path to a directory to run as a simple HTTP server: $ sanic ./path/to/static --simple Required ======== Positional: module Path to your Sanic app. Example: path.to.server:app If running a Simple Server, path to directory to serve. Example: ./ Optional ======== General: -h, --help show this help message and exit --version show program's version number and exit Application: --factory Treat app as an application factory, i.e. a () -> callable -s, --simple Run Sanic as a Simple Server, and serve the contents of a directory (module arg should be a path) --inspect Inspect the state of a running instance, human readable --inspect-raw Inspect the state of a running instance, JSON output --trigger-reload Trigger worker processes to reload --trigger-shutdown Trigger all processes to shutdown HTTP version: --http {1,3} Which HTTP version to use: HTTP/1.1 or HTTP/3. Value should be either 1, or 3. [default 1] -1 Run Sanic server using HTTP/1.1 -3 Run Sanic server using HTTP/3 Socket binding: -H HOST, --host HOST Host address [default 127.0.0.1] -p PORT, --port PORT Port to serve on [default 8000] -u UNIX, --unix UNIX location of unix socket TLS certificate: --cert CERT Location of fullchain.pem, bundle.crt or equivalent --key KEY Location of privkey.pem or equivalent .key file --tls DIR TLS certificate folder with fullchain.pem and privkey.pem May be specified multiple times to choose multiple certificates --tls-strict-host Only allow clients that send an SNI matching server certs Worker: -w WORKERS, --workers WORKERS Number of worker processes [default 1] --fast Set the number of workers to max allowed --single-process Do not use multiprocessing, run server in a single process --legacy Use the legacy server manager --access-logs Display access logs --no-access-logs No display access logs Development: --debug Run the server in debug mode -r, --reload, --auto-reload Watch source directory for file changes and reload on changes -R PATH, --reload-dir PATH Extra directories to watch and reload on changes -d, --dev debug + auto reload --auto-tls Create a temporary TLS certificate for local development (requires mkcert or trustme) Output: --coffee Uhm, coffee? --no-coffee No uhm, coffee? --motd Show the startup display --no-motd No show the startup display -v, --verbosity Control logging noise, eg. -vv or --verbosity=2 [default 0] --noisy-exceptions Output stack traces for all exceptions --no-noisy-exceptions No output stack traces for all exceptions ``` -------------------------------- ### Incorrectly Attaching Blueprint in Sanic Main Block (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md This example shows a common mistake where application setup logic, such as attaching blueprints, is placed inside the if __name__ == "__main__": block. This logic will only execute in the main process and not in the worker processes, preventing the blueprint from being attached correctly in a multi-worker setup. ```python from sanic import Sanic from my.other.module import bp app = Sanic("MyApp") if __name__ == "__main__": app.blueprint(bp) app.run() ``` -------------------------------- ### Running Sanic App with HTTP/3 (Python) Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Start the Sanic server programmatically using `app.run()`, specifying the desired HTTP version as 3. ```Python app.run(version=3) ``` -------------------------------- ### Running Sanic Application Factory via CLI Source: https://github.com/sanic-org/sanic-guide/blob/main/src/en/guide/deployment/running.md Shows different command-line syntaxes for starting a Sanic application defined by a factory function, including using the explicit `--factory` flag or implicit referencing. ```sh sanic server:create_app --factory ``` ```sh sanic "server:create_app()" ``` ```sh sanic server:create_app ```