API Reference

The following section documents every class and function in the baguette module.

Application

class baguette.Baguette(*, config=None, debug=False, default_headers=None, static_url_path='static', static_directory='static', templates_directory='static', error_response_type='plain', error_include_description=True, middlewares=[])[source]

Implements an ASGI application.

This class is the main class for any application written with the baguette framework.

Keyword Arguments
  • config (Config) – Config to use for the application. This replaces the other keyword arguments except middlewares. Default: see Config defaults.

  • debug (bool) – Whether to run the application in debug mode. Default: False.

  • default_headers (list of (str, str) tuples, dict or Headers) – Default headers to include in every response. Default: No headers.

  • static_url_path (str) – URL path for the static file handler. Default: "static".

  • static_directory (str) – Path to the folder containing static files. Default: "static".

  • templates_directory (str) – Path to the folder containing the HTML templates. Default: "templates".

  • error_response_type (str) – Type of response to use in case of error. One of: "plain", "json", "html". Default: "plain".

  • error_include_description (bool) – Whether to include the error description in the response in case of error. If debug is True, this will also be True. Default: True.

  • middlewares (list of middleware classes) – The middlewares to add to the application. Default: [].

config

The configuration of the app.

Type

Config

router

The URL router of the app.

Type

Router

renderer

Class that renders the templates.

Type

Renderer

debug

Whether the application is running in debug mode.

Type

bool

default_headers

Default headers included in every response.

Type

Headers

static_url_path

URL path for the static file handler.

Type

str

static_directory

Path to the folder containing static files.

Type

str

templates_directory

Path to the folder containing the HTML templates.

Type

str

error_response_type

Type of response to use in case of error. One of: "plain", "json", "html"

Type

str

error_include_description

Whether the error description is included in the response in case of error. If debug is True, this will also be True.

Type

bool

middlewares

The middlewares of the application.

Type

list of middlewares

async startup()[source]

Runs on application startup.

This will be executed when you start the application. For example, you can connect to a database.

New in version 0.1.0.

async shutdown()[source]

Runs on application shutdown.

This will be executed when you stop the application. For example, you can disconnect from a database.

New in version 0.1.0.

async handle_request(request)[source]

Handles a request and returns a response.

Parameters

request (Request) – The request to handle.

Returns

A response.

Return type

Response

Return type

Response

async dispatch(request)[source]

Dispatches a request to the correct handler and return its result.

Parameters

request (Request) – The request to handle.

Returns

The handler response.

Return type

Response

Changed in version 0.3.0: The return value isn’t the handler return value anymore, but instead a Response.

Return type

Response

add_route(path, handler, methods=None, name=None, defaults=None)[source]

Adds a route to the application router.

Parameters
  • path (str) – The path that the handler will handle. Can be dynamic, see Dynamic Routing.

  • handler (Async callable) – An asynchronous callable (function or class) that can handle a request.

  • methods (list of str) – Allowed methods for this path. Default: ["GET", "HEAD"].

  • name (str) – Name of the route. Default: handler function name.

  • defaults (Optional dict) – Default arguments to give to your handler. Default: {}.

Returns

The created route.

Return type

Route

Return type

Route

route(path, methods=None, name=None, defaults=None)[source]

Decorator to add a handler function to the router with the given path.

Parameters
  • path (str) – The path that the handler will handle. Can be dynamic, see Dynamic Routing.

  • methods (Optional list of str) – Allowed methods for this path. Default: ["GET", "HEAD"].

  • name (Optional str) – Name of the route. Default: handler function name.

  • defaults (Optional dict) – Default arguments to give to your handler. Default: {}.

Changed in version 0.0.3: Renamed from Baguette.endpoint to Baguette.route()

build_middlewares(middlewares=[])[source]

Builds the middleware stack from a list of middleware classes.

Note

The first middleware in the list will be the first called on a request.

See also

There are middlewares included by default. See Default middlewares.

Parameters

middlewares (list of Middleware) – The middlewares to add.

New in version 0.3.0.

add_middleware(middleware, index=1)[source]

Adds a middleware to the middleware stack.

Parameters
  • middleware (Middleware) – The middleware to add.

  • index (Optional int) – The index to add the middlware to. Default: 1 (second middleware, called after ErrorMiddleware)

New in version 0.3.0.

remove_middleware(middleware)[source]

Removes a middleware from the middleware stack.

Parameters

middleware (Middleware) – The middleware to remove.

New in version 0.3.0.

middleware(index=1)[source]

Decorator to add a middleware to the app.

Parameters

index (Optional int) – The index to add the middlware to. Default: 1 (second middleware, called after ErrorMiddleware)

New in version 0.3.0.

async handle_websocket(websocket)[source]

Handles a webhook.

Parameters

webhook (Webhook) – The webhook to handle.

async route_websocket(scope)[source]

Returns the correct route for the websocket.

Parameters

scope (ASGI scope) – The ASGI scope of the websocket connection.

Returns

The websocket route.

Return type

WebsocketRoute

Raises

NotFound – The websocket route.

Return type

WebsocketRoute

add_websocket_route(path, websocket, name=None)[source]

Adds a websocket route to the application websocket router.

Parameters
  • path (str) – The path that the websocket will handle.

  • websocket (Websocket class) – Websocket class that handles this path.

  • name (str) – Name of the route. Default: websocket class name.

