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

FlaskJSONProvider

Custom JSONProvider which adds connexion defaults on top of Flask's

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.

  • 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

__call__(self, scope, receive, send)

ASGI interface. Calls the middleware wrapped around the wsgi app.

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

class connexion.apps.flask_app.FlaskJSONProvider(app: flask.app.Flask)

Bases: flask.json.provider.DefaultJSONProvider

Custom JSONProvider which adds connexion defaults on top of Flask’s

ensure_ascii = True

Replace non-ASCII characters with escape sequences. This may be more compatible with some clients, but can be disabled for better performance and size.

sort_keys = True

Sort the keys in any serialized dicts. This may be useful for some caching situations, but can be disabled for better performance. When enabled, keys must all be strings, they are not converted before sorting.

compact :bool | None

If True, or None out of debug mode, the response() output will not add indentation, newlines, or spaces. If False, or None in debug mode, it will use a non-compact representation.

mimetype = application/json

The mimetype set in response().

default(self, o)
dumps(self, obj: Any, **kwargs: Any) str

Serialize data as JSON to a string.

Keyword arguments are passed to json.dumps(). Sets some parameter defaults from the default, ensure_ascii, and sort_keys attributes.

Parameters:
  • obj – The data to serialize.

  • kwargs – Passed to json.dumps().

loads(self, s: str | bytes, **kwargs: Any) Any

Deserialize data as JSON from a string or bytes.

Parameters:
  • s – Text or UTF-8 bytes.

  • kwargs – Passed to json.loads().

response(self, *args: Any, **kwargs: Any) flask.wrappers.Response

Serialize the given arguments as JSON, and return a Response object with it. The response mimetype will be “application/json” and can be changed with mimetype.

If compact is False or debug mode is enabled, the output will be formatted to be easier to read.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

Parameters:
  • args – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs – Treat as a dict to serialize.

dump(self, obj: Any, fp: IO[str], **kwargs: Any) None

Serialize data as JSON and write to a file.

Parameters:
  • obj – The data to serialize.

  • fp – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.

  • kwargs – May be passed to the underlying JSON library.

load(self, fp: IO[AnyStr], **kwargs: Any) Any

Deserialize data as JSON read from a file.

Parameters:
  • fp – A file opened for reading text or UTF-8 bytes.

  • kwargs – May be passed to the underlying JSON library.

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