API Reference

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

Application

class baguette.Baguette

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: :class:`Config`

The configuration of the app.

router: :class:`~baguette.router.Router`

The URL router of the app.

renderer: :class:`~baguette.rendering.Renderer`

Class that renders the templates.

debug: :class:`bool`

Whether the application is running in debug mode.

default_headers: :class:`Headers`

Default headers included in every response.

static_url_path: :class:`str`

URL path for the static file handler.

static_directory: :class:`str`

Path to the folder containing static files.

templates_directory: :class:`str`

Path to the folder containing the HTML templates.

error_response_type: :class:`str`

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

error_include_description: :class:`bool`

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

middlewares: :class:`list` of middlewares

The middlewares of the application.

async startup()

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()

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)

Handles a request and returns a response.

Parameters

request (Request) – The request to handle.

Returns

A response.

Return type

Response

async dispatch(request)

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.

add_route(path, handler, methods=None, name=None, defaults=None)

Adds a route to the application router.

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

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

  • 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

route(path, methods=None, name=None, defaults=None)

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=[])

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)

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)

Removes a middleware from the middleware stack.

Parameters

middleware (Middleware) – The middleware to remove.

New in version 0.3.0.

middleware(index=1)

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.

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')

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

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: :class:`bool`

Whether the application is running in debug mode.

default_headers: :class:`Headers`

Default headers included in every response.

static_url_path: :class:`str`

URL path for the static file handler.

static_directory: :class:`str`

Path to the folder containing static files.

templates_directory: :class:`str`

Path to the folder containing the HTML templates.

error_response_type: :class:`str`

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

error_include_description: :class:`bool`

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

classmethod from_json(filename)

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

classmethod from_class(class_or_module_name)

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

View

class baguette.View

Base view class.

Parameters

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

app: :class:`Baguette`

The app that the view was added to.

methods: :class:`list` of :class:`str`

The methods that this view can handle.

async dispatch(request, **kwargs)

Dispatch the request to the right method handler.

Request

class baguette.Request

Request class that is passed to the view functions.

Parameters
app: ASGI App

The application that handles the request.

http_version: :class:`str`

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

asgi_version: :class:`str`

The ASGI specification version used.

headers: :class:`Headers`

The HTTP headers included in the request.

method: :class:`str`

The HTTP method name, uppercased.

scheme: :class:`str`

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

path: :class:`str`

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.

querystring: :class:`dict` with :class:`str` keys and :class:`list` of :class:`str` values

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

server: :class:`tuple` of (:class:`str`, :class:`int`)

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.

client: :class:`tuple` of (:class:`str`, :class:`int`)

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

content_type: :class:`str`

Content type of the response body.

encoding: :class:`str`

Encoding of the response body.

async raw_body()

Gets the raw request body in bytes.

Returns

Raw request body.

Return type

bytes

async body()

Gets the request body in str.

Returns

Request body.

Return type

str

async json()

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.

async form(include_querystring=False)

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

set_raw_body(raw_body)

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)

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)

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)

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

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: :class:`int`

The HTTP status code of the reponse.

headers: :class:`Headers`

The headers of the reponse.

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a 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.

Plain Text Response

class baguette.PlainTextResponse

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: :class:`int`

The HTTP status code of the reponse.

headers: :class:`Headers`

The headers of the reponse.

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a 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.

HTML Response

class baguette.HTMLResponse

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: :class:`int`

The HTTP status code of the reponse.

headers: :class:`Headers`

The headers of the reponse.

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a 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.

JSON Response

class baguette.JSONResponse

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: 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

status_code: :class:`int`

The HTTP status code of the reponse.

headers: :class:`Headers`

The headers of the reponse.

property json

The request JSON data.

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a 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.

Empty Response

class baguette.EmptyResponse

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: :class:`int`

The HTTP status code of the reponse.

headers: :class:`Headers`

The headers of the reponse.

property body

The reponse body.

Note

Setting the request body also accepts a bytes but accessing the request body will always return a 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.

