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 exceptmiddlewares. Default: seeConfigdefaults.debug (
bool) – Whether to run the application in debug mode. Default:False.default_headers (
listof(str, str)tuples,dictorHeaders) – 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 isTrue, this will also beTrue. Default:True.middlewares (
listof 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 beTrue.
-
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.
-
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
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 (
listofstr) – 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(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
listofstr) – 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.endpointtoBaguette.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 (
listofMiddleware) – 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 afterErrorMiddleware)
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 afterErrorMiddleware)
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
uvicorninstalled 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.1port (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
listof(str, str)tuples,dictorHeaders) – 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 thewebsocketsandwsprotopackages 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:Nonelog_config (Optional
dictConfig()formats,.jsonand.yamlfile paths orfileConfig()formats.) – Logging configuration. Default: uvicorn.config.LOGGING_CONFIGlog_level (
"critical","error","warning","info","debug"or"trace") – Application log level. Default:"info"access_log (Optional
bool) – Whether to log every request. Default:Trueuse_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 iflog_configis given. Default:Noneworkers (Optional
int) – Number of worker processes to use. Default:WEB_CONCURRENCYenvironment variable if available, or1proxy_headers (Optional
bool) – Whether to enableX-Forwarded-Proto,X-Forwarded-ForandX-Forwarded-Portheaders to populate remote address info. Restricted to only trusting connecting IPs in theforwarded_allow_ipsparameter. Default:Trueforwarded_allow_ips (Optional
str) – Comma separated list of IPs to trust with proxy headers. A wildcard"*"means always trust. Default:FORWARDED_ALLOW_IPSenvironment variable if available, or127.0.0.1ssl_keyfile (Optional
str(path to file)) – SSL key file Default:Nonessl_certfile (Optional
str(path to file)) – SSL certificate file Default:Nonessl_keyfile_password (Optional
str) – Password to decrypt the ssl key Default:Nonessl_version (Optional
int) – SSL version to use. Seesslmodule. Default:ssl.PROTOCOL_TLSssl_cert_reqs (Optional
int) – Whether client certificate is required. One ofssl.VerifyModevalues, a constant of thesslmodule that starts withCERT_. Default:ssl.CERT_NONEssl_ca_certs (Optional
str(path to file)) – CA certificates file Default:Nonessl_ciphers (Optional
str) – Ciphers to use. Seesslmodule. Default:"TLSv1"
Note
Doesn’t support reloading, if you want reloading, run the application from the console with uvicorn and add the
--reloadflag.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 (
listof(str, str)tuples,dictorHeaders) – 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 isTrue, this will also beTrue. 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 beTrue.
-
classmethod
from_json(filename)¶ Loads the configuration from a JSON file.
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.
scope (
dict) – ASGI scope of the request. See HTTP scope ASGI specifications.receive (Asynchronous callable) – Awaitable callable that will yield a new event dictionary when one is available. See applications ASGI specifications.
-
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
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
400status code.
-
async
form(include_querystring=False)¶ Parses the request body as form data.
-
set_raw_body(raw_body)¶ Sets the raw body of the request.
-
set_body(body)¶ Sets the request body.
Responses¶
Base Response¶
Plain Text Response¶
HTML Response¶
JSON Response¶
-
class
baguette.JSONResponse¶ JSON response class.
- Parameters
-
JSON_ENCODER: JSON encoder¶ The JSON encoder to use in
json.dumps()with theclskeyword 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.
-
property
raw_body¶ The reponse raw body.
Empty Response¶
Redirect Response¶
-
class
baguette.RedirectResponse¶ Redirect response class.
- Parameters
location (
strorbytes) – The location to redirect the request to.status_code (
int) – Status code of the redirect response. Default:301.headers (
listof(str, str)tuples,dictorHeaders) – 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.
-
property
raw_body¶ The reponse raw body.
There’s an alias to create this class, it’s the redirect() function.
-
baguette.redirect()¶ Redirect the request to location.
- Parameters
location (
strorbytes) – The location to redirect the request to.status_code (
int) – Status code of the redirect response. Default:301.headers (
listof(str, str)tuples,dictorHeaders) – 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
Make Response¶
-
baguette.make_error_response()¶ Convert an
HTTPExceptionto aResponse.- 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
ValueError –
type_isn’t one of: ‘plain’, ‘json’, ‘html’.- Returns
Response that describes the error.
- Return type
Headers¶
Headers class¶
-
class
baguette.Headers¶ Headers implementation for handling
strorbytesnames and values.Tip
Use
make_headers()to easily make a header from alistor adict.-
get(name, default=None)¶ Gets a header from its name. If not found, returns
default.
-
keys()¶ Returns an iterator over the headers names.
- Returns
Iterator over the headers names.
- Return type
Iterator of
str
-
Rendering¶
Routing¶
Router¶
Path parameters converters¶
-
class
baguette.converters.StringConverter¶ Converter for string URL parameters.
- Parameters
-
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
- Raises
ValueError –
lengthis specified and the URL parameter has a different length thanlength.ValueError –
allow_slashisFalseand the URL parameter contains slashes.
-
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
- Raises
ValueError –
allow_emptyisTrueand the path is empty.
-
class
baguette.converters.IntegerConverter¶ Converter for integer URL parameters.
- Parameters
-
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
- Raises
ValueError –
signedisFalseand the URL parameter starts with+or-.ValueError – Couldn’t convert the URL parameter to an integer.
ValueError –
minis specified and the URL parameter is lower thenmin.ValueError –
maxis specified and the URL parameter is higher thenmax.
-
class
baguette.converters.FloatConverter¶ Converter for float URL parameters.
- Parameters
signed (Optional
bool) – Whether to accept floats starting with+or-. Default:Falsemin (Optional
float) – Minimum value of the float. Default:Nonemax (Optional
float) – Maximum value of the float. Default:Noneallow_infinity (Optional
bool) – Whether to accept floats that areinfor-inf. Default:Falseallow_nan (Optional
bool) – Whether to accept floats that areNaN. 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
infor-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
- Raises
ValueError –
signedisFalseand the URL parameter starts with+or-.ValueError – Couldn’t convert the URL parameter to an float.
ValueError –
minis specified and the URL parameter is lower thenmin.ValueError –
maxis specified and the URL parameter is higher thenmax.ValueError –
allow_infinityisFalseand the URL parameter isinfor-inf.ValueError –
allow_nanisFalseand the URL parameter isnan.
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 |
Bad request syntax or unsupported method. |
||
401 |
Unauthorized |
No permission – see authorization schemes. |
||
402 |
Payment Required |
No payment – see charging schemes. |
||
403 |
Forbidden |
Request forbidden – authorization will not help. |
||
404 |
Not Found |
Nothing matches the given URI. |
||
405 |
Method Not Allowed |
Specified method is invalid for this resource. |
||
406 |
Not Acceptable |
URI not available in preferred format. |
||
407 |
Proxy Authentication Required |
You must authenticate with this proxy before proceeding. |
||
408 |
Request Timeout |
Request timed out; try again later. |
||
409 |
Conflict |
Request conflict. |
||
410 |
Gone |
URI no longer exists and has been permanently removed. |
||
411 |
Length Required |
Client must specify Content-Length header. |
||
412 |
Precondition Failed |
Precondition in headers is false. |
||
413 |
Request Entity Too Large |
Entity is too large. |
||
414 |
Request-URI Too Long |
URI is too long. |
||
415 |
Unsupported Media Type |
Entity body in unsupported format. |
||
416 |
Requested Range Not Satisfiable |
Cannot satisfy request range. |
||
417 |
Expectation Failed |
Expect condition could not be satisfied. |
||
418 |
I’m a Teapot |
Server refuses to brew coffee because it is a teapot (1998 April Fools’). |
||
421 |
Misdirected Request |
Server is not able to produce a response. |
||
422 |
Unprocessable Entity |
Server understands the content but was unable to process the contained instructions.. |
||
423 |
Locked |
Source or destination resource of a method is locked. |
||
424 |
Failed Dependency |
Request method could not be performed on the resource because the requested action depended on another action that failed. |
||
425 |
Too Early |
Server is unwilling to risk processing a request that might be replayed. |
||
426 |
Upgrade Required |
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. |
||
428 |
Precondition Required |
Origin server requires the request to be conditional. |
||
429 |
Too Many Requests |
User has sent too many requests in a given amount of time (“rate limiting”). |
||
431 |
Request Header Fields Too Large |
Server is unwilling to process the request because its header fields are too large. |
||
451 |
Unavailable For Legal Reasons |
Server is denying access to the resource as a consequence of a legal demand. |
||
500 |
Internal Server Error |
Server got itself in trouble. |
||
501 |
Not Implemented |
Server does not support this operation. |
||
502 |
Bad Gateway |
Invalid responses from another server/proxy. |
||
503 |
Service Unavailable |
Server cannot process the request due to a high load. |
||
504 |
Gateway Timeout |
Gateway server did not receive a timely response. |
||
505 |
HTTP Version Not Supported |
Cannot fulfill request. |
||
506 |
Variant Also Negotiates |
Server configuration error in which the chosen variant is itself configured to engage in content negotiation, so is not a proper negotiation endpoint. |
||
507 |
Insufficient Storage |
Method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. |
||
508 |
Loop Detected |
Server terminated an operation because it encountered an infinite loop while processing a request. |
||
510 |
Not Extended |
Server terminated an operation because it encountered an infinite loop while processing a request. |
||
511 |
Network Authentication Required |
Client needs to authenticate to gain network access. |
-
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.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.InternalServerError(name=None, description=None)¶
-
exception
baguette.httpexceptions.NotImplemented(name=None, description=None)¶
-
exception
baguette.httpexceptions.BadGateway(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.
Included middlewares¶
-
class
baguette.middlewares.DefaultHeadersMiddleware(next_middleware, config)¶ Middleware to add the
app.config.default_headersto every response.
-
class
baguette.middlewares.ErrorMiddleware(next_middleware, config)¶ Middleware to handle errors in request handling. Can be
HTTPExceptionor other exceptions.If
app.config.debugand the HTTP status code is higher than 500, then the error traceback is included.
Testing¶
-
class
baguette.TestClient¶ Test client for a
Baguetteapplication.This class works like a
requests.Session.- Parameters
-
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
- Keyword Arguments
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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
-
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 ahost:portstring.