### Basic DispatcherMiddleware Setup Source: https://werkzeug.palletsprojects.com/en/stable/middleware/dispatcher Example of setting up DispatcherMiddleware to route requests to different WSGI applications based on URL paths. The first argument is the default application for unmatched paths. ```python app = DispatcherMiddleware(serve_frontend, { '/api': api_app, '/admin': admin_app, }) ``` -------------------------------- ### Start mod_wsgi-express with External Binding and User Dropping Source: https://werkzeug.palletsprojects.com/en/stable/deployment/mod_wsgi Example of starting mod_wsgi-express with root privileges to bind to port 80, specifying user and group for worker processes to drop permissions to. ```bash $ sudo /home/hello/venv/bin/mod_wsgi-express start-server \ /home/hello/wsgi.py \ --user hello --group hello --port 80 --processes 4 ``` -------------------------------- ### Install mod_wsgi in a Virtual Environment Source: https://werkzeug.palletsprojects.com/en/stable/deployment/mod_wsgi Steps to create a virtual environment, install your application, and then install the mod_wsgi package. ```bash $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install mod_wsgi ``` -------------------------------- ### Install uwsgi with SSL support Source: https://werkzeug.palletsprojects.com/en/stable/deployment/uwsgi Install the uwsgi package or pyuwsgi from source to include SSL support. This requires a compiler. ```bash $ pip install uwsgi # or $ pip install --no-binary pyuwsgi pyuwsgi ``` -------------------------------- ### Install gevent and Application Source: https://werkzeug.palletsprojects.com/en/stable/deployment/gevent Install gevent and your application within a virtual environment. Ensure greenlet>=1.0 is installed for proper context local functionality. ```bash cd hello-app python -m venv venv . venv/bin/activate pip install . # install your application pip install gevent ``` -------------------------------- ### Install Redis on Ubuntu/Debian Source: https://werkzeug.palletsprojects.com/en/stable/tutorial Use apt-get to install the redis-server package on Ubuntu or Debian. ```bash sudo apt-get install redis-server ``` -------------------------------- ### Install eventlet Source: https://werkzeug.palletsprojects.com/en/stable/deployment/eventlet Install eventlet and its dependencies within a virtual environment. Ensure greenlet>=1.0 is installed for proper context local support. ```bash cd hello-app python -m venv venv . venv/bin/activate pip install . # install your application pip install eventlet ``` -------------------------------- ### Install Werkzeug and Dependencies Source: https://werkzeug.palletsprojects.com/en/stable/tutorial Use pip to install Jinja2, redis, and Werkzeug for the application. ```bash pip install Jinja2 redis Werkzeug ``` -------------------------------- ### Start eventlet WSGI server Source: https://werkzeug.palletsprojects.com/en/stable/deployment/eventlet Execute the Python script to start the eventlet WSGI server. The server will output its startup information, including the address and port it is listening on. ```bash python wsgi.py (x) wsgi starting up on http://127.0.0.1:8000 ``` -------------------------------- ### MultiDict setlist() Example Source: https://werkzeug.palletsprojects.com/en/stable/datastructures Shows how to use the setlist() method to replace all values for a given key with a new list of values. ```python >>> d = MultiDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' ``` -------------------------------- ### Install Waitress Source: https://werkzeug.palletsprojects.com/en/stable/deployment/waitress Install Waitress within a virtual environment after installing your application. This is a standard setup for Python web applications. ```bash cd hello-app python -m venv venv . venv/bin/activate pip install . # install your application pip install waitress ``` -------------------------------- ### Install Gunicorn Source: https://werkzeug.palletsprojects.com/en/stable/deployment/gunicorn Install Gunicorn within a virtual environment after installing your application. This is a standard setup for Python projects. ```bash cd hello-app python -m venv venv . venv/bin/activate pip install . # install your application pip install gunicorn ``` -------------------------------- ### Start the development server command Source: https://werkzeug.palletsprojects.com/en/stable/tutorial Command to execute the Python script and start the Werkzeug development server. Shows output indicating the server is running and the reloader is active. ```bash $ python shortly.py * Running on http://127.0.0.1:5000/ * Restarting with reloader: stat() polling ``` -------------------------------- ### Run Simple Server with SSL Certificate Source: https://werkzeug.palletsprojects.com/en/stable/serving Starts the Werkzeug development server using a provided SSL certificate and key for HTTPS connections. ```python run_simple('localhost', 4000, application, ssl_context=('/path/to/the/key.crt', '/path/to/the/key.key')) ``` -------------------------------- ### Install pyuwsgi Source: https://werkzeug.palletsprojects.com/en/stable/deployment/uwsgi Install the pyuwsgi package for a straightforward installation without SSL support. This is suitable for common platforms. ```bash $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install pyuwsgi ``` -------------------------------- ### Install Redis on macOS Source: https://werkzeug.palletsprojects.com/en/stable/tutorial Use brew to install Redis on macOS. ```bash brew install redis ``` -------------------------------- ### Install Werkzeug using pip Source: https://werkzeug.palletsprojects.com/en/stable/installation Install the Werkzeug library within your activated virtual environment using pip. This command fetches and installs the latest stable version. ```bash pip install Werkzeug ``` -------------------------------- ### Run the development server Source: https://werkzeug.palletsprojects.com/en/stable/tutorial This snippet starts a local Werkzeug development server with debugging and code reloading enabled. It uses the `create_app` factory function. ```python if __name__ == '__main__': from werkzeug.serving import run_simple app = create_app() run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True) ``` -------------------------------- ### Hello World Application using Request and Response Objects Source: https://werkzeug.palletsprojects.com/en/stable/levels This example demonstrates a simple 'Hello World' application using Werkzeug's high-level Request and Response objects. It handles POST requests to greet the user by name. ```python from markupsafe import escape from werkzeug.wrappers import Request, Response @Request.application def hello_world(request): result = ['Greeter'] if request.method == 'POST': result.append(f"