Returns

The created route.

Return type

WebsocketRoute

Return type

Route

websocket(path, name=None)[source]

Decorator to add a websocket to the router with the given path.

Parameters
  • path (str) – The path that the websocket will handle.

  • name (Optional str) – Name of the route. Default: websocket class name.

run(*, host='127.0.0.1', port=8000, uds=None, fd=None, debug=None, headers=None, loop='auto', http='auto', ws='auto', env_file=None, log_config=None, log_level=None, access_log=True, use_colors=None, workers=None, proxy_headers=True, forwarded_allow_ips=None, root_path='', limit_concurrency=None, limit_max_requests=None, backlog=2048, timeout_keep_alive=5, timeout_notify=30, callback_notify=None, ssl_keyfile=None, ssl_certfile=None, ssl_keyfile_password=None, ssl_version=None, ssl_cert_reqs=<VerifyMode.CERT_NONE: 0>, ssl_ca_certs=None, ssl_ciphers='TLSv1')[source]

Runs the server with uvicorn.

Warning

You need uvicorn installed in order to use this. See Installing ASGI server.

Keyword Arguments
  • host (Optional str) – Bind socket to this host. IPv6 addresses are supported. Default: 127.0.0.1

  • port (Optional int) – Bind to a socket with this port. Default: 8000.

  • uds (Optional str) – Bind to a UNIX domain socket. Default: None.

  • fd (Optional int) – Bind to socket from this file descriptor. Default: None.

  • debug (Optional bool) – Update the app.debug variable while the app is running. Default: None.

  • headers (Optional list of (str, str) tuples, dict or Headers) – Add headers to every response while the app is running. Default: None.

  • loop (Optional "auto", "asyncio" or "uvloop") – Event loop implementation. The uvloop implementation provides greater performance, but is not compatible with Windows or PyPy. Default: "auto"

  • http (Optional "auto", "h11" or "httptools") – HTTP protocol implementation. The httptools implementation provides greater performance, but it not compatible with PyPy, and requires compilation on Windows. Default: "auto"

  • ws (Optional "auto", "none", "websockets" or "wsproto") – WebSocket protocol implementation. Either of the websockets and wsproto packages are supported. Use "none" to deny all websocket requests. Default: "auto"

  • env_file (Optional str (path to file)) – Environment configuration file. Loaded with python-dotenv Default: None

  • log_config (Optional dictConfig() formats, .json and .yaml file paths or fileConfig() formats.) – Logging configuration. Default: uvicorn.config.LOGGING_CONFIG

  • log_level ("critical", "error", "warning", "info", "debug" or "trace") – Application log level. Default: "info"

  • access_log (Optional bool) – Whether to log every request. Default: True

  • use_colors (Optional bool) – Whether to enable colorized formatting of the log records, in case this is not set it will be auto-detected. This option is ignored if log_config is given. Default: None

  • workers (Optional int) – Number of worker processes to use. Default: WEB_CONCURRENCY environment variable if available, or 1

  • proxy_headers (Optional bool) – Whether to enable X-Forwarded-Proto, X-Forwarded-For and X-Forwarded-Port headers to populate remote address info. Restricted to only trusting connecting IPs in the forwarded_allow_ips parameter. Default: True

  • forwarded_allow_ips (Optional str) – Comma separated list of IPs to trust with proxy headers. A wildcard "*" means always trust. Default: FORWARDED_ALLOW_IPS environment variable if available, or 127.0.0.1

  • ssl_keyfile (Optional str (path to file)) – SSL key file Default: None

  • ssl_certfile (Optional str (path to file)) – SSL certificate file Default: None

  • ssl_keyfile_password (Optional str) – Password to decrypt the ssl key Default: None

  • ssl_version (Optional int) – SSL version to use. See ssl module. Default: ssl.PROTOCOL_TLS

  • ssl_cert_reqs (Optional int) – Whether client certificate is required. One of ssl.VerifyMode values, a constant of the ssl module that starts with CERT_. Default: ssl.CERT_NONE

  • ssl_ca_certs (Optional str (path to file)) – CA certificates file Default: None

  • ssl_ciphers (Optional str) – Ciphers to use. See ssl module. Default: "TLSv1"

Note

Doesn’t support reloading, if you want reloading, run the application from the console with uvicorn and add the --reload flag.

New in version 0.1.2.

Configuration

class baguette.Config(*, debug=False, default_headers=None, static_url_path='static', static_directory='static', templates_directory='static', error_response_type='plain', error_include_description=True)[source]

Baguette application configuration.

Keyword Arguments
  • debug (bool) – Whether to run the application in debug mode. Default: False.

  • default_headers (list of (str, str) tuples, dict or Headers) – Default headers to include in every response. Default: No headers.

  • static_url_path (str) – URL path for the static file handler. Default: "static".

  • static_directory (str) – Path to the folder containing static files. Default: "static".

  • templates_directory (str) – Path to the folder containing the HTML templates. Default: "templates".

  • error_response_type (str) – Type of response to use in case of error. One of: "plain", "json", "html". Default: "plain".

  • error_include_description (bool) – Whether to include the error description in the response in case of error. If debug is True, this will also be True. Default: True.

debug

