Skip to main content

simple FastCGI sync/async handler in pure python

Project description

Simple FastCGI

simple FastCGI protocol parser and sync/async handler in pure python

Example (sync)

import json
from simple_fastcgi import *

class example_handler(HttpResponseMixin, FcgiHandler):
	def handle(self):
		self.send_response(200, "application/json", self.environ)

if __name__ == "__main__":
	with FcgiServer(example_handler) as server:
		server.serve_forever()

Example (async)

import json
import asyncio
from simple_fastcgi import *

class example_handler(AsyncHttpResponseMixin, AsyncFcgiHandler):
	async def handle(self):
		await self.send_response(200, "application/json", self.environ)

async def main():
	async with AsyncFcgiServer(example_handler) as server:
		await server.serve_forever()

if __name__ == "__main__":
	asyncio.run(main())

API reference

The import module name is simple_fastcgi

Exceptions

ProtocolError

Raised when encountered FastCGI protocol violations.

Handlers

class FcgiHandler

FastCGI Handler, subclass of BaseRequestHandler. To implement your own handler, subclass FcgiHandler and override the handle() method.

environ

Member environ is a dictionary containing key-value pairs from the webserver. The keys are converted to upper-case.

handle()

Override this method and do all the work here to serve a request.

aborted()

Check if the FastCGI request has been aborted by the webserver.

read(sz = -1)

Read and return up to sz bytes from input stream. If sz < 0, read until EOF. Returns empty bytes object on EOF.

readinto(buffer)

Read from input stream into buffer, return the actual read byte count. Returns 0 on EOF.

readall()

Read input stream until EOF and return all the data.

write(data)

Write data to the output stream.

write_err(data)

Write data to the error stream.

class AsyncFcgiHandler

Async variant of FcgiHandler. methods are the same, except being async.

async handle()

aborted()

async read(sz = -1)

async readinto(buffer)

async readall()

async write(data)

async write_err(data)

Servers

class FcgiServer

Subclass of BaseServer, but instead listening on FCGI_LISTENSOCK_FILENO ( fd 0 ). Can be used with context manager.

init(handler, sockfd = sys.stdin.fileno())

Initialize a server object. Subclass may override and do extra initialization.

handler is the handler-class which is instantiated on each request.

sockfd is a listening socket on which the server is running, defaults to fd 0 in conforming to FastCGI Specification.

fileno()

Get the underlying fd of the server object. Returns sockfd.

shutdown()

Stop the server.

serve_forever()

Start the server and block until shutdown.

service_actions()

Called in serve_forever loop. Subclass may override and do their own actions.

class AsyncFcgiServer

Async variant of FcgiServer. methods are the same, except being async. Can be used with async context manager.

Note there is no service_actions() in AsyncFcgiServer, since it runs on event loop instead of its own loop, and one can easily schedule tasks to event loop.

init(handler, sockfd = sys.stdin.fileno())

fileno()

get_loop()

Get the event loop on which the server is running.

async shutdown()

async serve_forever()

Mixins

class HttpResponseMixin

Helper mixin class for FcgiServer, to construct CGI/HTTP responses.

send_response(code, /, mime_type = "text/plain", data = None, *, extra_headers = [])

Construct a CGI document response and write to output stream.

code is the HTTP status code of the response.

mime_type is the content-type of the response.

extra_headers is the extra HTTP header fields that should be included in the response header.

data is the payload of the response.

  • if data is a function, it is assumed to be a generator and called to get chunks of data.
  • if data is a string, it is encoded in UTF-8.
  • if "json" appears in mime_type and data is not bytes-like, try to encode data as json.
  • else, append data to payload as-is.

Note that you can mix this method with write() calls. For example, you can call this method, passing first data chunk as data parameter, followed by multiple write() calls to append more data.

Also note that this method does not calculate or append a content-length header for you. You need to handle content-length header yourself, either omit this header, or calculate in advance.

send_redirect(target)

Construct a CGI redirect response and write to output stream.

target is the redirect target, it can be either local-Location or client-Location as defined in CGI Specification.

AsyncHttpResponseMixin

Async variant of HttpResponseMixin. methods are the same, except being async

async send_response(code, /, mime_type = "text/plain", data = None, *, extra_headers = [])

Note that if data is a function, it is assumed to be an async generator instead.

async send_redirect(target)

Reference

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

simple_fastcgi-0.0.2.tar.gz (10.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

simple_fastcgi-0.0.2-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file simple_fastcgi-0.0.2.tar.gz.

File metadata

  • Download URL: simple_fastcgi-0.0.2.tar.gz
  • Upload date:
  • Size: 10.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for simple_fastcgi-0.0.2.tar.gz
Algorithm Hash digest
SHA256 6ba5dc672289a13e5b7f7b499dde43aa89a8f75b99443f3a52081fcbade5958b
MD5 764434a78841a87e3b11d8f283b76154
BLAKE2b-256 7e8dd8302096ee474f76bb41b4ee54354bd380ab71f18e4c12e0e4ca3c0f64f1

See more details on using hashes here.

Provenance

The following attestation bundles were made for simple_fastcgi-0.0.2.tar.gz:

Publisher: python-publish.yml on USN484259/simple-fastcgi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file simple_fastcgi-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: simple_fastcgi-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 9.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for simple_fastcgi-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b88bc9390f342705e5b7659b9552581d02baf352740087eda7d993a31ef2c4dd
MD5 54f871f9181a8df254eb45561b5e019e
BLAKE2b-256 2e811c6312b9b07c4b527ea5a86960a5c6b9eb7bf9c8db019d592ec20dbd848a

See more details on using hashes here.

Provenance

The following attestation bundles were made for simple_fastcgi-0.0.2-py3-none-any.whl:

Publisher: python-publish.yml on USN484259/simple-fastcgi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page