Redirect Response

class baguette.RedirectResponse

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: :class:`int`

The HTTP status code of the reponse.

headers: :class:`Headers`

The headers of the reponse.

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.

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.

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

baguette.redirect()

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

File Response

class baguette.FileResponse

Make Response

baguette.make_response()

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

baguette.make_error_response()

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

Headers

Headers class

class baguette.Headers

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)

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()

Returns an iterator over the headers names.

Returns

Iterator over the headers names.

Return type

Iterator of str

items()

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()

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()

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

Forms

Form parsers

class baguette.forms.Form
classmethod parse(body, encoding='utf-8')
copy()
class baguette.forms.URLEncodedForm
classmethod parse(body, encoding='utf-8')
class baguette.forms.MultipartForm
classmethod parse(body, boundary, encoding='utf-8')

Fields

class baguette.forms.Field
copy()
class baguette.forms.FileField
property text
copy()

Rendering

Renderer

class baguette.rendering.Renderer
async render(template_name, *args, **kwargs)

Render

baguette.rendering.init()
async baguette.render()

Routing

Router

class baguette.router.Router
add_route(handler, path, methods=None, name=None, defaults=None)
get(path, method)

Route

class baguette.router.Route
build_converters()
build_regex()
match(path)
convert(path)

Path parameters converters

class baguette.converters.StringConverter

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: Optional :class:`int`

Required length of the string.

allow_slash: :class:`bool`

Allow slashes in the string.

REGEX: :class:`str`

Regex for the route build_regex().

convert(string)

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

Converter for string URL parameters.

Parameters

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

allow_empty: :class:`bool`

Whether to allow empty paths.

REGEX: :class:`str`

Regex for the route build_regex().

convert(string)

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

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: :class:`bool`

Whether to accept integers starting with + or -.

min: Optional :class:`int`

Minimum value of the integer.

max: Optional :class:`int`

Maximum value of the integer.

REGEX: :class:`str`

Regex for the route build_regex().

convert(string)

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

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: :class:`bool`

Whether to accept floats starting with + or -.

min: Optional :class:`float`

Minimum value of the float.

max: Optional :class:`float`

Maximum value of the float.

allow_infinity: :class:`bool`

Whether to accept floats that are inf or -inf.

allow_nan: :class:`bool`

Whether to accept floats that are NaN.

REGEX: :class:`str`

Regex for the route build_regex().

convert(string)

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)

Base class for HTTP exceptions.

status_code: :class:`int`

HTTP status code.

name: :class:`str`

Name of the HTTP exception.

description: :class:`str`

Description of the HTTP exception.

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

Middlewares

Base middleware

class baguette.Middleware

Base class for middlewares.

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

  • config (Config) – The application configuration.

next_middleware: :class:`Middleware`

The next middleware to call.

nexte: :class:`Middleware`

The next middleware to call. (Alias for next_middleware)

config: :class:`Config`

The application configuration.

async __call__(request)

Call the middleware, executed at every request.

Parameters

request (Request) – The request to handle.

Returns

The handled response.

Return type

Response

Included middlewares

class baguette.middlewares.DefaultHeadersMiddleware(next_middleware, config)

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

class baguette.middlewares.ErrorMiddleware(next_middleware, config)

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

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: :class:`Baguette`

Application tho send the test requests to.

default_headers: :class:`list` of ``(str, str)`` tuples, :class:`dict` or :class:`Headers`

Default headers included in every request.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

method = 'PATCH'

Utils

baguette.utils.get_encoding_from_content_type(content_type)

Returns encodings from given Content-Type Header.

baguette.utils.get_encoding_from_headers(headers)

Returns encodings from given HTTP Headers.

baguette.utils.file_path_to_path(*paths)

Convert a list of paths into a pathlib.Path.

baguette.utils.safe_join(directory, *paths)

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.

baguette.utils.split_on_first(text, sep)
baguette.utils.import_from_string(string)
baguette.utils.address_to_str(address)

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

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

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.

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

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.