Whether the application is running in debug mode.

Type

bool

default_headers

Default headers included in every response.

Type

Headers

static_url_path

URL path for the static file handler.

Type

str

static_directory

Path to the folder containing static files.

Type

str

templates_directory

Path to the folder containing the HTML templates.

Type

str

error_response_type

Type of response to use in case of error. One of: "plain", "json", "html"

Type

str

error_include_description

Whether the error description is included in the response in case of error. If debug is True, this will also be True.

Type

bool

classmethod from_json(filename)[source]

Loads the configuration from a JSON file.

Parameters

filename (str) – The file name of the JSON config file.

Returns

The loaded configuration.

Return type

Config

Return type

Config

classmethod from_class(class_or_module_name)[source]

Loads the configuration from a python class.

Parameters

class_or_module_name (class or str) – The class to load the configuration.

Returns

The loaded configuration.

Return type

Config

Return type

Config

View

class baguette.View(app)[source]

Base view class.

Parameters

app (Baguette) – The app that the view was added to.

app

The app that the view was added to.

Type

Baguette

methods

The methods that this view can handle.

Type

list of str

async dispatch(request, **kwargs)[source]

Dispatch the request to the right method handler.

Return type

Response

Request

class baguette.Request(app, scope, receive)[source]

Request class that is passed to the view functions.

Parameters
app

The application that handles the request.

Type

Baguette

http_version

The HTTP version used. One of "1.0", "1.1" or "2".

Type

str

asgi_version

The ASGI specification version used.

Type

str

headers

The HTTP headers included in the request.

Type

Headers

method

The HTTP method name, uppercased.

Type

str

scheme

URL scheme portion (likely "http" or "https").

Type

str

path

HTTP request target excluding any query string, with percent-encoded sequences and UTF-8 byte sequences decoded into characters. "/" at the end of the path is striped.

Type

str

querystring

URL querystring decoded by urllib.parse.parse_qs().

Type

dict with str keys and list of str values

server

Adress and port of the server. The first element can be the path to the UNIX socket running the application, in that case the second element is None.

Type

tuple of (str, int)

client

Adress and port of the client. The adress can be either IPv4 or IPv6.

Type

tuple of (str, int)

content_type

Content type of the response body.

Type

str

encoding

Encoding of the response body.

Type

str

async raw_body()[source]

Gets the raw request body in bytes.

Returns

Raw request body.

Return type

bytes

Return type

bytes

async body()[source]

Gets the request body in str.

Returns

Request body.

Return type

str

Return type

str

async json()[source]

Parses the request body to JSON.

Returns

Parsed body.

Return type

Anything that can be decoded from JSON

Raises

BadRequest – If the JSON body is not JSON. You can usually not handle this error as it will be handled by the app and converted to a response with a 400 status code.

Return type

Union[dict, list, tuple, str, int, float, bool]

async form(include_querystring=False)[source]

Parses the request body as form data.

Parameters

include_querystring (Optional bool) – Whether to include the querystrings in the form fields.

Returns

Parsed form.

Return type

Form

Return type

Form

set_raw_body(raw_body)[source]

Sets the raw body of the request.

Parameters

raw_body (bytes) – The new request raw body

Raises

TypeError – The raw body isn’t of type bytes

set_body(body)[source]

Sets the request body.

Parameters

body (str or bytes) – The new request body

Raises

TypeError – The body isn’t of type str or bytes

set_json(data)[source]

Sets the request JSON data.

Parameters

data (Anything JSON serializable) – The data to put in the request body.

Raises

TypeError – The data isn’t JSON serializable.

set_form(form)[source]

Sets the request form.

Parameters

form (Form) – The form to add to the request.

Raises

TypeError – The form isn’t a Form.

Responses

Base Response

class baguette.Response(body, status_code=200, headers=None)[source]

Base response class.

Parameters
  • body (str or bytes) – The response body.

  • status_code (int) – The HTTP status code of the reponse.

  • headers (list of (str, str) tuples, dict or Headers) – The headers of the reponse.

status_code

The HTTP status code of the reponse.

Type

int

headers

The headers of the reponse.

Type

Headers

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a str.

Return type

str

property raw_body

The reponse raw body.

Note

Setting the request body also accepts a str but accessing the request raw body will always return a bytes.

Return type

bytes

Plain Text Response

class baguette.PlainTextResponse(text, status_code=200, headers=None)[source]

Plain text response class.

Parameters
  • body (str or bytes) – The response body.

  • status_code (int) – The HTTP status code of the reponse.

  • headers (list of (str, str) tuples, dict or Headers) – The headers of the reponse.

status_code

The HTTP status code of the reponse.

Type

int

headers

The headers of the reponse.

Type

Headers

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a str.

Return type

str

property raw_body

The reponse raw body.

Note

Setting the request body also accepts a str but accessing the request raw body will always return a bytes.

Return type

bytes

HTML Response

class baguette.HTMLResponse(html, status_code=200, headers=None)[source]

HTML response class.

Parameters
  • body (str or bytes) – The response body.

  • status_code (int) – The HTTP status code of the reponse.

  • headers (list of (str, str) tuples, dict or Headers) – The headers of the reponse.

status_code

The HTTP status code of the reponse.

Type

int

headers

The headers of the reponse.

