connexion.apps.flask_app

Module Contents

Classes

FlaskApp

FlaskJSONEncoder

The default Flask JSON encoder. This one extends the default

Attributes

logger

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

Bases: connexion.apps.abstract.AbstractApp

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

static common_error_handler(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, **options)

Runs the application on a local development server. :param host: the host interface to bind on. :type host: str :param port: port to listen to :type port: int :param server: which wsgi server to use :type server: str | None :param debug: include debugging information :type debug: bool :param 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(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: flask.json.JSONEncoder

The default Flask JSON encoder. This one extends the default encoder by also supporting datetime, UUID, dataclasses, and Markup objects.

datetime objects are serialized as RFC 822 datetime strings. This is the same as the HTTP date format.

In order to support more data types, override the default() method.

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

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    return JSONEncoder.default(self, o)
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)