connexion.apps.flask_app

This module defines a FlaskApp, a Connexion application to wrap a Flask application.

Module Contents

Classes

FlaskApp

param extra_files:

additional files to be watched by the reloader, defaults to the swagger specs of added apis

FlaskJSONEncoder

The default JSON encoder. Handles extra types compared to the

NumberConverter

Flask converter for OpenAPI number type

IntegerConverter

Flask converter for OpenAPI integer type

Attributes

logger

connexion.apps.flask_app.logger
class connexion.apps.flask_app.FlaskApp(import_name, server='flask', extra_files=None, **kwargs)

Bases: connexion.apps.abstract.AbstractApp

Parameters:

extra_files (list[str | pathlib.Path], optional) – additional files to be watched by the reloader, defaults to the swagger specs of added apis

See AbstractApp for additional parameters.

create_app(self)

Creates the user framework application

get_root_path(self)

Gets the root path of the user framework application

set_errors_handlers(self)

Sets all errors handlers of the user framework application

common_error_handler(self, exception)
add_api(self, specification, **kwargs)

Adds an API to the application based on a swagger file or API dict

Parameters:
  • specification (pathlib.Path or str or dict) – swagger file with the specification | specification dict

  • base_path (str | None) – base path where to add this api

  • arguments (dict | None) – api version specific arguments to replace on the specification

  • auth_all_paths (bool) – whether to authenticate not defined paths

  • validate_responses (bool) – True enables validation. Validation errors generate HTTP 500 responses.

  • strict_validation (bool) – True enables validation on invalid request parameters

  • resolver (Resolver | types.FunctionType) – Operation resolver.

  • resolver_error (int | None) – If specified, turns ResolverError into error responses with the given status code.

  • pythonic_params (bool) – When True CamelCase parameters are converted to snake_case

  • options (dict | None) – New style options dictionary.

  • pass_context_arg_name (str | None) – Name of argument in handler functions to pass request context to.

  • validator_map (dict) – map of validators

Return type:

AbstractAPI

add_error_handler(self: int, error_code: types.FunctionType, function) None
run(self, port=None, server=None, debug=None, host=None, extra_files=None, **options)

Runs the application on a local development server.

Parameters:
  • host (str) – the host interface to bind on.

  • port (int) – port to listen to

  • server (str | None) – which wsgi server to use

  • debug (bool) – include debugging information

  • extra_files (Iterable[str | pathlib.Path]) – additional files to be watched by the reloader.

  • options – options to be forwarded to the underlying server

add_url_rule(self, rule, endpoint=None, view_func=None, **options)

Connects a URL rule. Works exactly like the route decorator. If a view_func is provided it will be registered with the endpoint.

Basically this example:

@app.route('/')
def index():
    pass

Is equivalent to the following:

def index():
    pass
app.add_url_rule('/', 'index', index)

If the view_func is not provided you will need to connect the endpoint to a view function like so:

app.view_functions['index'] = index

Internally`route` invokes add_url_rule so if you want to customize the behavior via subclassing you only need to change this method.

Parameters:
  • rule (str) – the URL rule as string

  • endpoint (str) – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint

  • view_func (types.FunctionType) – the function to call when serving a request to the provided endpoint

  • options – the options to be forwarded to the underlying werkzeug.routing.Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD).

route(self, rule, **options)

A decorator that is used to register a view function for a given URL rule. This does the same thing as add_url_rule but is intended for decorator usage:

@app.route('/')
def index():
    return 'Hello World'
Parameters:
  • rule (str) – the URL rule as string

  • endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint

  • options – the options to be forwarded to the underlying werkzeug.routing.Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD).

__call__(self, environ, start_response)

Makes the class callable to be WSGI-compliant. As Flask is used to handle requests, this is a passthrough-call to the Flask callable class. This is an abstraction to avoid directly referencing the app attribute from outside the class and protect it from unwanted modification.

class connexion.apps.flask_app.FlaskJSONEncoder(**kwargs)

Bases: flask.json.JSONEncoder

The default JSON encoder. Handles extra types compared to the built-in json.JSONEncoder.

  • datetime.datetime and datetime.date are serialized to RFC 822 strings. This is the same as the HTTP date format.

  • decimal.Decimal is serialized to a string.

  • uuid.UUID is serialized to a string.

  • dataclasses.dataclass is passed to dataclasses.asdict().

  • Markup (or any object with a __html__ method) will call the __html__ method to get a string.

Assign a subclass of this to flask.Flask.json_encoder or flask.Blueprint.json_encoder to override the default.

Deprecated since version 2.2: Will be removed in Flask 2.3. Use app.json instead.

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

item_separator = ,
key_separator = :
default(self, o)

Convert o to a JSON serializable type. See json.JSONEncoder.default(). Python does not support overriding how basic types like str or list are serialized, they are handled before this method.

encode(self, o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(self, o, _one_shot=False)

Encode the given object and yield each string representation as available.

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
class connexion.apps.flask_app.NumberConverter(map: werkzeug.routing.map.Map, *args: Any, **kwargs: Any)

Bases: werkzeug.routing.BaseConverter

Flask converter for OpenAPI number type

regex = [+-]?[0-9]*(\.[0-9]*)?
weight = 100
part_isolating = True
to_python(self, value)
to_url(self, value: Any) str
class connexion.apps.flask_app.IntegerConverter(map: werkzeug.routing.map.Map, *args: Any, **kwargs: Any)

Bases: werkzeug.routing.BaseConverter

Flask converter for OpenAPI integer type

regex = [+-]?[0-9]+
weight = 100
part_isolating = True
to_python(self, value)
to_url(self, value: Any) str