Type

Headers

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a str.

Return type

str

property raw_body

The reponse raw body.

Note

Setting the request body also accepts a str but accessing the request raw body will always return a bytes.

Return type

bytes

JSON Response

class baguette.JSONResponse(data, status_code=200, headers=None)[source]

JSON response class.

Parameters
  • data (Anything JSON serializable) – The response body.

  • status_code (int) – The HTTP status code of the reponse.

  • headers (list of (str, str) tuples, dict or Headers) – The headers of the reponse.

JSON_ENCODER

The JSON encoder to use in json.dumps() with the cls keyword argument. This is a class attribute. Default: the encoder from ujson

Type

JSON encoder

status_code

The HTTP status code of the reponse.

Type

int

headers

The headers of the reponse.

Type

Headers

property json

The request JSON data.

Return type

Any

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a str.

Return type

str

property raw_body

The reponse raw body.

Note

Setting the request body also accepts a str but accessing the request raw body will always return a bytes.

Return type

bytes

Empty Response

class baguette.EmptyResponse(status_code=204, headers=None)[source]

Empty response class.

Parameters
  • body (str or bytes) – The response body.

  • status_code (int) – The HTTP status code of the reponse.

  • headers (list of (str, str) tuples, dict or Headers) – The headers of the reponse.

status_code

The HTTP status code of the reponse.

Type

int

headers

The headers of the reponse.

Type

Headers

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a str.

Return type

str

property raw_body

The reponse raw body.

Note

Setting the request body also accepts a str but accessing the request raw body will always return a bytes.

Return type

bytes

Redirect Response

class baguette.RedirectResponse(location, body='', status_code=301, headers=None)[source]

Redirect response class.

Parameters
  • location (str or bytes) – The location to redirect the request to.

  • body (str or bytes) – The response body.

  • status_code (int) – Status code of the redirect response. Default: 301.

  • headers (list of (str, str) tuples, dict or Headers) – Headers to include in the response. Any location header will be overwritten with the location parameter. Default: None.

status_code

The HTTP status code of the reponse.

Type

int

headers

The headers of the reponse.

Type

Headers

property location

The location to redirect the request to.

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a str.

Return type

str

property raw_body

The reponse raw body.

Note

Setting the request body also accepts a str but accessing the request raw body will always return a bytes.

Return type

bytes

There’s an alias to create this class, it’s the redirect() function.

baguette.redirect(location, status_code=301, headers=None)[source]

Redirect the request to location.

Parameters
  • location (str or bytes) – The location to redirect the request to.

  • status_code (int) – Status code of the redirect response. Default: 301.

  • headers (list of (str, str) tuples, dict or Headers) – Headers to include in the response. Any location header will be overwritten with the location parameter. Default: None.

Returns

The created redirect response.

Return type

RedirectResponse

Return type

RedirectResponse

File Response

class baguette.FileResponse(*paths, attachment_filename=None, mimetype=None, as_attachment=False, add_etags=True, status_code=200, headers=None)[source]

Make Response

baguette.make_response(result)[source]

Makes a Response object from a handler return value.

Parameters

result (Anything described in Responses) – The handler return value.

Returns

The handler response.

Return type

Response

Return type

Response

baguette.make_error_response(http_exception, type_='plain', include_description=True, traceback=None)[source]

Convert an HTTPException to a Response.

Parameters
  • http_exception (HTTPException) – The HTTP exception to convert to a response.

  • type (str) – Type of response. Must be one of: ‘plain’, ‘json’, ‘html’.

  • include_description (bool) – Whether to include the description in the response.

  • traceback (Optional[str]) – Error traceback, usually only included in debug mode.

Raises

ValueErrortype_ isn’t one of: ‘plain’, ‘json’, ‘html’.

Returns

Response that describes the error.

Return type

Response

Return type

Response

Headers

Headers class

class baguette.Headers[source]

Headers implementation for handling str or bytes names and values.

Tip

Use make_headers() to easily make a header from a list or a dict.

get(name, default=None)[source]

Gets a header from its name. If not found, returns default.

Parameters
  • name (str or bytes) – Name of the header to get.

  • default (Optional anything) – Value to return if header not found. Default: None

Returns

  • str – Header value if found.

  • Anythingdefault’s value.

keys()[source]

Returns an iterator over the headers names.

Returns

Iterator over the headers names.

Return type

Iterator of str

items()[source]

Returns an iterator over the headers names and values.

Returns

Iterator over the headers names and values.

Return type

Iterator of (name, value) tuple

raw()[source]

Returns the raw headers, a list of [name, value] where name and value are bytes.

Returns

Raw headers for the ASGI response.

Return type

list of [name, value] where name and value are bytes

Make Headers

baguette.make_headers(headers=None)[source]

Makes a Headers object from a list of (str, str) tuples, a dict, or a Headers instance.

Parameters

headers (list of (str, str) tuples, dict or Headers) – The raw headers to convert.

Raises

TypeErrorheaders isn’t of type str, list, dict, Headers or None

Returns

The converted headers.

Return type

Headers

Return type

Headers

Forms

Form parsers

class baguette.forms.Form(fields=None, files=None)[source]
classmethod parse(body, encoding='utf-8')[source]
Return type

Form

copy()[source]
Return type

Form

