App Documentation¶
Web Service (App) Class¶
- class dyne.App(*, debug=False, static_dir='static', static_route='/static', templates_dir='templates', auto_escape=True, secret_key='NOTASECRET', enable_hsts=False, cors=False, cors_params={'allow_credentials': False, 'allow_headers': (), 'allow_methods': ('GET',), 'allow_origin_regex': None, 'allow_origins': (), 'expose_headers': (), 'max_age': 600}, allowed_hosts=None, env_file: str | Path | None = None, env_prefix: str = '', encoding: str = 'utf-8', environ: MutableMapping[str, str] = environ({'READTHEDOCS_VIRTUALENV_PATH': '/home/docs/checkouts/readthedocs.org/user_builds/dyneapi/envs/latest', 'READTHEDOCS_CANONICAL_URL': 'https://dyneapi.readthedocs.io/en/latest/', 'HOSTNAME': 'build-31611486-project-1061819-dyneapi', 'READTHEDOCS_GIT_CLONE_URL': 'https://github.com/tabotkevin/dyne.git', 'HOME': '/home/docs', 'NO_COLOR': '1', 'READTHEDOCS': 'True', 'READTHEDOCS_PRODUCTION_DOMAIN': 'app.readthedocs.org', 'READTHEDOCS_REPOSITORY_PATH': '/home/docs/checkouts/readthedocs.org/user_builds/dyneapi/checkouts/latest', 'READTHEDOCS_PROJECT': 'dyneapi', 'READTHEDOCS_OUTPUT': '/home/docs/checkouts/readthedocs.org/user_builds/dyneapi/checkouts/latest/_readthedocs/', 'PATH': '/home/docs/checkouts/readthedocs.org/user_builds/dyneapi/envs/latest/bin:/home/docs/.asdf/shims:/home/docs/.asdf/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'READTHEDOCS_VERSION_TYPE': 'branch', 'LANG': 'C.UTF-8', 'READTHEDOCS_LANGUAGE': 'en', 'DEBIAN_FRONTEND': 'noninteractive', 'READTHEDOCS_GIT_COMMIT_HASH': 'b8e754202c8b91ef7004d3a8ddc2a9bc4851cd7d', 'READTHEDOCS_VERSION_NAME': 'latest', 'READTHEDOCS_VERSION': 'latest', 'PWD': '/home/docs/checkouts/readthedocs.org/user_builds/dyneapi/checkouts/latest/docs', 'READTHEDOCS_GIT_IDENTIFIER': 'main', 'DOCUTILSCONFIG': '/home/docs/checkouts/readthedocs.org/user_builds/dyneapi/checkouts/latest/docs/docutils.conf'}))[source]¶
The primary web-service class.
- Parameters:
static_dir – The directory to use for static files. Will be created for you if it doesn’t already exist.
templates_dir – The directory to use for templates. Will be created for you if it doesn’t already exist.
auto_escape – If
True, HTML and XML templates will automatically be escaped.
:param application’s secret_key or set SECRET_KEY in config. :param enable_hsts: If
True, send all responses to HTTPS URLs. :param env_file: Path to a config .env file to load. :param env_prefix: Prefix for environment variables (e.g., ‘DYNE_’). :param encoding: Encoding for the env_file. :param environ: The environment mapping to use (defaults to os.environ).- add_event_handler(event_type, handler)[source]¶
Adds an event handler to the API.
- Parameters:
event_type – A string in (“startup”, “shutdown”)
handler – The function to run. Can be either a function or a coroutine.
- add_route(route=None, endpoint=None, *, default=False, static=True, check_existing=True, websocket=False, before_request=False, methods=('GET', 'POST'))[source]¶
Adds a route to the API.
- Parameters:
route – A string representation of the route.
endpoint – The endpoint for the route – can be a callable, or a class.
default – If
True, all unknown requests will route to this view.static – If
True, and no endpoint was passed, render “static/index.html”, and it will become a default route.methods – A list of supported request methods for this endpoint. e.g [“GET”, “POST”].
- client¶
A Requests session that is connected to the ASGI app.
- mount(route, app)[source]¶
Mounts an ASGI application at a given route.
- Parameters:
route – String representation of the route to be used (shouldn’t be parameterized).
app – The other ASGI app.
- on_event(event_type: str, **args)[source]¶
Decorator for registering functions or coroutines to run at certain events Supported events: startup, shutdown
Usage:
@api.on_event('startup') async def open_database_connection_pool(): ... @api.on_event('shutdown') async def close_database_connection_pool(): ...
- path_matches_route(path)[source]¶
Given a path portion of a URL, tests that it matches against any registered route.
- Parameters:
path – The path portion of a URL, to test all known routes against.
- redirect(resp, location, *, set_text=True, status_code=HTTPStatus.MOVED_PERMANENTLY)[source]¶
Redirects a given response to a given location. :param resp: The Response to mutate. :param location: The location of the redirect. :param set_text: If
True, sets the Redirect body content automatically. :param status_code: an API.status_codes attribute, or an integer, representing the HTTP status code of the redirect.
- route(route=None, methods=('GET',), **options)[source]¶
Decorator for creating new routes around function and class definitions.
Usage:
@api.route("/hello") def hello(req, resp): resp.text = "hello, world!"
- serve(*, address=None, port=None, **options)[source]¶
Runs the application with uvicorn. If the
PORTenvironment variable is set, requests will be served on that port automatically to all known hosts.- Parameters:
address – The address to bind to.
port – The port to bind to. If none is provided, one will be selected at random.
debug – Run uvicorn server in debug mode.
options – Additional keyword arguments to send to
uvicorn.run().
- session(base_url='http://;')[source]¶
Testing HTTP client. Returns a Requests session object, able to send HTTP requests to the dyne application.
- Parameters:
base_url – The URL to mount the connection adaptor to.
- template(filename, *args, **kwargs)[source]¶
Renders the given jinja2 template, with provided values supplied. Note: The current
apiinstance is by default passed into the view. This is set in the dictapi.jinja_values_base. :param filename: The filename of the jinja2 template, intemplates_dir. :param *args: Data to pass into the template. :param *kwargs: Date to pass into the template.
- template_string(source, *args, **kwargs)[source]¶
Renders the given jinja2 template string, with provided values supplied. Note: The current
apiinstance is by default passed into the view. This is set in the dictapi.jinja_values_base. :param source: The template to use. :param *args: Data to pass into the template. :param **kwargs: Data to pass into the template.
Requests & Responses¶
- class dyne.Request(scope, receive, app=None, formats=None)[source]¶
-
- property apparent_encoding¶
The apparent encoding, provided by the chardet library. Must be awaited.
- property content¶
The Request body, as bytes. Must be awaited.
- property cookies¶
The cookies sent in the Request, as a dictionary.
- property encoding¶
The encoding of the Request’s body. Can be set, manually. Must be awaited.
- property full_url¶
The full URL of the Request, query parameters and all.
- property headers¶
A case-insensitive dictionary, containing all headers sent in the Request.
- async media(format=None)[source]¶
Renders incoming json/yaml/form data as Python objects. Must be awaited.
- Parameters:
format – The name of the format being used. Alternatively accepts a custom callable for the format type.
- property method¶
The incoming HTTP method used for the request, lower-cased.
- property params¶
A dictionary of the parsed query parameters used for the Request.
- property session¶
The session data, in dict form. Returns an empty dict if SessionMiddleware is missing or hasn’t run.
- property state: State¶
Use the state to store additional information.
This can be a very helpful feature, if you want to hand over information from a middelware or a route decorator to the actual route handler.
Usage:
request.state.time_started = time.time()
- property text¶
The Request body, as unicode. Must be awaited.
- property url¶
The parsed URL of the Request.
- class dyne.Response(req, *, formats)[source]¶
- content¶
A bytes representation of the response body.
- cookies¶
The cookies set in the Response
- headers¶
A Python dictionary of
{key: value}, representing the headers of the response.
- media¶
A Python object that will be content-negotiated and sent back to the client. Typically, in JSON formatting.
- session¶
The cookie-based session data, in dict form, to add to the Response.
- status_code¶
The HTTP Status Code to use for the Response.