Hello {escape(request.form['name'])}!

") result.append('''

Name:

''') return Response(''.join(result), mimetype='text/html') ``` -------------------------------- ### Run basic uWSGI HTTP server Source: https://werkzeug.palletsprojects.com/en/stable/deployment/uwsgi Start a basic uWSGI HTTP server, specifying the master process, number of workers, and the application to import. ```bash $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app ``` -------------------------------- ### Hello World Application using Low-Level WSGI Functions Source: https://werkzeug.palletsprojects.com/en/stable/levels This example shows how to implement the same 'Hello World' application using Werkzeug's lower-level parsing functions and standard WSGI environ/start_response arguments, bypassing the Request and Response objects. ```python from markupsafe import escape from werkzeug.formparser import parse_form_data def hello_world(environ, start_response): result = ['Greeter'] if environ['REQUEST_METHOD'] == 'POST': form = parse_form_data(environ)[1] result.append(f"

Hello {escape(form['name'])}!

") result.append('''

Name:

''') start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')]) return [''.join(result).encode('utf-8')] ``` -------------------------------- ### Submount Rule Factory Example Source: https://werkzeug.palletsprojects.com/en/stable/routing Prefixes URL rules with a given path string, useful for mounting sub-applications. ```python url_map = Map([ Rule('/', endpoint='index'), Submount('/blog', [ Rule('/', endpoint='blog/index'), Rule('/entry/', endpoint='blog/show') ]) ]) ``` -------------------------------- ### RuleTemplate Example Source: https://werkzeug.palletsprojects.com/en/stable/routing Generates rules dynamically by expanding string templates with keyword arguments. ```python from werkzeug.routing import Map, Rule, RuleTemplate resource = RuleTemplate([ Rule('/$name/', endpoint='$name.list'), Rule('/$name/', endpoint='$name.show') ]) url_map = Map([resource(name='user'), resource(name='page')]) ``` -------------------------------- ### Run Gunicorn with App Source: https://werkzeug.palletsprojects.com/en/stable/deployment/gunicorn Start Gunicorn by specifying the module and application variable. Use the -w option to set the number of worker processes. ```bash gunicorn -w 4 'hello:app' ``` ```bash gunicorn -w 4 'hello:create_app()' ``` -------------------------------- ### Start mod_wsgi-express Server Source: https://werkzeug.palletsprojects.com/en/stable/deployment/mod_wsgi Command to start the mod_wsgi-express server, specifying the WSGI script and the number of worker processes. ```bash $ mod_wsgi-express start-server wsgi.py --processes 4 ``` -------------------------------- ### Run Simple Server with Unix Socket Source: https://werkzeug.palletsprojects.com/en/stable/serving Binds the Werkzeug development server to a Unix socket instead of a TCP socket. The hostname must start with 'unix://'. ```python from werkzeug.serving import run_simple run_simple('unix://example.sock', 0, app) ``` -------------------------------- ### EndpointPrefix Rule Factory Example Source: https://werkzeug.palletsprojects.com/en/stable/routing Prefixes all endpoints with a given string, useful for organizing endpoints in sub-applications. ```python url_map = Map([ Rule('/', endpoint='index'), EndpointPrefix('blog/', [Submount('/blog', [ Rule('/', endpoint='index'), Rule('/entry/', endpoint='show') ])]) ]) ``` -------------------------------- ### Subdomain Rule Factory Example Source: https://werkzeug.palletsprojects.com/en/stable/routing Defines rules that listen on a specific subdomain, useful for language-specific routing. ```python url_map = Map([ Rule('/', endpoint='#select_language'), Subdomain('', [ Rule('/', endpoint='index'), Rule('/about', endpoint='about'), Rule('/help', endpoint='help') ]) ]) ``` -------------------------------- ### ProxyMiddleware Configuration Source: https://werkzeug.palletsprojects.com/en/stable/middleware/http_proxy Demonstrates how to use ProxyMiddleware to proxy requests starting with a specific path prefix to a target URL. It shows how to configure target options like removing the prefix and setting custom headers. ```APIDOC ## ProxyMiddleware ### Description Proxies requests under a path to an external server, routing other requests to the app. This middleware can only proxy HTTP requests. ### Class Signature `werkzeug.middleware.http_proxy.ProxyMiddleware(_app_, _targets_, _chunk_size=2<<13_, _timeout=10_) ### Parameters * **app** (_WSGIApplication_) – The WSGI application to wrap. * **targets** (_t.Mapping[str, dict[str, t.Any]]_) – Proxy target configurations. A dictionary mapping a path prefix to a dictionary describing the host to be proxied to. * **chunk_size** (_int_) – Size of chunks to read from input stream and write to target. * **timeout** (_int_) – Seconds before an operation to a target fails. ### Target Options Each target configuration can include the following options: * **target** (_str_) – The target URL to dispatch to. This is required. * **remove_prefix** (_bool_) – Whether to remove the prefix from the URL before dispatching it to the target. Defaults to `False`. * **host** (_str_ | None) – Controls the Host header sent to the target. Defaults to "" (rewrites to target URL). `None` leaves it unmodified. Any other string overwrites it. * **headers** (_dict[str, str]_) – A dictionary of headers to be sent with the request to the target. Defaults to `{}`. * **ssl_context** (_ssl.SSLContext_ | None) – Defines how to verify requests if the target is HTTPS. Defaults to `None`. ### Example Usage ```python app = ProxyMiddleware(app, { "/static/": { "target": "http://127.0.0.1:5001/", "remove_prefix": True, "headers": {"X-Proxy-Header": "value"} } }) ``` ``` -------------------------------- ### Werkzeug Logger Setup Source: https://werkzeug.palletsprojects.com/en/stable/utils Configure and use the Werkzeug logger, which is named 'werkzeug'. The default level is INFO, and a StreamHandler is added if none exists. ```python import logging logger = logging.getLogger("werkzeug") ``` -------------------------------- ### Parse Multipart Form Data Example Source: https://werkzeug.palletsprojects.com/en/stable/http Demonstrates parsing multipart form data from a WSGI environment. This is useful for testing by creating a fake WSGI environment. ```python >>> from io import BytesIO >>> from werkzeug.formparser import parse_form_data >>> data = ( ... b'--foo\r\nContent-Disposition: form-data; name="test"\r\n' ... b"\r\nHello World!\r\n--foo--" ... ) >>> environ = { ... "wsgi.input": BytesIO(data), ... "CONTENT_LENGTH": str(len(data)), ... "CONTENT_TYPE": "multipart/form-data; boundary=foo", ... "REQUEST_METHOD": "POST", ... } >>> stream, form, files = parse_form_data(environ) >>> stream.read() b'' >>> form['test'] 'Hello World!' >>> not files True ``` -------------------------------- ### Retrieving Quality from Accept Object Source: https://werkzeug.palletsprojects.com/en/stable/datastructures Shows how to get the quality value associated with a specific item in an Accept object using dictionary-like item lookup. ```python >>> print a['utf-8'] 0.7 >>> a['utf7'] 0 ``` -------------------------------- ### Run WSGI Application with Werkzeug Development Server Source: https://werkzeug.palletsprojects.com/en/stable/serving This snippet shows the basic usage of `run_simple` to start a development server for a WSGI application. It enables the reloader to automatically restart the server when files change. ```python from werkzeug.serving import run_simple from myproject import make_app app = make_app(...) run_simple('localhost', 8080, app, use_reloader=True) ``` -------------------------------- ### Run Simple Test Application with Werkzeug Source: https://werkzeug.palletsprojects.com/en/stable/wsgi The `test_app` function provides a simple WSGI application that dumps environment information. It's useful for verifying Werkzeug installation and basic server functionality. Run it using `run_simple`. ```python from werkzeug.serving import run_simple from werkzeug.testapp import test_app run_simple('localhost', 3000, test_app) ``` -------------------------------- ### Basic ProxyMiddleware Configuration Source: https://werkzeug.palletsprojects.com/en/stable/middleware/http_proxy Configure ProxyMiddleware to route requests starting with '/static/' to a local development server. The host header is automatically rewritten, and the prefix is removed from the URL before dispatching. ```python app = ProxyMiddleware(app, { "/static/": { "target": "http://127.0.0.1:5001/", } }) ``` -------------------------------- ### Shut Down Server Using Multiprocessing Source: https://werkzeug.palletsprojects.com/en/stable/serving Demonstrates how to start the Werkzeug development server in a separate process and shut it down programmatically after receiving a token. This is useful for tasks like OAuth authentication. ```python import multiprocessing from werkzeug import Request, Response, run_simple def get_token(q: multiprocessing.Queue) -> None: @Request.application def app(request: Request) -> Response: q.put(request.args["token"]) return Response("", 204) run_simple("localhost", 5000, app) if __name__ == "__main__": q = multiprocessing.Queue() p = multiprocessing.Process(target=get_token, args=(q,)) p.start() print("waiting") token = q.get(block=True) p.terminate() print(token) ``` -------------------------------- ### werkzeug.serving.make_ssl_devcert Source: https://werkzeug.palletsprojects.com/en/stable/serving Creates an SSL key and certificate for development purposes. This function is useful for generating a persistent development SSL certificate, unlike the 'adhoc' key which generates a new certificate on each server start. It requires a base path for storing the files and can optionally take a host or a common name (CN). ```APIDOC ## werkzeug.serving.make_ssl_devcert ### Description Creates an SSL key for development. This should be used instead of the 'adhoc' key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN `*.host/CN=host`. ### Parameters #### Path Parameters - **base_path** (str) - Required - The path to the certificate and key. The extension `.crt` is added for the certificate, `.key` is added for the key. - **host** (str | None) - Optional - The name of the host. This can be used as an alternative for the `cn`. - **cn** (str | None) - Optional - The `CN` to use. ### Return type tuple[str, str] ``` -------------------------------- ### Get WSGI Headers for Environment Source: https://werkzeug.palletsprojects.com/en/stable/wrappers The `get_wsgi_headers()` method is called before the response starts and returns headers modified for the given WSGI environment. It handles modifications like joining location headers with the root URL and setting content length to zero for specific status codes. ```python response.get_wsgi_headers(_environ) ``` -------------------------------- ### Basic URL Matching with Werkzeug Map Source: https://werkzeug.palletsprojects.com/en/stable/routing Demonstrates how to create a URL map with different rules and bind it to a host. It then shows how to match a path and method against these rules, returning the endpoint and arguments. ```python >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.match("/", "GET") ('index', {}) >>> urls.match("/downloads/42") ('downloads/show', {'id': 42}) ``` -------------------------------- ### GET Request Source: https://werkzeug.palletsprojects.com/en/stable/test Simulates a GET request to a given URL. This method is a shortcut for calling open() with method set to GET. ```APIDOC ## GET Request ### Description Simulates a GET request to a given URL. This method is a shortcut for calling open() with method set to GET. ### Method GET ### Endpoint Not applicable (client method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a TestResponse object. #### Response Example None ``` -------------------------------- ### Create a Simple Response Source: https://werkzeug.palletsprojects.com/en/stable/wrappers Demonstrates how to create a basic HTTP response with a 'Hello, World!' body using the Response class. ```python from werkzeug.wrappers.response import Response def index(): return Response("Hello, World!") ``` -------------------------------- ### Create app factory wrapper Source: https://werkzeug.palletsprojects.com/en/stable/deployment/uwsgi Create a small Python file to instantiate your application when using the app factory pattern. ```python from hello import create_app app = create_app() ``` -------------------------------- ### Initialize Werkzeug Test Client Source: https://werkzeug.palletsprojects.com/en/stable/test Instantiate the `Client` to simulate requests to a WSGI application. Requires importing `Client` and the application to test. ```python from werkzeug.test import Client from werkzeug.testapp import test_app c = Client(test_app) response = c.get("/") response.status_code response.headers response.get_data(as_text=True) ``` -------------------------------- ### TypeConversionDict get() with type conversion Source: https://werkzeug.palletsprojects.com/en/stable/datastructures Demonstrates using the get() method of TypeConversionDict to retrieve and convert values. If type conversion fails with ValueError or TypeError, the default value is returned. ```python >>> d = TypeConversionDict(foo='42', bar='blub') >>> d.get('foo', type=int) 42 >>> d.get('bar', -1, type=int) -1 ``` -------------------------------- ### Validate byte content range Source: https://werkzeug.palletsprojects.com/en/stable/http Use `is_byte_range_valid` to check if a given byte range (start, stop) is valid for a content of a specific length. Handles None values for start, stop, and length. ```python from werkzeug.http import is_byte_range_valid is_byte_range_valid(0, 100, 200) # True is_byte_range_valid(150, 200, 200) # True is_byte_range_valid(0, 100, 50) # False ``` -------------------------------- ### Get Response Body as Text or Bytes Source: https://werkzeug.palletsprojects.com/en/stable/wrappers The `get_data` method retrieves the response body. Set `as_text=True` to get a decoded string; otherwise, it returns bytes. Be cautious with large streamed data as this method encodes and flattens the response iterable. ```python response.get_data(as_text=False) ``` ```python response.get_data(as_text=True) ``` -------------------------------- ### Run uWSGI with app factory Source: https://werkzeug.palletsprojects.com/en/stable/deployment/uwsgi Run uWSGI pointing to an application created by an app factory pattern. ```bash $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app ``` -------------------------------- ### host Source: https://werkzeug.palletsprojects.com/en/stable/wrappers Gets the host name the request was made to, including the port if non-standard. Validated with `trusted_hosts`. ```APIDOC ## property host ### Description The host name the request was made to, including the port if it’s non-standard. Validated with `trusted_hosts`. See `get_host()` for a detailed explanation. ### Return Type str ``` -------------------------------- ### Basic WSGI Application Source: https://werkzeug.palletsprojects.com/en/stable/quickstart A standard WSGI 'Hello World' application without using Werkzeug's Response objects. ```python def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!'] ``` -------------------------------- ### Get Mimetype Quality Value Source: https://werkzeug.palletsprojects.com/en/stable/quickstart Retrieves the quality value (q-value) for a specific mimetype from the Accept header. ```python print(request.accept_mimetypes["application/json"]) ``` -------------------------------- ### Instantiating HeaderSet Source: https://werkzeug.palletsprojects.com/en/stable/datastructures Demonstrates how to create a HeaderSet object from an iterable of strings. This is the standard way to initialize HeaderSet if not using parse_set_header(). ```python >>> hs = HeaderSet(['foo', 'bar', 'baz']) >>> hs HeaderSet(['foo', 'bar', 'baz']) ``` -------------------------------- ### Cached Property Example Source: https://werkzeug.palletsprojects.com/en/stable/utils Demonstrates the usage of cached_property for efficient attribute access. The value is computed only once and then cached. ```python class Example: @cached_property def value(self): # calculate something important here return 42 e = Example() e.value # evaluates e.value # uses cache e.value = 16 # sets cache del e.value # clears cache ``` -------------------------------- ### werkzeug.http.is_byte_range_valid Source: https://werkzeug.palletsprojects.com/en/stable/http Validates if a given byte content range (start, stop) is valid with respect to the total length of the content. ```APIDOC ## werkzeug.http.is_byte_range_valid ### Description Checks if a given byte content range is valid for the given length. ### Parameters #### Path Parameters - **start** (int | None) - **stop** (int | None) - **length** (int | None) ### Returns - **bool** ``` -------------------------------- ### MapAdapter Initialization Source: https://werkzeug.palletsprojects.com/en/stable/routing The MapAdapter is returned by Map.bind() or Map.bind_to_environ() and is used for URL matching and building based on runtime information. It requires several parameters including the map, server name, script name, subdomain, URL scheme, path info, default method, and optional query arguments. ```APIDOC ## class werkzeug.routing.MapAdapter(_map_, _server_name_, _script_name_, _subdomain_, _url_scheme_, _path_info_, _default_method_, _query_args =None_) Returned by `Map.bind()` or `Map.bind_to_environ()` and does the URL matching and building based on runtime information. Parameters: * **map** (_Map_) * **server_name** (_str_) * **script_name** (_str_) * **subdomain** (_str_ _|_ _None_) * **url_scheme** (_str_) * **path_info** (_str_) * **default_method** (_str_) * **query_args** (_t.Mapping_ _[__str_ _,__t.Any_ _]__|__str_ _|__None_) ``` -------------------------------- ### Configure hosts file for local domain simulation Source: https://werkzeug.palletsprojects.com/en/stable/deployment/apache-httpd Edit your system's hosts file to associate a domain name with a local IP address for testing purposes. ```bash 127.0.0.1 hello.localhost ``` -------------------------------- ### Run Simple Server with Adhoc SSL Source: https://werkzeug.palletsprojects.com/en/stable/serving Enables SSL for the Werkzeug development server by generating an ad-hoc certificate on the fly. This is discouraged for production. ```python run_simple('localhost', 4000, application, ssl_context='adhoc') ``` -------------------------------- ### property values: CombinedMultiDict[str, str] Source: https://werkzeug.palletsprojects.com/en/stable/wrappers A `werkzeug.datastructures.CombinedMultiDict` that merges `args` and `form` parameters. For GET requests, only `args` are present. ```APIDOC ## property values: CombinedMultiDict[str, str] ### Description A `werkzeug.datastructures.CombinedMultiDict` that combines `args` and `form`. For GET requests, only `args` are present, not `form`. ### Changelog ``` -------------------------------- ### Raising BadRequestKeyError Source: https://werkzeug.palletsprojects.com/en/stable/exceptions This example demonstrates how a KeyError can also function as a BadRequest exception, useful for handling missing form data. ```python def new_post(request): post = Post(title=request.form['title'], body=request.form['body']) post.save() return redirect(post.url) ``` -------------------------------- ### Basic HTTP Exception Handling Source: https://werkzeug.palletsprojects.com/en/stable/exceptions Demonstrates raising a `NotFound` exception and catching `HTTPException` to handle it as a WSGI application. ```python from werkzeug.wrappers.request import Request from werkzeug.exceptions import HTTPException, NotFound def view(request): raise NotFound() @Request.application def application(request): try: return view(request) except HTTPException as e: return e ``` -------------------------------- ### Run uWSGI with gevent worker Source: https://werkzeug.palletsprojects.com/en/stable/deployment/uwsgi Run uWSGI using the gevent worker for asynchronous support. Ensure greenlet>=1.0 is installed. ```bash $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app ``` -------------------------------- ### Dispatching a Request with Werkzeug Source: https://werkzeug.palletsprojects.com/en/stable/routing This snippet demonstrates how to use the `dispatch` method of a MapAdapter to handle incoming requests. It shows setting up a simple WSGI application with routing and view functions, and how to bind the map to the WSGI environment. ```python from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder from werkzeug.routing import Map, Rule def on_index(request): return Response('Hello from the index') url_map = Map([Rule('/', endpoint='index')]) views = {'index': on_index} @responder def application(environ, start_response): request = Request(environ) urls = url_map.bind_to_environ(environ) return urls.dispatch(lambda e, v: views[e](request, **v), catch_http_exceptions=True) ``` -------------------------------- ### Run Gunicorn with Eventlet Worker Source: https://werkzeug.palletsprojects.com/en/stable/deployment/gunicorn Use the eventlet worker type for asynchronous operations. Similar to gevent, ensure greenlet>=1.0 is installed. ```bash gunicorn -k eventlet 'hello:create_app()' ``` -------------------------------- ### Initialize Redis and Jinja2 environment Source: https://werkzeug.palletsprojects.com/en/stable/tutorial Extends the `Shortly` class constructor to initialize the Redis client and set up the Jinja2 environment for template rendering. ```python def __init__(self, config): self.redis = redis.Redis(config['redis_host'], config['redis_port']) template_path = os.path.join(os.path.dirname(__file__), 'templates') self.jinja_env = Environment(loader=FileSystemLoader(template_path), autoescape=True) ``` -------------------------------- ### Access Response Body Data Source: https://werkzeug.palletsprojects.com/en/stable/wrappers The `data` property provides convenient access to get and set the response body, internally calling `get_data()` and `set_data()`. ```python response.data ``` -------------------------------- ### Host Matching with Variable Hostnames Source: https://werkzeug.palletsprojects.com/en/stable/routing Demonstrates host matching where a part of the hostname is a variable. The `host` argument in `Rule` can include variable parts like `.example.com`. ```python url_map = Map([ Rule('/', endpoint='www_index', host='www.example.com'), Rule('/', endpoint='user_index', host='.example.com') ], host_matching=True) ``` -------------------------------- ### Run Simple Server with SSLContext Object Source: https://werkzeug.palletsprojects.com/en/stable/serving Configures the Werkzeug development server to use HTTPS by providing an `ssl.SSLContext` object for fine-grained TLS control. ```python import ssl ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain('ssl.cert', 'ssl.key') run_simple('localhost', 4000, application, ssl_context=ctx) ``` -------------------------------- ### Accessing the top item of LocalStack Source: https://werkzeug.palletsprojects.com/en/stable/local Access the 'top' property to get the topmost item on a LocalStack without removing it. Returns None if the stack is empty. ```python stack.top ``` -------------------------------- ### Map Class Initialization Parameters Source: https://werkzeug.palletsprojects.com/en/stable/routing Initializes a Map instance with various configuration options that affect URL rule storage and matching. All arguments besides 'rules' must be passed as keyword arguments. ```python class werkzeug.routing.Map(_rules =None_, _default_subdomain =''_, _strict_slashes =True_, _merge_slashes =True_, _redirect_defaults =True_, _converters =None_, _sort_parameters =False_, _sort_key =None_, _host_matching =False_) ``` -------------------------------- ### Run Waitress with WSGI App Source: https://werkzeug.palletsprojects.com/en/stable/deployment/waitress Serve a WSGI application by specifying the module and app variable. Use --call for app factories. ```bash waitress-serve hello:app --host 127.0.0.1 ``` ```bash waitress-serve --call hello:create_app --host 127.0.0.1 ```