class baguette.forms.URLEncodedForm(fields=None, files=None)[source]
classmethod parse(body, encoding='utf-8')[source]
Return type

URLEncodedForm

class baguette.forms.MultipartForm(fields=None, files=None)[source]
classmethod parse(body, boundary, encoding='utf-8')[source]
Return type

MultipartForm

Fields

class baguette.forms.Field(name, values, encoding='utf-8')[source]
copy()[source]
Return type

Field

class baguette.forms.FileField(name, content, filename='', content_type=None, encoding='utf-8')[source]
property text

Union[str, bytes]

Type

rtype

copy()[source]
Return type

FileField

Rendering

Renderer

class baguette.rendering.Renderer(templates_directory='templates')[source]
async render(template_name, *args, **kwargs)[source]

Render

baguette.rendering.init(templates_directory='templates')[source]
async baguette.render()[source]

Routing

Routers

class baguette.router.Router(routes=None)[source]

Class for routing a Request to the correct Route.

Parameters

routes (Optional list of Route) – The routes to include directly.

add_route(handler, path, methods=None, name=None, defaults=None)[source]

Adds a route to the router.

Parameters
  • handler (Async callable) – The function/class that handles requests.

  • path (str) – The path that the route will be at.

  • methods (list of str) – The methods that the route can handle.

  • name (Optional str) – The name of the route.

  • defaults (Optional dict) – Default URL parameters to provide to the handler, if none in the URL.

Returns

The added route.

Return type

Route

Return type

Route

get(path, method)[source]

Gets the route for a path and a method.

Parameters
  • path (str) – The path of the request.

  • method (str) – The method of the request.

Returns

The correct route.

Return type

Route

Raises
Return type

Route

class baguette.router.WebsocketRouter(routes=None)[source]

Class for routing a websocket connection to the correct Websocket.

add_route(websocket, path, name=None)[source]
get(path)[source]
Return type

WebsocketRoute

Routes

class baguette.router.Route(path, name, handler, methods, defaults=None)[source]

Class for storing info about a route and setting up converters.

Parameters
  • path (str) – The path that the route will be at.

  • name (Optional str) – The name of the route.

  • handler (Async callable) – The function/class that handles requests.

  • methods (list of str) – The methods that the route can handle.

  • defaults (Optional dict) – Default URL parameters to provide to the handler, if none in the URL.

build_converters()[source]

Sets up converters for the route URL parameters.

Raises

ValueError – The converter type isn’t one of PARAM_CONVERTERS.

build_regex()[source]

Sets up the regex for route matching.

match(path)[source]

Returns whether the path matches the route regex.

Parameters

path (str) – The path to test.

Returns

The match, or None if no match was found.

Return type

Optional re.Match

Return type

Optional[Match]

convert(path)[source]

Converts the URL parameters from the path.

Parameters

path (str) – The path that has the parameters.

Returns

The converted parameters.

Return type

dict

Raises
Return type

Dict[str, Any]

class baguette.router.WebsocketRoute(path, name, websocket)[source]

Class for storing info about a websocket route.

Path parameters converters

class baguette.converters.StringConverter(length=None, allow_slash=False)[source]

Converter for string URL parameters.

Parameters
  • length (Optional int) – Required length of the string. Default: None

  • allow_slash (Optional bool) – Allow slashes in the string. Default: False

length

Required length of the string.

Type

Optional int

allow_slash

Allow slashes in the string.

Type

bool

REGEX

Regex for the route build_regex().

Type

str

convert(string)[source]

Converts the string of the URL parameter and validates the value.

Parameters

string (str) – URL parameter to convert.

Returns

Converted URL parameter.

Return type

str

Raises
class baguette.converters.PathConverter(allow_empty=False)[source]

Converter for string URL parameters.

Parameters

allow_empty (Optional bool) – Whether to allow empty paths. Default: False

allow_empty

Whether to allow empty paths.

Type

bool

REGEX

Regex for the route build_regex().

Type

str

convert(string)[source]

Converts the string of the URL parameter and validates the value.

Parameters

string (str) – URL parameter to convert.

Returns

Converted URL parameter.

Return type

str

Raises

ValueErrorallow_empty is True and the path is empty.

class baguette.converters.IntegerConverter(signed=False, min=None, max=None)[source]

Converter for integer URL parameters.

Parameters
  • signed (Optional bool) – Whether to accept integers starting with + or -. Default: False

  • min (Optional int) – Minimum value of the integer. Default: None

  • max (Optional int) – Maximum value of the integer. Default: None

signed

Whether to accept integers starting with + or -.

Type

bool

min

Minimum value of the integer.

Type

Optional int

max

Maximum value of the integer.

Type

Optional int

REGEX

Regex for the route build_regex().

Type

str

convert(string)[source]

Converts the string of the URL parameter and validates the value.

Parameters

string (str) – URL parameter to convert.

Returns

Converted URL parameter.

Return type

int

Raises
class baguette.converters.FloatConverter(signed=False, min=None, max=None, allow_infinity=False, allow_nan=False)[source]

Converter for float URL parameters.

