### Create a basic 'Hello World' app with socketify.py Source: https://docs.socketify.dev/getting-started This example shows how to create a simple 'Hello World' web application using socketify.py. It defines a GET route for the root path and starts a server on port 3000. No external dependencies are required beyond the socketify library. ```python from socketify import App def make_app(app: App): app.get("/", lambda res, req: res.end("Hello World socketify from Python!")) if __name__ == "__main__": app = App() make_app(app) app.listen(3000, lambda config: print("Listening on port http://localhost:%d now\n" % config.port)) app.run() ``` -------------------------------- ### Socketify CLI Example: Running an App Source: https://docs.socketify.dev/cli This example demonstrates how to run a Socketify.py application using the CLI. It specifies the application module and the 'run' function, along with custom port and worker count configurations. ```bash python3 -m socketify main:app -w 8 -p 8181 ``` -------------------------------- ### Create a 'Hello World' app with SSL using socketify.py Source: https://docs.socketify.dev/getting-started This example demonstrates how to create a 'Hello World' application with SSL enabled using socketify.py. It requires SSL certificate and key files (key.pem, cert.pem) and an optional passphrase. The server listens on port 3000. ```python from socketify import App, AppOptions def make_app(app): app.get("/", lambda res, req: res.end("Hello World socketify from Python!")) if __name__ == "__main__": app = App(AppOptions(key_file_name="./misc/key.pem", cert_file_name="./misc/cert.pem", passphrase="1234")) app.listen(3000, lambda config: print("Listening on port http://localhost:%d now\n" % config.port)) app.run() ``` -------------------------------- ### Implement WebSockets with socketify.py Source: https://docs.socketify.dev/getting-started This example shows how to implement WebSocket functionality using socketify.py. It includes configurations for compression, maximum payload length, and idle timeout. It defines handlers for WebSocket open, message, drain, and close events, and a fallback route for HTTP requests. ```python from socketify import App, AppOptions, OpCode, CompressOptions def ws_open(ws): print('A WebSocket got connected!') ws.send("Hello World!", OpCode.TEXT) def ws_message(ws, message, opcode): #Ok is false if backpressure was built up, wait for drain ok = ws.send(message, opcode) def make_app(app): app.ws("/*", { 'compression': CompressOptions.SHARED_COMPRESSOR, 'max_payload_length': 16 * 1024 * 1024, 'idle_timeout': 12, 'open': ws_open, 'message': ws_message, 'drain': lambda ws: print('WebSocket backpressure: %i' % ws.get_buffered_amount()), 'close': lambda ws, code, message: print('WebSocket closed') }) app.any("/", lambda res,req: res.end("Nothing to see here!'")) if __name__ == "__main__": app = App() make_app(app) app.listen(3000, lambda config: print("Listening on port http://localhost:%d now\n" % (config.port))) app.run() ``` -------------------------------- ### Using the `send` Method Source: https://docs.socketify.dev/basics A comprehensive guide on using the `res.send` method for simplified response handling. ```APIDOC ## Using the `send` Method ### Description The `res.send()` method provides a convenient way to send responses, handling status, content type, and body in a single call. ### Method - **`res.send(message, content_type=b'text/plain', status=b'200 OK', headers=None, end_connection=False)`** - **Description**: Combines status writing, header writing, and response ending into one easy-to-use method. If `message` is an object, it will attempt to be JSON-encoded. - **Parameters**: - **message** (str, bytes, dict, etc.) - Required - The response body content. - **content_type** (bytes) - Optional - The `Content-Type` header value. Defaults to `b'text/plain'`. - **status** (int or bytes) - Optional - The HTTP status code. Defaults to `b'200 OK'`. - **headers** (iterator of iterators/tuples) - Optional - Additional headers to send, in the format `iter(tuple(str, str))`. - **end_connection** (bool) - Optional - Whether to close the connection after sending. Defaults to `False`. - **Method**: `send` ### Examples: **Simple Text Response:** ```python def not_found(res, req): res.send("Not Found", status=404) ``` **OK Response:** ```python def ok(res, req): res.send("OK", status="200 OK") ``` **JSON Response:** ```python def json(res, req): res.send({"Hello": "World!"}) ``` **Response with Custom Headers:** ```python def with_headers(res, req): res.send({"Hello": "World!"}, headers=(("X-Rate-Limit-Remaining", "10"), (b'Another-Headers', b'Value'))) ``` ``` -------------------------------- ### Use Mako Template Extension with socketify.py Source: https://docs.socketify.dev/templates This example demonstrates how to register and use the Mako template extension with socketify.py. It involves creating an `App` instance, registering `MakoTemplate`, defining a route that uses `res.render`, and starting the server. ```python from socketify import App # see helper/templates.py for plugin implementation from helpers.templates import MakoTemplate app = App() # register templates app.template( MakoTemplate( directories=["./templates"], output_encoding="utf-8", encoding_errors="replace" ) ) def home(res, req): res.render("mako_home.html", message="Hello, World") app.get("/", home) app.listen( 3000, lambda config: print( "Listening on port http://localhost:%s now\n" % str(config.port) ), ) app.run() ``` -------------------------------- ### Socketify Hello World + WebSockets Source: https://docs.socketify.dev/cli This Python snippet is a starting point for a Socketify.py application that includes both basic HTTP handling and WebSocket functionality. It imports necessary classes from the socketify library. ```python from socketify import App, OpCode ``` -------------------------------- ### Socketify CLI with WebSocket Configuration Source: https://docs.socketify.dev/cli This example shows how to run a Socketify.py application that includes WebSocket support using the CLI. It specifies the main application, the WebSocket handler module, and configures the port and worker count. ```bash python3 -m socketify hello_world_cli:run --ws hello_world_cli:ws --port 8080 --workers 2 ``` -------------------------------- ### WebSockets with Socketify CLI Source: https://docs.socketify.dev/cli This section covers how to configure and serve WebSockets using the socketify.py CLI, including examples for integrating WebSocket handlers. ```APIDOC ## WebSockets with Socketify CLI ### Description WebSockets can be served alongside HTTP routes or in a separate module. The CLI provides options to configure WebSocket behavior and integrate WebSocket handlers. ### Serving WebSockets WebSockets can be configured using the `--ws` option. You can specify a module to load WebSocket handlers from. ### Example: Hello World with WebSockets ```bash python3 -m socketify hello_world_cli:run --ws hello_world_cli:ws --port 8080 --workers 2 ``` ### WebSocket Handler Example ```python from socketify import App, OpCode # In hello_world_cli.py def run(app: App): # HTTP routes can be added here app.get("/", lambda res, req: res.end("Hello World!")) def ws(app: App): # WebSocket routes app.ws("/", { "open": lambda ws, req: print("WebSocket opened!"), "message": lambda ws, message, isBinary: print(f"Received message: {message}"), "close": lambda ws, code, reason: print(f"WebSocket closed with code: {code}") }) ``` ``` -------------------------------- ### Configure GraphiQL with Strawberry and Socketify.py Source: https://docs.socketify.dev/graphiql This example demonstrates how to configure a Socketify.py application to serve a GraphiQL interface and handle GraphQL POST requests using a helper function. It requires the 'strawberry' and 'socketify' libraries. ```python import dataclasses import strawberry import strawberry.utils.graphiql from socketify import App from typing import List, Optional from helpers.graphiql import graphiql_from @strawberry.type class User: name: str @strawberry.type class Query: @strawberry.field def user(self) -> Optional[User]: # self.context is the AppRequest return User(name="Hello") app = App() app.get("/", lambda res, req: res.end(strawberry.utils.graphiql.get_graphiql_html())) app.post("/", graphiql_from(Query)) # you can also pass an Mutation as second parameter # app.post("/", graphiql_from(Query, Mutation)) app.listen( 3000, lambda config: print("Listening on port http://localhost:%d now\n" % config.port), ) app.run() ``` -------------------------------- ### socketify.py CLI Usage Source: https://docs.socketify.dev/cli This section details how to use the socketify.py command-line tool to run applications. It covers the basic usage, available options, and provides an example. ```APIDOC ## socketify.py CLI Tool ### Description The socketify.py CLI tool is used to run ASGI, WSGI, or socketify.py applications. It provides various options for configuring the server. ### Usage ```bash python3 -m socketify APP [OPTIONS] ``` ### Options - **--help** or **-h**: Show this help message. - **--host** or **-h** TEXT: Bind socket to this host. [default: 127.0.0.1] - **--port** or **-p** INTEGER: Bind socket to this port. [default: 8000] - **--workers** or **-w** INTEGER: Number of worker processes. Defaults to the WEB_CONCURRENCY environment variable if available, or 1. - **--uds** TEXT: Bind to a UNIX domain socket. This option disables `--host` and `--port`. - **--ws** [auto|none|module:ws]: WebSocket configuration. If `module:ws` is informed, it will auto-detect to use socketify.py or ASGI websockets interface and disabled if informed `none`. [default: auto] - **--ws-max-size** INTEGER: WebSocket max size message in bytes. [default: 16777216] - **--ws-auto-ping** BOOLEAN: WebSocket auto ping sending. [default: True] - **--ws-idle-timeout** INT: WebSocket idle timeout. [default: 20] - **--ws-reset-idle-on-send** BOOLEAN: Reset WebSocket idle timeout on send. [default: True] - **--ws-per-message-deflate** BOOLEAN: WebSocket per-message-deflate compression. [default: False] - **--ws-max-lifetime** INT: Websocket maximum socket lifetime in seconds before forced closure, 0 to disable. [default: 0] - **--ws-max-backpressure** INT: WebSocket maximum backpressure in bytes. [default: 16777216] - **--ws-close-on-backpressure-limit** BOOLEAN: Close connections that hit maximum backpressure. [default: False] - **--lifespan** [auto|on|off]: Lifespan implementation. [default: auto] - **--interface** [auto|asgi|asgi3|wsgi|ssgi|socketify]: Select ASGI (same as ASGI3), ASGI3, WSGI, or SSGI as the application interface. [default: auto] - **--disable-listen-log** BOOLEAN: Disable log when start listening. [default: False] - **--version** or **-v**: Display the socketify.py version and exit. - **--ssl-keyfile** TEXT: SSL key file. - **--ssl-certfile** TEXT: SSL certificate file. - **--ssl-keyfile-password** TEXT: SSL keyfile password. - **--ssl-ca-certs** TEXT: CA certificates file. - **--ssl-ciphers** TEXT: Ciphers to use (see stdlib ssl module's). [default: TLSv1] - **--req-res-factory-maxitems** INT: Pre-allocated instances of Response and Request objects for socketify interface. [default: 0] - **--ws-factory-maxitems** INT: Pre-allocated instances of WebSockets objects for socketify interface. [default: 0] - **--task-factory-maxitems** INT: Pre-allocated instances of Task objects for socketify, ASGI interface. [default: 100000] ### Example ```bash python3 -m socketify main:app -w 8 -p 8181 ``` ``` -------------------------------- ### Handle Application Lifespan Events in Socketify Source: https://docs.socketify.dev/basics Shows how to use `app.on_start` and `app.on_shutdown` to execute code when the application starts or shuts down. These handlers can be synchronous or asynchronous and are useful for managing resources like connection pools. ```python from socketify import App import asyncio def run(app: App): @app.on_start async def on_start(): print("wait...") await asyncio.sleep(1) print("start!") @app.on_shutdown async def on_shutdown(): print("wait...") await asyncio.sleep(1) print("shutdown!") router = app.router() @router.get("/") def home(res, req): res.send("Hello, World!") ``` -------------------------------- ### Configure SSL/HTTPS in Socketify.py Source: https://docs.socketify.dev/ssl This code demonstrates how to initialize Socketify.py with SSL/HTTPS enabled. It requires specifying the paths to the key and certificate files, and optionally a passphrase. The application then sets up a basic route and starts listening on a specified port. ```python from socketify import App, AppOptions app = App( AppOptions( key_file_name="./misc/key.pem", cert_file_name="./misc/cert.pem", passphrase="1234", ) ) app.get("/", lambda res, req: res.end("Hello World socketify from Python!")) app.listen( 3000, lambda config: print("Listening on port https://localhost:%d now\n" % config.port), ) app.run() ``` -------------------------------- ### Basic Route Definition Source: https://docs.socketify.dev/routes Defines a simple GET route for the root path that responds with 'Hello World!'. Supports both lambda functions and regular function definitions. ```APIDOC ## GET / ### Description Handles GET requests to the root URL and sends a 'Hello World!' response. ### Method GET ### Endpoint / ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **response**: string - 'Hello World!' #### Response Example ``` Hello World! ``` ``` -------------------------------- ### Accessing Request Parameters in Python Source: https://docs.socketify.dev/basics Explains how to retrieve parameters from the request URL. `req.get_parameter(index)` fetches a specific parameter by its position, while `req.get_parameters()` returns a list of all parameters. An example demonstrates routing with a dynamic parameter '/user/:id'. ```python def user(res, req): if int(req.get_parameter(0)) == 1: return res.end("Hello user with id 1!") params = req.get_parameters() print('All params', params) app.get("/user/:id", user) ``` -------------------------------- ### Dynamically Handle Content Types (Python) Source: https://docs.socketify.dev/upload-post This example demonstrates how to dynamically handle different content types based on the `Content-Type` header. It checks the header and uses the appropriate method (`get_json`, `get_form_urlencoded`, or `get_text`) to parse the incoming data. This provides flexibility in accepting various data formats. ```python async def upload_multiple(res, req): print(f"Posted to {req.get_url()}") content_type = req.get_header("content-type") # we can check the Content-Type to accept multiple formats if content_type == "application/json": data = await res.get_json() elif content_type == "application/x-www-form-urlencoded": data = await res.get_form_urlencoded() else: data = await res.get_text() print(f"Your data is ${data}") # We respond when we are done res.cork_end("Thanks for the data!") ``` -------------------------------- ### Define HTTP GET Route Source: https://docs.socketify.dev/routes Defines a route that responds to HTTP GET requests. It pairs a URL pattern with a callback function. The callback receives response (res) and request (req) objects to handle the request and send a response. This example shows a simple "Hello World!" response. ```python app.get("/", lambda res, req: res.end("Hello World!")) ``` ```python def home(res, req): res.end("Hello World!") app.get("/", home) ``` -------------------------------- ### Socketify CLI Help and Usage Source: https://docs.socketify.dev/cli This snippet shows the basic command to view the help message for the socketify CLI and outlines the general usage pattern for running an application. It details the 'APP' argument and various command-line options for configuring the server environment. ```bash python3 -m socketify --help ``` ```bash Usage: python -m socketify APP [OPTIONS] python3 -m socketify APP [OPTIONS] pypy3 -m socketify APP [OPTIONS] Options: --help Show this Help --host or -h TEXT Bind socket to this host. [default:127.0.0.1] --port or -p INTEGER Bind socket to this port. [default: 8000] --workers or -w INTEGER Number of worker processes. Defaults to the WEB_CONCURRENCY environment variable if available, or 1 --uds TEXT Bind to a UNIX domain socket, this options disables --host or -h and --port or -p. --ws [auto|none|module:ws] If informed module:ws will auto detect to use socketify.py or ASGI websockets interface and disabled if informed none [default: auto] --ws-max-size INTEGER WebSocket max size message in bytes [default: 16777216] --ws-auto-ping BOOLEAN WebSocket auto ping sending [default: True] --ws-idle-timeout INT WebSocket idle timeout [default: 20] --ws-reset-idle-on-send BOOLEAN Reset WebSocket idle timeout on send [default: True] --ws-per-message-deflate BOOLEAN WebSocket per-message-deflate compression [default: False] --ws-max-lifetime INT Websocket maximum socket lifetime in seconds before forced closure, 0 to disable [default: 0] --ws-max-backpressure INT WebSocket maximum backpressure in bytes [default: 16777216] --ws-close-on-backpressure-limit BOOLEAN Close connections that hits maximum backpressure [default: False] --lifespan [auto|on|off] Lifespan implementation. [default: auto] --interface [auto|asgi|asgi3|wsgi|ssgi|socketify] Select ASGI (same as ASGI3), ASGI3, WSGI or SSGI as the application interface. [default: auto] --disable-listen-log BOOLEAN Disable log when start listening [default: False] --version or -v Display the socketify.py version and exit. --ssl-keyfile TEXT SSL key file --ssl-certfile TEXT SSL certificate file --ssl-keyfile-password TEXT SSL keyfile password --ssl-ca-certs TEXT CA certificates file --ssl-ciphers TEXT Ciphers to use (see stdlib ssl module's) [default: TLSv1] --req-res-factory-maxitems INT Pre allocated instances of Response and Request objects for socketify interface [default: 0] --ws-factory-maxitems INT Pre allocated instances of WebSockets objects for socketify interface [default: 0] --task-factory-maxitems INT Pre allocated instances of Task objects for socketify, ASGI interface [default: 100000] ``` -------------------------------- ### Get Uploaded Data as JSON (Python) Source: https://docs.socketify.dev/upload-post This example demonstrates retrieving uploaded data and parsing it directly as JSON using `res.get_json()`. This method is convenient when the client sends JSON data. It returns a Python dictionary representing the JSON object or `None` if parsing fails. ```python async def upload_json(res, req): print(f"Posted to {req.get_url()}") # await all the data and parses as json, returns None if fail info = await res.get_json() print(info) # We respond when we are done res.cork_end("Thanks for the data!") ``` -------------------------------- ### Get All Uploaded Data at Once (Python) Source: https://docs.socketify.dev/upload-post This example shows how to retrieve all uploaded data in a single call using `res.get_data()`. Socketify.py internally manages a `BytesIO` object to accumulate the data. This method is suitable for moderately sized uploads where memory is not a primary concern. It returns the accumulated data upon completion. ```python async def upload_chunks(res, req): print(f"Posted to {req.get_url()}") # await all the data, returns received chunks if fail (most likely fail is aborted requests) data = await res.get_data() print(f"Got {len(data.getvalue())} bytes of data!") # We respond when we are done res.cork_end("Thanks for the data!") ``` -------------------------------- ### Pattern Matching and Wildcards Source: https://docs.socketify.dev/routes Explains route matching order and demonstrates using parameter routes and wildcard routes. ```APIDOC ## Route Pattern Matching ### Description Details the priority of route matching, from static routes to parameter routes and wildcard routes. Also shows how to skip to the next route. ### Method GET, ANY ### Endpoint - `/user/:user_id` (parameter route) - `/*` (wildcard route) ### Parameters #### Path Parameters - **user_id** (integer) - The ID of the user to retrieve. ### Request Body None ### Request Example None ### Response #### Success Response (200) - **response**: string - "Hello user 1!" or "Not Found". #### Response Example - For `/user/1`: `Hello user 1!` - For any other route not matching `/user/:user_id`: `Not Found` **Note**: `req.get_parameter(0)` retrieves the value for the first defined parameter (e.g., `:user_id`). `req.set_yield(1)` is used to pass control to the next route if the current one doesn't fully handle the request. ``` -------------------------------- ### Run Socketify with ASGI and Custom WebSocket Handler Source: https://docs.socketify.dev/cli This command illustrates how to run an application using Socketify, specifying both the ASGI application and a custom WebSocket handler. It's useful for mixing different functionalities within the same server instance. ```bash python3 -m socketify main:app --ws main:ws --port 8080 --workers 2 ``` -------------------------------- ### Get Uploaded Data as Text (Python) Source: https://docs.socketify.dev/upload-post This snippet illustrates how to get uploaded data decoded as text using `res.get_text()`. It allows specifying the encoding, defaulting to UTF-8. This method is useful when the incoming data is expected to be plain text. It returns the decoded string or `None` if decoding fails. ```python async def upload_text(res, req): print(f"Posted to {req.get_url()}") # await all the data and decode as text, returns None if fail text = await res.get_text() # first parameter is the encoding (default utf-8) print(f"Your text is ${text}") # We respond when we are done res.cork_end("Thanks for the data!") ``` -------------------------------- ### Get Uploaded Data as Form URL Encoded (Python) Source: https://docs.socketify.dev/upload-post This snippet shows how to get uploaded data and decode it as `application/x-www-form-urlencoded` using `res.get_form_urlencoded()`. It allows specifying the encoding, defaulting to UTF-8. This is useful for processing data submitted from HTML forms. It returns a dictionary of form key-value pairs or `None` if decoding fails. ```python async def upload_urlencoded(res, req): print(f"Posted to {req.get_url()}") # await all the data and decode as application/x-www-form-urlencoded, returns None if fails form = await res.get_form_urlencoded()# first parameter is the encoding (default utf-8) print(f"Your form is ${form}") # We respond when we are done res.cork_end("Thanks for the data!") ``` -------------------------------- ### Handling URL Parameters Source: https://docs.socketify.dev/basics Demonstrates how to extract path parameters from the request URL. ```APIDOC ## Handling URL Parameters ### Description This section covers how to retrieve parameters that are part of the URL path, often used for identifying resources. ### Methods - **`req.get_parameter(index)`** - **Description**: Retrieves a specific URL parameter by its index. Parameters are typically extracted from routes defined with placeholders (e.g., `/user/:id`). - **Parameters**: - **index** (int) - Required - The zero-based index of the parameter to retrieve. - **Return Value**: String - The value of the requested parameter. - **`req.get_parameters()`** - **Description**: Retrieves all URL parameters as a list. - **Return Value**: List of Strings - A list containing all extracted URL parameters. ### Example: ```python # Assuming app.get("/user/:id", user) is defined def user(res, req): if int(req.get_parameter(0)) == 1: return res.end("Hello user with id 1!") params = req.get_parameters() print('All params', params) ``` ``` -------------------------------- ### AppListenOptions Class Source: https://docs.socketify.dev/api Defines options for the `listen` method of the App class. ```APIDOC ## AppListenOptions Class ### Description Represents the configuration options for listening to incoming connections. ### Properties - **`port`** (int) - The port number to listen on. Defaults to 0. - **`host`** (str) - The host address to bind to. Defaults to None. - **`options`** (int) - Additional options for listening. Defaults to 0. - **`domain`** (str) - The domain name for virtual hosting. Defaults to None. ``` -------------------------------- ### Redirecting Requests Source: https://docs.socketify.dev/basics Illustrates how to perform an HTTP redirect to a different URL. ```APIDOC ## Redirecting Requests ### Description This section covers how to send an HTTP redirect response to the client. ### Method - **`res.redirect(url, status_code=302)`** - **Description**: Sends a redirect response to the specified URL. The `status_code` is optional and defaults to `302` (Found). - **Parameters**: - **url** (str) - Required - The URL to redirect to. - **status_code** (int) - Optional - The HTTP status code for the redirect (e.g., 301, 302, 307, 308). - **Method**: `redirect` ### Example: ```python def redirect(res, req): # status code is optional default is 302 res.redirect("/redirected", 302) ``` ``` -------------------------------- ### Accessing Request URL and Method Source: https://docs.socketify.dev/basics Learn how to retrieve the full URL, path, and HTTP method from an incoming request. ```APIDOC ## Accessing Request URL and Method ### Description This section explains how to access details about the incoming request, including its full URL, the path, and the HTTP method. ### Methods - **`req.get_full_url()`** - **Description**: Returns the full URL of the request, including the path and query string. - **Return Value**: String - **`req.get_url()`** - **Description**: Returns the path part of the request URL, excluding the query string. - **Return Value**: String - **`req.get_method()`** - **Description**: Returns the HTTP method used for the request (e.g., 'GET', 'POST'). The method is case-sensitive. - **Return Value**: String ``` -------------------------------- ### AppOptions Class Source: https://docs.socketify.dev/api Defines SSL/TLS options for the App class. ```APIDOC ## AppOptions Class ### Description Represents the configuration options for SSL/TLS settings. ### Properties - **`key_file_name`** (str) - Path to the private key file. Defaults to None. - **`cert_file_name`** (str) - Path to the certificate file. Defaults to None. - **`passphrase`** (str) - Passphrase for the private key. Defaults to None. - **`dh_params_file_name`** (str) - Path to the Diffie-Hellman parameters file. Defaults to None. - **`ca_file_name`** (str) - Path to the Certificate Authority file. Defaults to None. - **`ssl_ciphers`** (str) - String specifying allowed SSL ciphers. Defaults to None. - **`ssl_prefer_low_memory_usage`** (int) - Option to prefer low memory usage for SSL. Defaults to 0. ``` -------------------------------- ### Set and Get Cookies in Socketify Source: https://docs.socketify.dev/basics Demonstrates how to set and retrieve cookies using `res.set_cookie` and `req.get_cookie`. It includes options for cookie expiration, path, security, and HttpOnly attributes. The cookie is set after the response ends. ```python from socketify import App from datetime import datetime, timedelta def cookies(res, req): # cookies are written after end res.set_cookie( "session_id", "1234567890", { # expires # path # comment # domain # max-age # secure # version # httponly # samesite "path": "/", # "domain": "*.test.com", "httponly": True, "samesite": "None", "secure": True, "expires": datetime.utcnow() + timedelta(minutes=30), }, ) res.end("Your session_id cookie is: %s" % req.get_cookie("session_id")) ``` -------------------------------- ### Writing HTTP Status Source: https://docs.socketify.dev/basics Explains how to manually set the HTTP status code for a response. ```APIDOC ## Writing HTTP Status ### Description This section details how to explicitly set the HTTP status line for a response before sending its body. ### Methods - **`res.write_status(status_code)`** - **Description**: Sets the HTTP status code for the response. Can be an integer (e.g., 404) or a string (e.g., '200 OK'). This method returns the response object itself to allow chaining with other methods like `end()`. - **Parameters**: - **status_code** (int or str) - Required - The HTTP status code. - **Method**: `write_status` - **`res.end(message)`** - **Description**: Sends the response body and terminates the connection. Often chained after `write_status`. - **Method**: `end` ### Examples: **Not Found:** ```python def not_found(res, req): res.write_status(404).end("Not Found") ``` **OK Status:** ```python def ok(res, req): res.write_status("200 OK").end("OK") ``` ``` -------------------------------- ### Socketify Application Structure Source: https://docs.socketify.dev/cli This section explains the required structure for a socketify.py application, specifically the `run` function that the CLI will use to create and configure the application instance. ```APIDOC ## Socketify Application Structure ### Description Socketify applications require a `run` function that the CLI will use to create and configure the application instance. This function receives an `App` object to which routes and other configurations can be added. ### `run` Function Signature ```python from socketify import App def run(app: App): # Add your routes here app.get("/", lambda res, req: res.end("Hello World!")) ``` ### Example Usage with CLI ```bash python3 -m socketify main:app ``` In this example, `main` is the Python module, and `app` is the `App` instance created within the `run` function. ``` -------------------------------- ### Get Remote and Proxied IP Addresses in Socketify Source: https://docs.socketify.dev/basics Shows how to retrieve the client's IP address using `res.get_remote_address` and the proxied IP address using `res.get_proxied_remote_address`. It also mentions `_bytes` versions for raw byte retrieval. ```python def home(res, req): res.write("