### Sanic CLI Usage Examples Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Provides examples of how to run the Sanic CLI for different application setups, including global app instances, factory patterns, and simple directory serving. ```Shell $ sanic path.to.module:app # global app instance $ sanic path.to.module:create_app # factory pattern $ sanic ./path/to/directory/ # simple serve ``` -------------------------------- ### Create and Run Sanic Server Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Demonstrates the low-level API for creating a Sanic server instance without starting it immediately. This is useful for integrating Sanic into other systems. The example shows how to manually start the server and serve requests indefinitely, including setting up the event loop with uvloop. ```Python import asyncio import uvloop from sanic import Sanic, response app = Sanic("Example") @app.route("/") async def test(request): return response.json({"answer": "42"}) async def main(): server = await app.create_server() await server.startup() await server.serve_forever() if __name__ == "__main__": asyncio.set_event_loop(uvloop.new_event_loop()) asyncio.run(main()) ``` -------------------------------- ### Sanic Hello World Example Source: https://sanic.readthedocs.io/en/latest/index A basic 'Hello World' example for the Sanic web framework. It defines a simple web application that responds with a JSON object containing 'hello': 'world' when the root URL is accessed. The example demonstrates how to create a Sanic app, define a route, and run the server. ```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() ``` -------------------------------- ### Blueprint Route Example Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Shows a basic route definition within a Sanic Blueprint, handling GET requests to the root URL and returning text. ```Python @bp1.route("/") async def bp1_route(request): return text("bp1") ``` -------------------------------- ### Decorate Function as a Route (GET) Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Decorates a function to be registered as a route. This example shows how to define a simple GET endpoint for '/hello' that returns 'Hello, World!'. ```python from sanic import Sanic, Request from sanic.response import text app = Sanic(__name__) @app.route("/hello") async def hello(request: Request): return text("Hello, World!") ``` -------------------------------- ### Example of Dispatching an Event in Sanic Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Demonstrates how to dispatch a 'user.registration.created' event with associated context after a POST request to '/register'. This example shows the integration of signal dispatching within a web request handler. ```Python @app.signal("user.registration.created") async def send_registration_email(**context): await send_email(context["email"], template="registration") @app.post("/register") async def handle_registration(request): await do_registration(request) await request.app.dispatch( "user.registration.created", context={"email": request.json.email} ) ``` -------------------------------- ### Sanic Server Methods Source: https://sanic.readthedocs.io/en/latest/genindex Details methods for server operations, including starting, serving, and handling server-related tasks. ```python sanic.server.HttpProtocol.send() ``` ```python sanic.server.AsyncioServer.serve_forever() ``` ```python sanic.server.AsyncioServer.start_serving() ``` ```python sanic.server.AsyncioServer.startup() ``` ```python sanic.server.AsyncioServer.wait_closed() ``` ```python sanic.server.try_use_uvloop() ``` -------------------------------- ### Define GET Endpoint with Sanic Route Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorator to register a function as a route. This example shows defining a GET endpoint for '/hello' that returns a simple text response. ```python @app.route(“/hello”) async def hello(request: Request): return text(“Hello, World!”) ``` -------------------------------- ### Example of Waiting for an Event in Sanic Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Illustrates how to continuously wait for the 'foo.bar.baz' event within a Sanic application. The `wait_for_event` coroutine is added as a task after the server starts, demonstrating asynchronous event monitoring. ```Python async def wait_for_event(app): while True: print(”> waiting”) await app.event(“foo.bar.baz”) print(”> event found”) @app.after_server_start async def after_server_start(app, loop): app.add_task(wait_for_event(app)) ``` -------------------------------- ### Install Sanic with no uvloop or ujson Source: https://sanic.readthedocs.io/en/latest/index This snippet shows how to install Sanic while disabling the use of uvloop and ujson for performance. It involves setting environment variables before running the pip install command. This is useful if you encounter compatibility issues or prefer not to use these specific packages. ```bash export SANIC_NO_UVLOOP=true export SANIC_NO_UJSON=true pip3 install --no-binary :all: sanic ``` -------------------------------- ### Sanic App Methods Source: https://sanic.readthedocs.io/en/latest/genindex Details methods and properties associated with the Sanic application class, including starting and stopping the server, handling signals, and managing configurations. ```python sanic.app.Sanic.serve() ``` ```python sanic.app.Sanic.serve_single() ``` ```python sanic.app.Sanic.set_serving() ``` ```python sanic.app.Sanic.should_auto_reload() ``` ```python sanic.app.Sanic.shutdown_tasks() ``` ```python sanic.app.Sanic.signal() ``` ```python sanic.app.Sanic.signalize() ``` ```python sanic.app.Sanic.static() ``` ```python sanic.app.Sanic.stop() ``` ```python sanic.app.Sanic.tasks ``` ```python sanic.app.Sanic.test_client ``` ```python sanic.app.Sanic.unregister_app() ``` ```python sanic.app.Sanic.update_config() ``` ```python sanic.app.Sanic.url_for() ``` ```python sanic.app.Sanic.websocket() ``` -------------------------------- ### Blueprint Middleware Example Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Demonstrates how to define a request middleware for a specific Sanic Blueprint, which will be executed before the route handler. ```Python @bp1.on_request async def bp1_only_middleware(request): print("applied on Blueprint : bp1 Only") ``` -------------------------------- ### Setting Sanic Start Method Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Demonstrates how to explicitly set the multiprocessing start method for Sanic, which can be important for compatibility and performance on different operating systems. ```Python from sanic import Sanic Sanic.start_method = "fork" ``` -------------------------------- ### Listener for Reload Process Start Event Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorator for registering a listener that is triggered specifically during the Sanic reload process, not on worker processes. Useful for setup tasks that should only run once when the server reloads. ```python @app.reload_process_start async def on_reload_process_start(app: Sanic): print("Reload process started") ``` -------------------------------- ### Implement GET and PUT methods in HTTPMethodView Source: https://sanic.readthedocs.io/en/latest/sanic/api/core Example of subclassing HTTPMethodView and implementing GET and PUT methods to handle corresponding HTTP requests. Each method returns a text response. ```python class DummyView(HTTPMethodView): def get(self, request: Request): return text('I am get method') def put(self, request: Request): return text('I am put method') ``` -------------------------------- ### Sanic Get App Method Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'get_app()' class method for retrieving the Sanic application instance. ```python get_app() -> Sanic: ...(sanic.app.Sanic class method) ``` -------------------------------- ### Sanic Example Modernization Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Fixes examples to use modern implementations, making them more relevant and easier to understand. ```Python #2305 Fix examples to use modern implementations ``` -------------------------------- ### Sanic HTTP Protocol and Server Management Source: https://sanic.readthedocs.io/en/latest/genindex Details classes and methods related to the HTTP protocol and server operations in Sanic. This includes managing HTTP protocol states and starting the server. ```Python sanic.http.Stage.HANDLER sanic.http.Stage.IDLE sanic.http.Http sanic.http.Http3 sanic.server.HttpProtocol sanic.server.AsyncioServer.is_serving() sanic.server.HttpProtocol.HTTP_CLASS ``` -------------------------------- ### Sanic Application Methods Source: https://sanic.readthedocs.io/en/latest/genindex This section covers various methods for interacting with the Sanic application instance, including getting the application instance, enabling websockets, and dispatching delayed tasks. ```python enable_websocket() dispatch_delayed_tasks() get_app() -> Sanic get_server_location() -> str get_task() -> asyncio.Task extend() finalize() finalize_middleware() get() get_address() get_motd_data() exception() event() ``` -------------------------------- ### Run Sanic Server with Custom Port and Debug Mode Source: https://sanic.readthedocs.io/en/latest/sanic/api/app This example demonstrates how to initialize a Sanic application and run it on a specific port with development mode enabled. It defines a simple route that returns a JSON response. ```python from sanic import Sanic, Request, json app = Sanic("TestApp") @app.get("/") async def handler(request: Request): return json({"foo": "bar"}) if __name__ == "__main__": app.run(port=9999, dev=True) ``` -------------------------------- ### Blueprint Group Middleware Example Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Shows how to apply a middleware to an entire Blueprint Group, ensuring it's executed for all blueprints within that group. ```Python @group1.on_request async def group_middleware(request): print("common middleware applied for both bp1 and bp2") ``` -------------------------------- ### Sanic: Register Before Server Start Listener Source: https://sanic.readthedocs.io/en/latest/sanic/api/app A decorator for registering a listener that executes before the Sanic server starts on all worker processes. This is ideal for initializing global resources, such as database connection pools or cache clients, that will be shared across the application. ```python from sanic import Sanic app = Sanic(__name__) @app.before_server_start async def on_before_server_start(app: Sanic): print("Before server start") ``` -------------------------------- ### Setup Sanic Event Loop Source: https://sanic.readthedocs.io/en/latest/sanic/api/app The `setup_loop` method is an internal Sanic method responsible for configuring the event loop. It attempts to use `uvloop` if available, otherwise it falls back to a Windows selector loop on Windows systems. ```python setup_loop() ``` -------------------------------- ### Create and Group Sanic Blueprints Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints This example demonstrates how to create individual Sanic Blueprints and then group them using the Blueprint.group() method. It also shows how to apply middleware to the entire group and define routes within each blueprint. ```python from sanic import Blueprint, Sanic from sanic.response import text # Create individual blueprints bp1 = Blueprint("bp1", url_prefix="/bp1") bp2 = Blueprint("bp2", url_prefix="/bp2") bp3 = Blueprint("bp3", url_prefix="/bp4") bp4 = Blueprint("bp3", url_prefix="/bp4") # Group blueprints without versioning group1 = Blueprint.group(bp1, bp2) # Group blueprints with versioning and a custom version prefix group2 = Blueprint.group(bp3, bp4, version_prefix="/api/v", version="1") # Middleware for a specific blueprint @bp1.on_request async def bp1_only_middleware(request): print("applied on Blueprint : bp1 Only") # Route for bp1 @bp1.route("/") async def bp1_route(request): return text("bp1") # Route for bp2 with a parameter @bp2.route("/") async def bp2_route(request, param): return text(param) # Route for bp3 @bp3.route("/") async def bp3_route(request): return text("bp3") # Route for bp4 with a parameter @bp4.route("/") async def bp4_route(request, param): return text(param) # Middleware for the entire group1 @group1.on_request async def group_middleware(request): print("common middleware applied for both bp1 and bp2") # Example of how to run the Sanic app (requires Sanic instance) # app = Sanic(__name__) # app.blueprint(group1) # app.blueprint(group2) # if __name__ == "__main__": # app.run(host="0.0.0.0", port=8000) ``` -------------------------------- ### Sanic Request Methods (Get) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'get()' method for retrieving values from various Sanic components, including the application, blueprints, cookie jars, request parameters, and routers. ```python get(key: str, default: Optional[Any] = None) -> Any ``` -------------------------------- ### Sanic Instance Naming Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Allows instance names in Sanic to start with an underscore. ```Python #2335 Allow underscore to start instance names ``` -------------------------------- ### Define GET Route in Sanic Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Shows how to use the `get` decorator to define a route handler for HTTP GET requests in Sanic. It includes parameters for specifying the URI, host, and handling of trailing slashes. ```python app.get( uri='/example', host='example.com', strict_slashes=True ) def handler(request): return text('Hello, world!') ``` -------------------------------- ### Register Main Process Start Listener Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Decorator to register a listener for the main_process_start event, which fires on the main process before workers start. Ideal for initializing shared or worker-unsafe resources. ```python import sanic @app.main_process_start async def on_main_process_start(app: sanic.Sanic): print("Main process started") ``` -------------------------------- ### Create Signal Handler in Sanic Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorator for creating a signal handler. This example demonstrates how to set up a handler for a signal named 'foo.bar.', which receives the 'thing' parameter and any additional keyword arguments. ```python @app.signal("foo.bar.") async def signal_handler(thing, **kwargs): print(f"[signal_handler] {thing=}", kwargs) ``` -------------------------------- ### Sanic Get All Method Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'get_all()' method for retrieving all values for a given header key in Sanic's compat.Header. ```python get_all(key: str) -> List[str]: ...(sanic.compat.Header method) ``` -------------------------------- ### Sanic ApplicationState Class Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Manages the overall state of the Sanic application, including configuration parameters like host, port, SSL settings, and operational states such as running, started, and stopping. It is accessible via `app.state`. ```Python class ApplicationState(_app_ , _asgi=False_ , _coffee=False_ , _fast=False_ , _host=''_ , _port=0_ , _ssl=None_ , _sock=None_ , _unix=None_ , _mode=Mode.PRODUCTION_ , _reload_dirs= _, _auto_reload=False_ , _server=Server.SANIC_ , _is_running=False_ , _is_started=False_ , _is_stopping=False_ , _verbosity=0_ , _workers=0_ , _primary=True_ , _server_info= _, __init=False_): """Application state. This class is used to store the state of the application. It is instantiated by the application and is available as app.state. """ pass ``` -------------------------------- ### Sanic ASGI Test Client Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Provides a testing client that uses ASGI to interact with the Sanic application. This requires the 'sanic-testing' package to be installed. It allows for in-depth testing of application handlers via the ASGI interface. ```python app.asgi_client ``` -------------------------------- ### Sanic: Register Before Server Start Listener Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorator for registering a listener for the 'before_server_start' event. This event is fired on all worker processes and is typically used for initializing global resources like database connection pools or cache clients. ```python @app.before_server_start async def on_before_server_start(app: Sanic): print(“Before server start”) ``` -------------------------------- ### Sanic HTTP Connection Stage Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Ensures HTTP connections start in the IDLE stage, avoiding delays and error messages during connection establishment. ```Python #2268 Make HTTP connections start in IDLE stage, avoiding delays and error messages ``` -------------------------------- ### Sanic Request Methods (Get Args) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet details the 'get_args()' method for retrieving arguments from a Sanic request. ```python get_args() -> RequestParameters ``` -------------------------------- ### Sanic Certificate Loader for In-Process Creation Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Adds a certificate loader for in-process certificate creation, simplifying TLS setup for development or testing environments. ```Python from sanic import Sanic, response app = Sanic(__name__) # The certificate loader would typically be configured during server startup. # This might involve passing specific arguments or using a configuration setting. # Example (conceptual - actual implementation depends on Sanic's internals): # app.run(host='0.0.0.0', port=8000, ssl={'cert': 'path/to/cert.pem', 'key': 'path/to/key.pem'}) # The new loader simplifies the creation or retrieval of these cert/key pairs. @app.get('/') async def hello_world(request): return response.text("Hello TLS!") ``` -------------------------------- ### Register Main Process Start Listener Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorator to register a listener for the main_process_start event, which fires only on the main process. Useful for initializing shared resources. ```python import sanic app = sanic.Sanic(__name__) @app.main_process_start async def on_main_process_start(app: sanic.Sanic): print("Main process started") ``` -------------------------------- ### Register Listener for Sanic Events Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Creates a listener for a specific event in the application's lifecycle. This can be used for setup or teardown tasks. It supports direct registration or using convenience methods like `before_server_start`. ```Python from sanic import Sanic app = Sanic(__name__) @app.listener("before_server_start") async def before_server_start_handler(app, loop): print("Server is about to start!") @app.listener("after_server_stop") async def after_server_stop_handler(app, loop): print("Server has stopped.") if __name__ == "__main__": app.run(host="0.0.0.0", port=8000) ``` -------------------------------- ### Decorate Function as a Route with Context Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Decorates a function to be registered as a route, including custom context keyword arguments. This example defines a '/greet' route where the 'name' is stored in the route's context and used in the response. ```python from sanic import Sanic, Request from sanic.response import text app = Sanic(__name__) @app.route("/greet", ctx_name="World") async def greet(request: Request): name = request.route.ctx.name return text(f"Hello, {name}!") ``` -------------------------------- ### Instantiate Sanic Application Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Demonstrates how to create an instance of the Sanic application class. It shows valid and invalid naming conventions for the application name. The constructor accepts various optional arguments for configuration. ```python from sanic import Sanic # This will cause an error because it contains spaces # Sanic("This is not legal") # This is legal app = Sanic("Hyphens-are-legal_or_also_underscores") # Example with more arguments (assuming types are imported) # from sanic.config import Config # from sanic.router import Router # from sanic.error import ErrorHandler # app = Sanic("MySanicApp", config=Config(), router=Router(), error_handler=ErrorHandler()) ``` -------------------------------- ### Register Listener for Reload Process Start Event Source: https://sanic.readthedocs.io/en/latest/sanic/api/app A decorator for registering a listener that is triggered specifically when the reload process starts. This event is not fired on worker processes. It's similar to `main_process_start` but exclusive to the reload process initiation. Refer to the Sanic guide for more details on listeners. ```python @app.reload_process_start async def on_reload_process_start(app: Sanic): pass ``` -------------------------------- ### Sanic Request and Response Methods (Get All) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet includes the 'get_all()' method for retrieving all values associated with a given header key in Sanic. ```python get_all(key: str) -> List[str] ``` -------------------------------- ### Sanic Configuration Loading Source: https://sanic.readthedocs.io/en/latest/genindex Explains methods for loading configuration settings in Sanic, including loading from files and environment variables. It also covers methods for accessing configuration values. ```Python sanic.config.Config.load() sanic.config.Config.load_environment_vars() sanic.request.Request.load_json() ``` -------------------------------- ### Sanic Extensions Access Source: https://sanic.readthedocs.io/en/latest/sanic/api/app A convenience property to access Sanic Extensions, which must be installed separately. It's useful for tasks like registering dependency injections within the application. ```python app.ext.dependency(SomeObject()) ``` -------------------------------- ### Start Sanic HTTP Server Source: https://sanic.readthedocs.io/en/latest/sanic/api/server Initiates an asynchronous HTTP server on a specified host and port. It supports various configurations including SSL, Unix sockets, multiple workers, and custom event loops. The function can also register system signals for graceful shutdown. ```python sanic.server.serve( host='127.0.0.1', port=8000, app=app, ssl=None, sock=None, unix=None, reuse_port=False, loop=None, protocol=sanic.server.protocols.http_protocol.HttpProtocol, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=sanic.models.server_types.Signal(), state=None, asyncio_server_kwargs=None, version=HTTP.VERSION_1 ) ``` -------------------------------- ### Serve Sanic Applications Source: https://sanic.readthedocs.io/en/latest/sanic/api/app The `serve` classmethod is the main entry point for running Sanic applications. It should be called within the `if __name__ == "__main__":` block. It supports serving one or more applications and has options for loading applications via an AppLoader instance or a factory function. It raises various RuntimeErrors and TypeErrors for invalid configurations. ```python if __name__ == "__main__": app.prepare() Sanic.serve() ``` -------------------------------- ### Sanic Developer Install Command Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Changes the command used for developer installation of Sanic. ```Python #2251 Change dev install command ``` -------------------------------- ### Finalize Sanic Application Routing Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Provides an example of finalizing the routing configuration for a Sanic application. This step is crucial for optimizing performance and ensuring all routes are correctly set up, though it's often called internally. ```python app.finalize() ``` -------------------------------- ### Retrieve Server Address and Port Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Gets the host address and port for a Sanic service. It supports different HTTP versions and automatic TLS configuration, providing default values for convenience. ```python host, port = Sanic._get_address(host='127.0.0.1', port=8000, version=HTTP.VERSION_1, auto_tls=False) ``` -------------------------------- ### BlueprintGroup Initialization Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Shows the constructor for the BlueprintGroup class, highlighting optional parameters for URL prefix, versioning, strict slashes, and name prefixing. ```python Blueprint.group(_url_prefix=None_, _version=None_, _strict_slashes=None_, _version_prefix='/v'_, _name_prefix=''_) ``` -------------------------------- ### Sanic Tests Folder Exclusion from Package Resolver Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Ensures the tests folder is not included in the installed package resolver, preventing potential conflicts or unnecessary inclusion during installation. ```Python # This change typically involves modifying setup.py or pyproject.toml # to exclude the 'tests' directory from being packaged. # Example modification in setup.py (conceptual): # setup( # ... # packages=find_packages(exclude=['tests', 'tests.*']), # ... # ) print("Sanic package resolver updated to exclude tests folder.") ``` -------------------------------- ### Sanic Blueprint Methods Source: https://sanic.readthedocs.io/en/latest/genindex Details methods for Sanic Blueprints, including registering routes and handling signals. ```python sanic.blueprints.Blueprint.signal() ``` ```python sanic.blueprints.Blueprint.static() ``` ```python sanic.blueprints.Blueprint.websocket() ``` -------------------------------- ### Prepare and Serve Sanic App Source: https://sanic.readthedocs.io/en/latest/sanic/api/app This snippet shows the basic structure for preparing and serving a Sanic application. It's typically used within an `if __name__ == "__main__":` block to ensure the code runs only when the script is executed directly. ```python if __name__ == "__main__": app.prepare() app.serve() ``` -------------------------------- ### Create Sanic Event Listener Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Creates a listener for specific events in the application's lifecycle, such as server startup or shutdown. It can be used as a decorator or called directly, with options for immediate application and priority. Convenience methods like `before_server_start` are often preferred. ```python @bp.listener("before_server_start") async def before_server_start(app, loop): # Example of using listener as a decorator pass ``` ```python def listener(listener_or_event, event_or_none=None, apply=True, *args, priority=0): # Create a listener for a specific event in the application’s lifecycle. pass ``` -------------------------------- ### Define Sanic GET Route Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorates a function to create a route definition for the HTTP GET method. It allows specifying the URI, host, versioning, and other parameters for the route. The 'ignore_body' parameter controls whether the request body is consumed. ```Python app.get("/uri", host="example.com", version=1, strict_slashes=True, version_prefix='/v', name="my_route", ignore_body=False, error_format="{message}", **ctx_kwargs) ``` -------------------------------- ### Load Configuration from Dictionary Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Shows how to update the Sanic application's configuration by passing a dictionary containing the settings. This is a straightforward way to programmatically set configuration values. ```python d = {"A": 1, "B": 2} config.update_config(d) ``` -------------------------------- ### Get Sanic Application Instance Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Retrieves an existing Sanic application instance by name. It's recommended to use this within methods called after the app is created to avoid potential import-time errors. It can optionally create a new instance if one doesn't exist. ```python app = Sanic.get_app() app1 = Sanic("app1") app2 = Sanic.get_app("app1") ``` -------------------------------- ### Finalize Sanic Middleware Configuration Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Completes the middleware setup for a Sanic application. This method is typically called internally during server setup and is used to identify routes and optimize performance. It's generally not recommended to call this method manually. ```Python app.finalize_middleware() ``` -------------------------------- ### Sanic Prepare Function Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Prepares one or more Sanic applications to be served simultaneously. This low-level API is typically used when you need to run multiple Sanic applications at the same time. Once prepared, Sanic.serve() should be called in the if __name__ == '__main__' block. ```python prepare(_host=None_, _port=None_, _*_, _dev=False_, _debug=False_, _auto_reload=None_, _version=HTTP.VERSION_1_, _ssl=None_, _sock=None_, _workers=1_, _protocol=None_, _backlog=100_, _register_sys_signals=True_, _access_log=None_, _unix=None_, _loop=None_, _reload_dir=None_, _noisy_exceptions=None_, _motd=True_, _fast=False_, _verbosity=0_, _motd_display=None_, _coffee=False_, _auto_tls=False_, _single_process=False_) """Prepares one or more Sanic applications to be served simultaneously. This low-level API is typically used when you need to run multiple Sanic applications at the same time. Once prepared, Sanic.serve() should be called in the if __name__ == “__main__” block. Note “Preparing” and “serving” with this function is equivalent to using app.run for a single instance. This should only be used when running multiple applications at the same time. Args: """ pass ``` -------------------------------- ### Register Listener for After Server Start Event in Sanic Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Decorator for registering a listener for the after_server_start event. This event is fired on all worker processes after the server has started. It's suitable for initiating background tasks or actions not directly tied to request handling, like periodic cache clearing. ```python @app.after_server_start async def on_after_server_start(app: Sanic): print("After server start") ``` -------------------------------- ### Register Listener for after_server_start Event Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Decorator for registering a listener for the after_server_start event. This event fires on all worker processes after the server has started. It's suitable for running background tasks or actions not directly tied to request handling, but not for initializing request-critical resources. ```Python @app.after_server_start async def on_after_server_start(app: Sanic): print("After server start") ``` -------------------------------- ### Sanic Listener and Logging Source: https://sanic.readthedocs.io/en/latest/genindex Covers methods for registering listeners and accessing logging utilities in Sanic. This includes setting up event listeners and utilizing the built-in logger. ```Python sanic.app.Sanic.listener() sanic.blueprints.Blueprint.listener() sanic.log.logger sanic.log.LOGGING_CONFIG_DEFAULTS ``` -------------------------------- ### Getting All Request Parameters Source: https://sanic.readthedocs.io/en/latest/sanic/api/core Retrieves all values associated with a request parameter as a list. ```Python request_parameters.getlist(name, default=None) ``` -------------------------------- ### Get Request Content Type (content_type) Source: https://sanic.readthedocs.io/en/latest/sanic/api/core Retrieves the `Content-Type` header from the incoming request. ```python request.content_type ``` -------------------------------- ### Sanic Get Form Method Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'get_form()' method for retrieving form data from a Sanic request. ```python get_form() -> Dict[str, str]: ``` -------------------------------- ### Verify Sanic Hello World Response Source: https://sanic.readthedocs.io/en/latest/index This snippet shows how to verify the 'Hello World' Sanic application is working correctly by using `curl` to make a request to the running server and inspecting the response. It expects a 200 OK status and a JSON body. ```bash curl localhost:8000 -i ``` -------------------------------- ### Sanic Get Cookie Method Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'get_cookie()' method for retrieving a cookie value from the CookieJar in Sanic. ```python get_cookie(key: str, default: Optional[str] = None) -> Optional[str]: ...(sanic.cookies.CookieJar method) ``` -------------------------------- ### Configure Sanic Server Options Source: https://sanic.readthedocs.io/en/latest/sanic/api/server This snippet details various boolean and optional parameters for configuring a Sanic server instance. It covers settings for running multiple workers, enabling asynchronous server objects, managing connections and signals, and passing keyword arguments to the asyncio create_server method. ```python run_multiple (bool, optional): Run multiple workers. Defaults to False. run_async (bool, optional): Return an AsyncServer object. Defaults to False. connections: Connections. Defaults to None. signal (Signal, optional): Signal. Defaults to Signal(). asyncio_server_kwargs (Optional[Dict[str, Union[int, float]]], optional): key-value args for asyncio/uvloop create_server method. Defaults to None. version (str, optional): HTTP version. Defaults to HTTP.VERSION_1. ``` -------------------------------- ### Sanic Application Configuration Source: https://sanic.readthedocs.io/en/latest/genindex Lists constants related to Sanic's application modes and server stages, such as 'PARTIAL' for server stages and 'PRODUCTION' for operational modes. ```Python PARTIAL (sanic.application.constants.ServerStage attribute) PRODUCTION (sanic.application.constants.Mode attribute) ``` -------------------------------- ### Get Request Endpoint Name (endpoint) Source: https://sanic.readthedocs.io/en/latest/sanic/api/core An alias for `sanic.request.Request.name`, returning the name of the route associated with the request. ```python request.endpoint ``` -------------------------------- ### Sanic Get Current Method Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'get_current()' class method for retrieving the current request instance in Sanic. ```python get_current() -> Request: ...(sanic.request.Request class method) ``` -------------------------------- ### Sanic Configuration Methods Source: https://sanic.readthedocs.io/en/latest/genindex Details methods for updating Sanic configurations. ```python sanic.config.Config.update() ``` ```python sanic.config.Config.update_config() ``` -------------------------------- ### Sanic Request Methods (Get Form) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet details the 'get_form()' method for retrieving form data from a Sanic request. ```python get_form() -> Dict[str, str] ``` -------------------------------- ### Extend Sanic Application with Extensions Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Illustrates how to extend a Sanic application instance with additional functionality using Sanic Extensions. This includes enabling built-in extensions and providing custom configurations or extensions. ```python app.extend( extensions=[MyCustomExtension], built_in_extensions=True ) ``` -------------------------------- ### Sanic Request Handling Methods Source: https://sanic.readthedocs.io/en/latest/genindex Provides an overview of methods used for handling requests within the Sanic framework. This includes methods for processing directory requests, exceptions, and general request management. ```Python sanic.handlers.DirectoryHandler.handle() sanic.app.Sanic.handle_exception() sanic.app.Sanic.handle_request() ``` -------------------------------- ### Sanic Extensions Integration Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Automatically extends the Sanic application with Sanic Extensions if installed, providing first-class support for accessing extensions. ```Python #2308 Auto extend application with Sanic Extensions if it is installed, and provide first class support for accessing the extensions ``` -------------------------------- ### Load Configuration from File Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Demonstrates how to update the Sanic application's configuration by providing the path to a Python file containing settings. Environment variables can be included in the file using the ${ENV_VAR} format, but they are treated as plain strings. ```python # /some/py/file A = 1 B = 2 ``` ```python config.update_config("${some}/py/file") ``` -------------------------------- ### Sanic Request Methods (Get Query Args) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet details the 'get_query_args()' method for retrieving query parameters from a Sanic request. ```python get_query_args() -> RequestParameters ``` -------------------------------- ### Sanic Request and Response Utilities Source: https://sanic.readthedocs.io/en/latest/genindex Highlights utility methods for requests and responses, such as creating request contexts and logging responses. It also includes methods for handling different stages of HTTP communication. ```Python sanic.request.Request.make_context() sanic.http.Http.log_response() sanic.http.Stage.HANDLER sanic.http.Stage.IDLE ``` -------------------------------- ### Sanic Request Methods (Get Current) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet includes the 'get_current()' class method for retrieving the current Sanic request instance. ```python get_current() -> Request ``` -------------------------------- ### Sanic Response Methods (File) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet covers the 'file()' method for creating a file response in Sanic. ```python file(filepath: str, filename: Optional[str] = None, mime: Optional[str] = None, download: bool = False, **kwargs) -> HTTPResponse ``` -------------------------------- ### Load Configuration from Object Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Illustrates updating the Sanic configuration using any Python object. The configuration will be loaded from the object's `__dict__` attribute, allowing settings to be defined as class attributes. ```python class C: A = 1 B = 2 config.update_config(C) ``` -------------------------------- ### Get Sanic Server Stage Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Retrieves the current stage of the Sanic server. This property, available through `ApplicationState`, returns a `ServerStage` enum value. ```Python property _stage _: ServerStage_ """Get the server stage.""" pass ``` -------------------------------- ### Sanic Application Management Methods Source: https://sanic.readthedocs.io/en/latest/genindex This snippet details methods for managing a Sanic application, including refreshing, registering listeners and middleware, and handling process reloads. ```Python from sanic import Sanic # Example usage (conceptual): # app = Sanic(__name__) # app.refresh() # app.register_listener(my_listener, 'before_server_start') # app.register_middleware(my_middleware, 'request') # app.reload_process_start() # app.reload_process_stop() ``` -------------------------------- ### Getting Single Request Parameter Source: https://sanic.readthedocs.io/en/latest/sanic/api/core Retrieves the first value of a request parameter. Returns the default value if the parameter is not found. ```Python request_parameters.get(name, default=None) ``` -------------------------------- ### Sanic Request Methods (Get Task) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet includes the 'get_task()' method for retrieving the current asyncio task associated with a Sanic request. ```python get_task() -> asyncio.Task ``` -------------------------------- ### Sanic View and Renderer Management Source: https://sanic.readthedocs.io/en/latest/genindex Covers classes and methods for creating views and rendering responses in Sanic. This includes HTTPMethodView for class-based views and various renderers for different content types. ```Python sanic.views.HTTPMethodView sanic.errorpages.BaseRenderer.minimal() sanic.errorpages.HTMLRenderer.minimal() sanic.errorpages.JSONRenderer.minimal() sanic.errorpages.TextRenderer.minimal() sanic.errorpages.HTMLRenderer sanic.errorpages.JSONRenderer sanic.errorpages.TextRenderer ``` -------------------------------- ### Sanic Request Methods (Get Motd Data) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet includes the 'get_motd_data()' method for retrieving the 'Message of the Day' data from a Sanic application. ```python get_motd_data() -> Optional[Dict[str, Any]] ``` -------------------------------- ### Sanic Exception and Compatibility Patches Source: https://sanic.readthedocs.io/en/latest/genindex Lists exceptions and compatibility patches for different Python implementations. This includes 'PayloadTooLarge' exception and patches for PyPy. ```Python PayloadTooLarge pypy_os_module_patch() (in module sanic.compat) pypy_windows_set_console_cp_patch() (in module sanic.compat) ``` -------------------------------- ### Blueprint Route with Parameter Source: https://sanic.readthedocs.io/en/latest/sanic/api/blueprints Illustrates a Sanic Blueprint route that accepts a URL parameter and returns its value. ```Python @bp2.route("/") async def bp2_route(request, param): return text(param) ``` -------------------------------- ### Sanic ApplicationServerInfo Class Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Represents information about a server instance within the Sanic application. It stores settings, the current server stage, and the server object itself. ```Python class ApplicationServerInfo(_settings_ , _stage =ServerStage.STOPPED_, _server =None_): """Information about a server instance.""" pass ``` -------------------------------- ### Sanic Cookie Management Source: https://sanic.readthedocs.io/en/latest/genindex This snippet details methods for managing cookies within Sanic, including getting and setting cookies. It covers 'get_cookie()' and 'set_cookie()'. ```python get_cookie(key: str, default: Optional[str] = None) -> Optional[str] set_cookie(key: str, value: str, domain: Optional[str] = None, expires: Optional[datetime] = None, path: str = '/', httponly: bool = False, secure: bool = False, samesite: Optional[str] = None): ... ``` -------------------------------- ### Accessing Example Field in Request Headers Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Demonstrates how to access and compare a custom field within the request headers. This is useful for custom request processing or validation. ```Python request.headers.example_field == "Foo, Bar,Baz" ``` -------------------------------- ### Sanic Test Client Source: https://sanic.readthedocs.io/en/latest/sanic/api/app Offers a testing client utilizing httpx and a live server to interact with the Sanic application. This requires the 'sanic-testing' package and enables testing handlers via a live server connection. ```python app.test_client ``` -------------------------------- ### Sanic Sentinel Identity for Spawn Compatibility Source: https://sanic.readthedocs.io/en/latest/sanic/changelog Avoids using sentinel identity for `spawn` compatibility, improving the reliability of multiprocessing when using the 'spawn' start method. ```Python from multiprocessing import get_context # The fix relates to how Sanic manages processes, particularly with the 'spawn' # start method. It ensures that process identities are handled correctly # without relying on potentially problematic sentinel values. # Example of setting the start method (if needed): # ctx = get_context('spawn') # Sanic's internal logic would then use this context appropriately. print("Sanic process management updated for spawn compatibility.") ``` -------------------------------- ### Sanic Request Methods (Get Address) Source: https://sanic.readthedocs.io/en/latest/genindex This snippet includes the 'get_address()' static method for retrieving the server's address information within a Sanic application. ```python get_address() -> Tuple[str, int] ```