Parameters
  • signed (Optional bool) – Whether to accept floats starting with + or -. Default: False

  • min (Optional float) – Minimum value of the float. Default: None

  • max (Optional float) – Maximum value of the float. Default: None

  • allow_infinity (Optional bool) – Whether to accept floats that are inf or -inf. Default: False

  • allow_nan (Optional bool) – Whether to accept floats that are NaN. Default: False

signed

Whether to accept floats starting with + or -.

Type

bool

min

Minimum value of the float.

Type

Optional float

max

Maximum value of the float.

Type

Optional float

allow_infinity

Whether to accept floats that are inf or -inf.

Type

bool

allow_nan

Whether to accept floats that are NaN.

Type

bool

REGEX

Regex for the route build_regex().

Type

str

convert(string)[source]

Converts the string of the URL parameter and validates the value.

Parameters

string (str) – URL parameter to convert.

Returns

Converted URL parameter.

Return type

float

Raises

HTTP Exceptions

Exceptions for HTTP status code over 400 (4xx client errors and 5xx server errors) from the http module.

Status code

Name

Exception class

Description

RFC Link

400

Bad Request

BadRequest

Bad request syntax or unsupported method.

RFC 7231#6.5.1

401

Unauthorized

Unauthorized

No permission – see authorization schemes.

RFC 7235#3.1

402

Payment Required

PaymentRequired

No payment – see charging schemes.

RFC 7231#6.5.2

403

Forbidden

Forbidden

Request forbidden – authorization will not help.

RFC 7231#6.5.3

404

Not Found

NotFound

Nothing matches the given URI.

RFC 7231#6.5.4

405

Method Not Allowed

MethodNotAllowed

Specified method is invalid for this resource.

RFC 7231#6.5.5

406

Not Acceptable

NotAcceptable

URI not available in preferred format.

RFC 7231#6.5.6

407

Proxy Authentication Required

ProxyAuthenticationRequired

You must authenticate with this proxy before proceeding.

RFC 7235#3.2

408

Request Timeout

RequestTimeout

Request timed out; try again later.

RFC 7231#6.5.7

409

Conflict

Conflict

Request conflict.

RFC 7231#6.5.8

410

Gone

Gone

URI no longer exists and has been permanently removed.

RFC 7231#6.5.9

411

Length Required

LengthRequired

Client must specify Content-Length header.

RFC 7231#6.5.10

412

Precondition Failed

PreconditionFailed

Precondition in headers is false.

RFC 7232#4.2

413

Request Entity Too Large

RequestEntityTooLarge

Entity is too large.

RFC 7231#6.5.11

414

Request-URI Too Long

RequestURITooLong

URI is too long.

RFC 7231#6.5.12

415

Unsupported Media Type

UnsupportedMediaType

Entity body in unsupported format.

RFC 7231#6.5.13

416

Requested Range Not Satisfiable

RequestedRangeNotSatisfiable

Cannot satisfy request range.

RFC 7233#4.4

417

Expectation Failed

ExpectationFailed

Expect condition could not be satisfied.

RFC 7231#6.5.14

418

I’m a Teapot

IMATeapot

Server refuses to brew coffee because it is a teapot (1998 April Fools’).

RFC 2324#2.3.2

421

Misdirected Request

MisdirectedRequest

Server is not able to produce a response.

RFC 7540#9.1.2

422

Unprocessable Entity

UnprocessableEntity

Server understands the content but was unable to process the contained instructions..

RFC 4918#11.2

423

Locked

Locked

Source or destination resource of a method is locked.

RFC 4918#11.3

424

Failed Dependency

FailedDependency

Request method could not be performed on the resource because the requested action depended on another action that failed.

RFC 4918#11.4

425

Too Early

TooEarly

Server is unwilling to risk processing a request that might be replayed.

RFC 8470#5.2

426

Upgrade Required

UpgradeRequired

Server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.

RFC 7231#6.5.15

428

Precondition Required

PreconditionRequired

Origin server requires the request to be conditional.

RFC 6585#3

429

Too Many Requests

TooManyRequests

User has sent too many requests in a given amount of time (“rate limiting”).

RFC 6585#4

431

Request Header Fields Too Large

RequestHeaderFieldsTooLarge

Server is unwilling to process the request because its header fields are too large.

RFC 6585#5

451

Unavailable For Legal Reasons

UnavailableForLegalReasons

Server is denying access to the resource as a consequence of a legal demand.

RFC 7725#3

500

Internal Server Error

InternalServerError

Server got itself in trouble.

RFC 7231#6.6.1

501

Not Implemented

NotImplemented

Server does not support this operation.

RFC 7231#6.6.2

502

Bad Gateway

BadGateway

Invalid responses from another server/proxy.

RFC 7231#6.6.3

503

Service Unavailable

ServiceUnavailable

Server cannot process the request due to a high load.

RFC 7231#6.6.4

504

Gateway Timeout

GatewayTimeout

Gateway server did not receive a timely response.

RFC 7231#6.6.5

505

HTTP Version Not Supported

HTTPVersionNotSupported

Cannot fulfill request.

RFC 7231#6.6.6

506

Variant Also Negotiates

VariantAlsoNegotiates

Server configuration error in which the chosen variant is itself configured to engage in content negotiation, so is not a proper negotiation endpoint.

RFC 2295#8.1

507

Insufficient Storage

InsufficientStorage

Method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.

RFC 4918#11.5

508

Loop Detected

LoopDetected

