Pyjo.Server.WSGI - WSGI server

from Pyjo.Server.WSGI import WSGI

wsgi = WSGI()


@wsgi.unsubscribe('request').on('request')
def request(wsgi, tx):
    # Request
    method = tx.req.method
    path = tx.req.url.path

    # Response
    tx.res.code = 200
    tx.res.headers.content_type = 'text/plain'
    tx.res.body = f'{method} request for {path}!'.encode()

    # Resume transaction
    tx.resume()


app = wsgi.to_wsgi_app()

# Or import the module, as in Google Python Style Guide

import Pyjo.Server.WSGI

wsgi = Pyjo.Server.WSGI.new()


@wsgi.unsubscribe('request').on('request')
def request(wsgi, tx):
    # Request
    method = tx.req.method
    path = tx.req.url.path

    # Response
    tx.res.code = 200
    tx.res.headers.content_type = 'text/plain'
    tx.res.body = f'{method} request for {path}!'.encode()

    # Resume transaction
    tx.resume()


app = wsgi.to_wsgi_app()

Pyjo.Server.WSGI allows Pyjoyment applications to run on all WSGI compatible servers, as PEP 3333 describes them.

# Serve with the server of wsgiref
from wsgiref.simple_server import make_server

make_server('', 3000, app).serve_forever()

The response is given in the request event, as WSGI is synchronous; its content can come later, as the event loop of Pyjo.IOLoop runs while the server waits for it. The request is read from the environment of PEP 3333 with read, a body of unknown length when the server sets wsgi.input_terminated, as for a chunked request. The response goes without the hop-by-hop headers that PEP 3333 forbids, so chunked content is sent without its framing, which the server adds. The transaction is finished when the server closes the body of the response.

WSGI servers

  • Gunicorn and Waitress: also chunked requests.

  • uWSGI with --http-socket: a chunked request reaches the application without its body.

  • Werkzeug: also chunked requests, with a Date header of its own next to the one of the response.

Events

Pyjo.Server.WSGI inherits all events from Pyjo.Server.

Attributes

Pyjo.Server.WSGI inherits all attributes from Pyjo.Server.

See also

Pyjoyment, https://mojolicious.org.

Ported from Mojo::Server::PSGI of Mojolicious 9.49.

Classes

class Pyjo.Server.WSGI.Pyjo_Server_WSGI(*, app: Application | None = None, reverse_proxy: bool | None = None, trusted_proxies: list[str] | None = None)

Pyjo.Server.WSGI inherits all methods from Pyjo.Server and implements the following new ones.

run(environ: dict[str, Any]) → tuple[str, list[tuple[str, str]], Iterable[bytes]]
status, headers, body = wsgi.run(environ)

Run WSGI: the status, the headers and the body of the response, whose close finishes the transaction.

to_wsgi_app() → Callable[[dict[str, Any], StartResponse], Iterable[bytes]]
app = wsgi.to_wsgi_app()

Turn Pyjoyment application into WSGI application.