Server terminated an operation because it encountered an infinite loop while processing a request.

RFC 5842#7.2

510

Not Extended

NotExtended

Server terminated an operation because it encountered an infinite loop while processing a request.

RFC 2774#7

511

Network Authentication Required

NetworkAuthenticationRequired

Client needs to authenticate to gain network access.

RFC 6585#6

exception baguette.httpexceptions.HTTPException(status_code, name=None, description=None)[source]

Base class for HTTP exceptions.

status_code

HTTP status code.

Type

int

name

Name of the HTTP exception.

Type

str

description

Description of the HTTP exception.

Type

str

exception baguette.httpexceptions.BadRequest(name=None, description=None)[source]
exception baguette.httpexceptions.Unauthorized(name=None, description=None)[source]
exception baguette.httpexceptions.PaymentRequired(name=None, description=None)[source]
exception baguette.httpexceptions.Forbidden(name=None, description=None)[source]
exception baguette.httpexceptions.NotFound(name=None, description=None)[source]
exception baguette.httpexceptions.MethodNotAllowed(name=None, description=None)[source]
exception baguette.httpexceptions.NotAcceptable(name=None, description=None)[source]
exception baguette.httpexceptions.ProxyAuthenticationRequired(name=None, description=None)[source]
exception baguette.httpexceptions.RequestTimeout(name=None, description=None)[source]
exception baguette.httpexceptions.Conflict(name=None, description=None)[source]
exception baguette.httpexceptions.Gone(name=None, description=None)[source]
exception baguette.httpexceptions.LengthRequired(name=None, description=None)[source]
exception baguette.httpexceptions.PreconditionFailed(name=None, description=None)[source]
exception baguette.httpexceptions.RequestEntityTooLarge(name=None, description=None)[source]
exception baguette.httpexceptions.RequestURITooLong(name=None, description=None)[source]
exception baguette.httpexceptions.UnsupportedMediaType(name=None, description=None)[source]
exception baguette.httpexceptions.RequestedRangeNotSatisfiable(name=None, description=None)[source]
exception baguette.httpexceptions.ExpectationFailed(name=None, description=None)[source]
exception baguette.httpexceptions.IMATeapot(name=None, description=None)[source]
exception baguette.httpexceptions.MisdirectedRequest(name=None, description=None)[source]
exception baguette.httpexceptions.UnprocessableEntity(name=None, description=None)[source]
exception baguette.httpexceptions.Locked(name=None, description=None)[source]
exception baguette.httpexceptions.FailedDependency(name=None, description=None)[source]
exception baguette.httpexceptions.TooEarly(name=None, description=None)[source]
exception baguette.httpexceptions.UpgradeRequired(name=None, description=None)[source]
exception baguette.httpexceptions.PreconditionRequired(name=None, description=None)[source]
exception baguette.httpexceptions.TooManyRequests(name=None, description=None)[source]
exception baguette.httpexceptions.RequestHeaderFieldsTooLarge(name=None, description=None)[source]
exception baguette.httpexceptions.UnavailableForLegalReasons(name=None, description=None)[source]
exception baguette.httpexceptions.InternalServerError(name=None, description=None)[source]
exception baguette.httpexceptions.NotImplemented(name=None, description=None)[source]
exception baguette.httpexceptions.BadGateway(name=None, description=None)[source]
exception baguette.httpexceptions.ServiceUnavailable(name=None, description=None)[source]
exception baguette.httpexceptions.GatewayTimeout(name=None, description=None)[source]
exception baguette.httpexceptions.HTTPVersionNotSupported(name=None, description=None)[source]
exception baguette.httpexceptions.VariantAlsoNegotiates(name=None, description=None)[source]
exception baguette.httpexceptions.InsufficientStorage(name=None, description=None)[source]
exception baguette.httpexceptions.LoopDetected(name=None, description=None)[source]
exception baguette.httpexceptions.NotExtended(name=None, description=None)[source]
exception baguette.httpexceptions.NetworkAuthenticationRequired(name=None, description=None)[source]

Websocket

class baguette.Websocket(app, scope, receive, send)[source]

Base websocket class.

You usually only need to overwrite the on_connect(), on_message(), on_disconnect() and on_close() when subclassing.

async connect()[source]

Connects to the websocket.

Warning

This method must be called before handle_messages().

Returns

Whether the websocket is connected.

Return type

bool

Raises

RuntimeError – Websocket is already connected

Return type

bool

async accept(headers=None, subprotocol=None)[source]

Accepts the websocket connection.

If you want to accept with your own headers or subprotocol, call this in on_connect(). If you don’t, it will be called in connect() if on_connect() doesn’t error.

Parameters
  • headers (list of (str, str) tuples, dict or Headers) – The headers to include in the accept message. Default: No headers.

  • subprotocol (Optional str) – The subprotocol to use in the websocket. Default: None

async receive()[source]

Receives a message from the websocket.

Note

You don’t need to call this method in on_message().

Returns

The received message

Return type

str

Return type

str

async send(message)[source]

Sends a message to the websocket.

Parameters

message (str or bytes) – The message to send to the websocket.

Raises

TypeError – The message isn’t of type str or bytes.

async send_json(data)[source]
async close(code=1000, reason='')[source]

Closes the websocket connection.

Parameters
  • code (Optional int) – The status code to close the websocket connection with. Default: 1000.

  • reason (Optional str) – The reason to close the websocket connection with. Default: "".

Raises

RuntimeError – The connection is already closed.

async handle_messages()[source]

Handles the received messages, calls on_message() and puts them in queue.

Raises

RuntimeError – The websocket isn’t connected.

dispatch(event, *args, **kwargs)[source]

Dispatches an event to the correct handler.

async main()[source]

Runs in a loop until the websocket is closed.

async on_connect()[source]

Called on websocket connection.

If this function raises an exception, the websocket connection wont be accepted.

async on_message(message)[source]

Called on every websocket message.

Parameters

message (str) – The websocket message

async on_disconnect(code)[source]

Called on websocket disconnection.

If the server closed the connection, this is called before on_close().

Parameters

code (int) – The websocket close status code.

async on_close(code, reason)[source]

Called when the websocket is closed by the server.

Parameters
  • code (int) – The websocket close status code.

  • reason (str) – The reason why the websocket is closed.

async on_error(event_name, error, *args, **kwargs)[source]

Called when an event errors.

Parameters
  • event_name (str) – The event that raised the error.

  • error (str) – The error that was raised.

  • *args (tuple) – The arguments of the event.

  • **kwargs (dict) – The keyword arguments of the event.

Middlewares

Base middleware

class baguette.Middleware(next_middleware, config)[source]

Base class for middlewares.

Parameters
  • next_middleware (Middleware) – The next middleware to call.

  • config (Config) – The application configuration.

next_middleware

The next middleware to call.

Type

Middleware

nexte

The next middleware to call. (Alias for next_middleware)

Type

Middleware

config

The application configuration.

Type

Config

async __call__(request)[source]

Call the middleware, executed at every request.

Parameters

request (Request) – The request to handle.

Returns

The handled response.

Return type

Response

Return type

Response

Included middlewares

class baguette.middlewares.DefaultHeadersMiddleware(next_middleware, config)[source]

Middleware to add the app.config.default_headers to every response.

class baguette.middlewares.ErrorMiddleware(next_middleware, config)[source]

Middleware to handle errors in request handling. Can be HTTPException or other exceptions.

If app.config.debug and the HTTP status code is higher than 500, then the error traceback is included.

Testing

class baguette.TestClient(app, default_headers=None)[source]

Test client for a Baguette application.

This class works like a requests.Session.

Parameters
  • app (Baguette) – Application tho send the test requests to.

  • default_headers (list of (str, str) tuples, dict or Headers) – Default headers to include in every request. Default: No headers.

app

Application tho send the test requests to.

Type

Baguette

default_headers

Default headers included in every request.

Type

list of (str, str) tuples, dict or Headers

async request(method, path, *, params=None, body=None, json=None, headers=None)[source]

Creates and sends a request to app.

Parameters
  • method (str) – The HTTP method for the request.

  • path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async get(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a GET request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async head(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a HEAD request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async post(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a POST request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async put(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a PUT request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async delete(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a DELETE request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async connect(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a CONNECT request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async options(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a OPTIONS request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async trace(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a TRACE request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

async patch(path, *, params=None, body=None, json=None, headers=None)[source]

Sends a PATCH request to app.

Parameters

path (str) – The path of the request.

Keyword Arguments
  • params (str or dict with str keys and str or list values) – The parameters to send in the querystring.

  • body (str or bytes) – The data to send in the request body.

  • json (Anything JSON serializable) – The JSON data to send in the request body.

  • headers (list of (str, str) tuples, dict or Headers) – The headers to send in the request.

Return type

Response

method = 'PATCH'

Type:    str

Utils

baguette.utils.get_encoding_from_content_type(content_type)[source]

Returns encodings from given Content-Type Header.

baguette.utils.get_encoding_from_headers(headers)[source]

Returns encodings from given HTTP Headers.

baguette.utils.file_path_to_path(*paths)[source]

Convert a list of paths into a pathlib.Path.

Return type

Path

baguette.utils.safe_join(directory, *paths)[source]

Safely join the paths to the known directory to return a full path.

Raises

NotFound – If the full path does not share a commonprefix with the directory.

Return type

Path

baguette.utils.split_on_first(text, sep)[source]
Return type

Tuple[str, str]

baguette.utils.import_from_string(string)[source]
baguette.utils.address_to_str(address)[source]

Converts a (host, port) tuple into a host:port string.

Return type

str

baguette.utils.to_bytes(str_or_bytes, encoding='utf-8')[source]

Makes sure that the argument is a bytes.

Parameters
  • str_or_bytes (str or bytes) – The argument to convert to a bytes.

  • encoding (Optional str) – The string encoding. Default: "utf-8"

Returns

The converted argument.

Return type

bytes

Raises

TypeError – The argument isn’t a str or a bytes.

Return type

bytes

baguette.utils.to_str(str_or_bytes, encoding='utf-8')[source]

Makes sure that the argument is a str.

Parameters
  • str_or_bytes (str or bytes) – The argument to convert to a bytes.

  • encoding (Optional str) – The bytes encoding. Default: "utf-8"

Returns

The converted argument.

Return type

str

Raises

TypeError – The argument isn’t a str or a bytes.

Return type

str