Index: buildhelpers/codegen/templates/__init__model.mustache
===================================================================
--- buildhelpers/codegen/templates/__init__model.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/__init__model.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,7 @@
+# coding: utf-8
+
+# flake8: noqa
+from __future__ import absolute_import
+# import models into model package
+{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}{{/model}}
+{{/models}}
Index: buildhelpers/codegen/templates/__init__test.mustache
===================================================================
--- buildhelpers/codegen/templates/__init__test.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/__init__test.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,67 @@
+import logging
+
+import flask
+import connexion
+from flask_cors import CORS
+from flask_testing import TestCase
+from flask_mail import Mail
+from sqlalchemy.event import listen
+from celery import Celery
+import tempfile
+import os
+from PIL import Image
+import shutil
+
+from {{packageName}}.encoder import JSONEncoder
+from {{packageName}}_impl.database.Model import (
+    db, db_setup, load_spatialite
+)
+from {{packageName}}_impl.tests import db_test_setup
+
+class BaseTestCase(TestCase):
+	def create_app(self):
+		logging.getLogger('connexion.operation').setLevel('ERROR')
+		app = connexion.App(__name__, specification_dir='../openapi/')
+		application = app.app
+		CORS(application)
+		mail = Mail()
+		application.json_encoder = JSONEncoder
+		app.add_api('openapi.yaml')
+
+		application.config.from_object('{{packageName}}_impl.Config.TestingConfig')
+		application.template_folder = os.path.join(os.path.dirname(__file__), '../../mapservice_impl/templates')
+		celery = Celery(__name__, broker=application.config['CELERY_BROKER_URL'])
+		celery.config_from_object(application.config)
+		mail.init_app(application)
+		db.init_app(application)
+		application.app_context().push()
+		
+		self._create_test_tile(application)
+		
+		return application
+
+	def setUp(self):
+		listen(db.engine, 'connect', load_spatialite)
+		db.drop_all()
+		# create the tables whether the database already exists or not
+		db_setup(True)
+		self.db_content = db_test_setup.DatabaseContent()
+		self.db_content.setup()
+        
+	def tearDown(self):
+		db.session.remove()
+		db.drop_all()
+		shutil.rmtree(self.tiles_cache)
+
+	def _create_test_tile(self, application):
+		self.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests')
+		application.config['TILES_CACHE_PATH'] = self.tiles_cache
+		
+		tile_path = os.path.join(self.tiles_cache, '100_100/256/15/17298/')
+		os.makedirs(tile_path)
+		img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))
+		img.save(os.path.join(tile_path, "21435.png"), "PNG")
+		
+	def check_key(self, key, value, data):
+		assert key in data, "{} not in data {}".format(key, data)
+		assert data[key] == value, "{} = {}".format(value, data[key])
Index: buildhelpers/codegen/templates/__main__.mustache
===================================================================
--- buildhelpers/codegen/templates/__main__.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/__main__.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,19 @@
+{{#supportPython2}}
+#!/usr/bin/env python
+{{/supportPython2}}
+{{^supportPython2}}
+#!/usr/bin/env python3
+{{/supportPython2}}
+
+import os
+
+from {{packageName}}_impl import (
+    app, application, mail, celery, setup_app, config_object
+)
+
+def main():
+	setup_app('{{appName}}', config_object, template_folder = os.path.join(os.path.dirname(__file__), 'templates'))
+	app.run(host=application.config.get("HOST", "localhost"), port=application.config.get("PORT", {{serverPort}}))
+
+if __name__ == '__main__':
+	main()
Index: buildhelpers/codegen/templates/base_model_.mustache
===================================================================
--- buildhelpers/codegen/templates/base_model_.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/base_model_.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,73 @@
+import pprint
+
+import six
+{{^supportPython2}}
+import typing
+{{/supportPython2}}
+
+from {{packageName}} import util
+{{^supportPython2}}
+
+T = typing.TypeVar('T')
+{{/supportPython2}}
+
+
+class Model(object):
+    # openapiTypes: The key is attribute name and the
+    # value is attribute type.
+    openapi_types = {}
+
+    # attributeMap: The key is attribute name and the
+    # value is json key in definition.
+    attribute_map = {}
+
+    @classmethod
+    def from_dict(cls{{^supportPython2}}: typing.Type[T]{{/supportPython2}}, dikt){{^supportPython2}} -> T{{/supportPython2}}:
+        """Returns the dict as a model"""
+        return util.deserialize_model(dikt, cls)
+
+    def to_dict(self):
+        """Returns the model properties as a dict
+
+        :rtype: dict
+        """
+        result = {}
+
+        for attr, _ in six.iteritems(self.openapi_types):
+            value = getattr(self, attr)
+            if isinstance(value, list):
+                result[attr] = list(map(
+                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
+                    value
+                ))
+            elif hasattr(value, "to_dict"):
+                result[attr] = value.to_dict()
+            elif isinstance(value, dict):
+                result[attr] = dict(map(
+                    lambda item: (item[0], item[1].to_dict())
+                    if hasattr(item[1], "to_dict") else item,
+                    value.items()
+                ))
+            else:
+                result[attr] = value
+
+        return result
+
+    def to_str(self):
+        """Returns the string representation of the model
+
+        :rtype: str
+        """
+        return pprint.pformat(self.to_dict())
+
+    def __repr__(self):
+        """For `print` and `pprint`"""
+        return self.to_str()
+
+    def __eq__(self, other):
+        """Returns true if both objects are equal"""
+        return self.__dict__ == other.__dict__
+
+    def __ne__(self, other):
+        """Returns true if both objects are not equal"""
+        return not self == other
Index: buildhelpers/codegen/templates/controller.mustache
===================================================================
--- buildhelpers/codegen/templates/controller.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/controller.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,113 @@
+import connexion
+import six
+
+{{#imports}}{{import}}  # noqa: E501
+{{/imports}}
+from {{packageName}} import util
+{{#operations}}
+{{#operation}}
+
+from {{packageName}}_impl.controllers import {{classname}}
+
+def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}):  # noqa: E501
+    """{{#summary}}{{.}}{{/summary}}{{^summary}}{{operationId}}{{/summary}}
+
+    {{#notes}}{{.}}{{/notes}} # noqa: E501
+
+    {{#allParams}}
+    :param {{paramName}}: {{description}}
+        {{^isContainer}}
+            {{#isPrimitiveType}}
+    :type {{paramName}}: {{>param_type}}
+            {{/isPrimitiveType}}
+            {{#isUuid}}
+    :type {{paramName}}: {{>param_type}}
+            {{/isUuid}}
+            {{^isPrimitiveType}}
+                {{#isFile}}
+    :type {{paramName}}: werkzeug.datastructures.FileStorage
+                {{/isFile}}
+                {{^isFile}}
+                    {{^isUuid}}
+    :type {{paramName}}: dict | bytes
+                    {{/isUuid}}
+                {{/isFile}}
+            {{/isPrimitiveType}}
+        {{/isContainer}}
+        {{#isListContainer}}
+            {{#items}}
+                {{#isPrimitiveType}}
+    :type {{paramName}}: List[{{>param_type}}]
+                {{/isPrimitiveType}}
+                {{^isPrimitiveType}}
+    :type {{paramName}}: list | bytes
+                {{/isPrimitiveType}}
+            {{/items}}
+        {{/isListContainer}}
+        {{#isMapContainer}}
+            {{#items}}
+                {{#isPrimitiveType}}
+    :type {{paramName}}: Dict[str, {{>param_type}}]
+                {{/isPrimitiveType}}
+                {{^isPrimitiveType}}
+    :type {{paramName}}: dict | bytes
+                {{/isPrimitiveType}}
+            {{/items}}
+        {{/isMapContainer}}
+    {{/allParams}}
+
+    :rtype: {{#returnType}}{{.}}{{/returnType}}{{^returnType}}None{{/returnType}}
+    """
+    {{#allParams}}
+        {{^isContainer}}
+            {{#isDate}}
+    {{paramName}} = util.deserialize_date({{paramName}})
+            {{/isDate}}
+            {{#isDateTime}}
+    {{paramName}} = util.deserialize_datetime({{paramName}})
+            {{/isDateTime}}
+            {{^isPrimitiveType}}
+                {{^isFile}}
+                    {{^isUuid}}
+    if connexion.request.is_json:
+        {{paramName}} = {{baseType}}.from_dict(connexion.request.get_json())  # noqa: E501
+                    {{/isUuid}}
+                {{/isFile}}
+            {{/isPrimitiveType}}
+        {{/isContainer}}
+        {{#isListContainer}}
+            {{#items}}
+                {{#isDate}}
+    if connexion.request.is_json:
+        {{paramName}} = [util.deserialize_date(s) for s in connexion.request.get_json()]  # noqa: E501
+                {{/isDate}}
+                {{#isDateTime}}
+    if connexion.request.is_json:
+        {{paramName}} = [util.deserialize_datetime(s) for s in connexion.request.get_json()]  # noqa: E501
+                {{/isDateTime}}
+                {{#complexType}}
+    if connexion.request.is_json:
+        {{paramName}} = [{{complexType}}.from_dict(d) for d in connexion.request.get_json()]  # noqa: E501
+                {{/complexType}}
+            {{/items}}
+        {{/isListContainer}}
+        {{#isMapContainer}}
+            {{#items}}
+                {{#isDate}}
+    if connexion.request.is_json:
+        {{paramName}} = {k: util.deserialize_date(v) for k, v in six.iteritems(connexion.request.get_json())}  # noqa: E501
+                {{/isDate}}
+                {{#isDateTime}}
+    if connexion.request.is_json:
+        {{paramName}} = {k: util.deserialize_datetime(v) for k, v in six.iteritems(connexion.request.get_json())}  # noqa: E501
+                {{/isDateTime}}
+                {{#complexType}}
+    if connexion.request.is_json:
+        {{paramName}} = {k: {{baseType}}.from_dict(v) for k, v in six.iteritems(connexion.request.get_json())}  # noqa: E501
+                {{/complexType}}
+            {{/items}}
+        {{/isMapContainer}}
+    {{/allParams}}
+    return {{classname}}.{{operationId}}({{#allParams}}{{paramName}}{{^required}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
+{{/operation}}
+{{/operations}}
Index: buildhelpers/codegen/templates/controller_test.mustache
===================================================================
--- buildhelpers/codegen/templates/controller_test.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/controller_test.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,57 @@
+# coding: utf-8
+
+from __future__ import absolute_import
+import unittest
+
+from flask import json
+from six import BytesIO
+
+{{#imports}}{{import}}  # noqa: E501
+{{/imports}}
+from . import BaseTestCase
+
+
+class {{#operations}}Test{{classname}}(BaseTestCase):
+    """{{classname}} integration test stubs"""
+
+    {{#operation}}
+    {{#vendorExtensions.x-skip-test}}
+    @unittest.skip("{{reason}}")
+    {{/vendorExtensions.x-skip-test}}
+    def test_{{operationId}}(self):
+        """Test case for {{{operationId}}}
+        {{{summary}}}
+        """
+        {{#bodyParam}}
+        {{paramName}} = {{{example}}}
+        {{/bodyParam}}
+        {{#queryParams}}
+        {{#-first}}query_string = [{{/-first}}{{^-first}}                {{/-first}}('{{paramName}}', '{{{example}}}'){{#hasMore}},{{/hasMore}}{{#-last}}]{{/-last}}
+        {{/queryParams}}
+        headers = { {{#vendorExtensions.x-prefered-produce}}
+            'Accept': '{{mediaType}}',{{/vendorExtensions.x-prefered-produce}}{{#vendorExtensions.x-prefered-consume}}
+            'Content-Type': '{{mediaType}}',{{/vendorExtensions.x-prefered-consume}}{{#headerParams}}
+            '{{paramName}}': '{{{example}}}',{{/headerParams}}{{#authMethods}}
+            {{#isBasicBasic}}'Authorization': 'Basic YXV0b3Rlc3RzOmF1dG90ZXN0cw==',{{/isBasicBasic}}
+            {{/authMethods}}
+        }
+        {{#formParams}}
+        {{#-first}}data = dict({{/-first}}{{^-first}}            {{/-first}}{{paramName}}={{{example}}}{{#hasMore}},{{/hasMore}}{{#-last}}){{/-last}}
+        {{/formParams}}
+        response = self.client.open(
+            '{{#contextPath}}{{{.}}}{{/contextPath}}{{{path}}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{paramName}}='{{{example}}}'{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/pathParams}},
+            method='{{httpMethod}}',
+            headers=headers{{#bodyParam}},
+            data=json.dumps({{paramName}}){{^consumes}},
+            content_type='application/json'{{/consumes}}{{/bodyParam}}{{#formParams}}{{#-first}},
+            data=data{{/-first}}{{/formParams}}{{#consumes}}{{#-first}},
+            content_type='{{{mediaType}}}'{{/-first}}{{/consumes}}{{#queryParams}}{{#-first}},
+            query_string=query_string{{/-first}}{{/queryParams}})
+        self.assert200(response,
+                       'Response body is : ' + response.data.decode('utf-8'))
+
+   {{/operation}}
+{{/operations}}
+
+if __name__ == '__main__':
+    unittest.main()
Index: buildhelpers/codegen/templates/encoder.mustache
===================================================================
--- buildhelpers/codegen/templates/encoder.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/encoder.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,20 @@
+from connexion.apps.flask_app import FlaskJSONEncoder
+import six
+
+from {{modelPackage}}.base_model_ import Model
+
+
+class JSONEncoder(FlaskJSONEncoder):
+    include_nulls = False
+
+    def default(self, o):
+        if isinstance(o, Model):
+            dikt = {}
+            for attr, _ in six.iteritems(o.openapi_types):
+                value = getattr(o, attr)
+                if value is None and not self.include_nulls:
+                    continue
+                attr = o.attribute_map[attr]
+                dikt[attr] = value
+            return dikt
+        return FlaskJSONEncoder.default(self, o)
Index: buildhelpers/codegen/templates/model.mustache
===================================================================
--- buildhelpers/codegen/templates/model.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/model.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,170 @@
+# coding: utf-8
+
+from __future__ import absolute_import
+from datetime import date, datetime  # noqa: F401
+
+from typing import List, Dict  # noqa: F401
+
+from {{modelPackage}}.base_model_ import Model
+{{#models}}
+{{#model}}
+{{#pyImports}}
+{{import}}
+{{/pyImports}}
+{{/model}}
+{{/models}}
+from {{packageName}} import util
+
+{{#imports}}
+{{{import}}}  # noqa: E501
+{{/imports}}
+
+{{#models}}
+{{#model}}
+class {{classname}}(Model):
+    """NOTE: This class is auto generated by OpenAPI Generator
+       (https://openapi-generator.tech).
+
+    Do not edit the class manually.
+    """{{#allowableValues}}
+
+    """
+    allowed enum values
+    """
+{{#enumVars}}
+    {{name}} = {{{value}}}{{^-last}}
+{{/-last}}
+{{/enumVars}}{{/allowableValues}}
+
+    def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}):  # noqa: E501
+        """{{classname}} - a model defined in OpenAPI
+
+        {{#vars}}
+        :param {{name}}: The {{name}} of this {{classname}}.  # noqa: E501
+        :type {{name}}: {{dataType}}
+        {{/vars}}
+        """
+        self.openapi_types = {
+{{#vars}}
+            '{{name}}': {{{dataType}}}{{#hasMore}},{{/hasMore}}
+{{/vars}}
+        }
+
+        self.attribute_map = {
+{{#vars}}
+            '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}}
+{{/vars}}
+        }
+{{#vars}}{{#-first}}
+{{/-first}}
+        self._{{name}} = {{name}}
+{{/vars}}
+
+    @classmethod
+    def from_dict(cls, dikt){{^supportPython2}} -> '{{classname}}'{{/supportPython2}}:
+        """Returns the dict as a model
+
+        :param dikt: A dict.
+        :type: dict
+        :return: The {{name}} of this {{classname}}.  # noqa: E501
+        :rtype: {{classname}}
+        """
+        return util.deserialize_model(dikt, cls){{#vars}}{{#-first}}
+
+{{/-first}}
+    @property
+    def {{name}}(self):
+        """Gets the {{name}} of this {{classname}}.
+
+        {{#description}}
+        {{{description}}}  # noqa: E501
+        {{/description}}
+
+        :return: The {{name}} of this {{classname}}.
+        :rtype: {{dataType}}
+        """
+        return self._{{name}}
+
+    @{{name}}.setter
+    def {{name}}(self, {{name}}):
+        """Sets the {{name}} of this {{classname}}.
+
+        {{#description}}
+        {{{description}}}  # noqa: E501
+        {{/description}}
+
+        :param {{name}}: The {{name}} of this {{classname}}.
+        :type {{name}}: {{dataType}}
+        """
+{{#isEnum}}
+        allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]  # noqa: E501
+{{#isContainer}}
+{{#isListContainer}}
+        if not set({{{name}}}).issubset(set(allowed_values)):
+            raise ValueError(
+                "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]"  # noqa: E501
+                .format(", ".join(map(str, set({{{name}}}) - set(allowed_values))),  # noqa: E501
+                        ", ".join(map(str, allowed_values)))
+            )
+{{/isListContainer}}
+{{#isMapContainer}}
+        if not set({{{name}}}.keys()).issubset(set(allowed_values)):
+            raise ValueError(
+                "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]"  # noqa: E501
+                .format(", ".join(map(str, set({{{name}}}.keys()) - set(allowed_values))),  # noqa: E501
+                        ", ".join(map(str, allowed_values)))
+            )
+{{/isMapContainer}}
+{{/isContainer}}
+{{^isContainer}}
+        if {{{name}}} not in allowed_values:
+            raise ValueError(
+                "Invalid value for `{{{name}}}` ({0}), must be one of {1}"
+                .format({{{name}}}, allowed_values)
+            )
+{{/isContainer}}
+{{/isEnum}}
+{{^isEnum}}
+{{#required}}
+        if {{name}} is None:
+            raise ValueError("Invalid value for `{{name}}`, must not be `None`")  # noqa: E501
+{{/required}}
+{{#hasValidation}}
+{{#maxLength}}
+        if {{name}} is not None and len({{name}}) > {{maxLength}}:
+            raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`")  # noqa: E501
+{{/maxLength}}
+{{#minLength}}
+        if {{name}} is not None and len({{name}}) < {{minLength}}:
+            raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`")  # noqa: E501
+{{/minLength}}
+{{#maximum}}
+        if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}:  # noqa: E501
+            raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`")  # noqa: E501
+{{/maximum}}
+{{#minimum}}
+        if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}:  # noqa: E501
+            raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`")  # noqa: E501
+{{/minimum}}
+{{#pattern}}
+        if {{name}} is not None and not re.search(r'{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}):  # noqa: E501
+            raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`")  # noqa: E501
+{{/pattern}}
+{{#maxItems}}
+        if {{name}} is not None and len({{name}}) > {{maxItems}}:
+            raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`")  # noqa: E501
+{{/maxItems}}
+{{#minItems}}
+        if {{name}} is not None and len({{name}}) < {{minItems}}:
+            raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`")  # noqa: E501
+{{/minItems}}
+{{/hasValidation}}
+{{/isEnum}}
+
+        self._{{name}} = {{name}}{{^-last}}
+
+{{/-last}}
+{{/vars}}
+
+{{/model}}
+{{/models}}
Index: buildhelpers/codegen/templates/openapi.mustache
===================================================================
--- buildhelpers/codegen/templates/openapi.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/openapi.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,1 @@
+{{{openapi-yaml}}}
Index: buildhelpers/codegen/templates/param_type.mustache
===================================================================
--- buildhelpers/codegen/templates/param_type.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/param_type.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,1 @@
+{{#isString}}str{{/isString}}{{#isInteger}}int{{/isInteger}}{{#isLong}}int{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}float{{/isDouble}}{{#isByteArray}}str{{/isByteArray}}{{#isBinary}}str{{/isBinary}}{{#isBoolean}}bool{{/isBoolean}}{{#isDate}}str{{/isDate}}{{#isDateTime}}str{{/isDateTime}}
Index: buildhelpers/codegen/templates/security_controller_.mustache
===================================================================
--- buildhelpers/codegen/templates/security_controller_.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/security_controller_.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,90 @@
+from typing import List
+
+{{#authMethods}}
+{{#isOAuth}}
+
+def info_from_{{name}}(token):
+    """
+    Validate and decode token.
+    Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
+    'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
+    'scope' or 'scopes' will be passed to scope validation function.
+
+    :param token Token provided by Authorization header
+    :type token: str
+    :return: Decoded token information or None if token is invalid
+    :rtype: dict | None
+    """
+    return {'scopes': ['read:pets', 'write:pets'], 'uid': 'user_id'}
+
+
+def validate_scope_{{name}}(required_scopes, token_scopes):
+    """
+    Validate required scopes are included in token scope
+
+    :param required_scopes Required scope to access called API
+    :type required_scopes: List[str]
+    :param token_scopes Scope present in token
+    :type token_scopes: List[str]
+    :return: True if access to called API is allowed
+    :rtype: bool
+    """
+    return set(required_scopes).issubset(set(token_scopes))
+
+{{/isOAuth}}
+{{#isApiKey}}
+
+def info_from_{{name}}(api_key, required_scopes):
+    """
+    Check and retrieve authentication information from api_key.
+    Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
+    'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
+
+    :param api_key API key provided by Authorization header
+    :type api_key: str
+    :param required_scopes Always None. Used for other authentication method
+    :type required_scopes: None
+    :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API
+    :rtype: dict | None
+    """
+    return {'uid': 'user_id'}
+
+{{/isApiKey}}
+{{#isBasicBasic}}
+
+def info_from_{{name}}(username, password, required_scopes):
+    """
+    Check and retrieve authentication information from basic auth.
+    Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
+    'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
+
+    :param username login provided by Authorization header
+    :type username: str
+    :param password password provided by Authorization header
+    :type password: str
+    :param required_scopes Always None. Used for other authentication method
+    :type required_scopes: None
+    :return: Information attached to user or None if credentials are invalid or does not allow access to called API
+    :rtype: dict | None
+    """
+    return {'uid': 'user_id'}
+
+{{/isBasicBasic}}
+{{#isBasicBearer}}
+
+def info_from_{{name}}(token):
+    """
+    Check and retrieve authentication information from custom bearer token.
+    Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
+    'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.
+
+    :param token Token provided by Authorization header
+    :type token: str
+    :return: Decoded token information or None if token is invalid
+    :rtype: dict | None
+    """
+    return {'uid': 'user_id'}
+
+{{/isBasicBearer}}
+{{/authMethods}}
+
Index: buildhelpers/codegen/templates/util.mustache
===================================================================
--- buildhelpers/codegen/templates/util.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
+++ buildhelpers/codegen/templates/util.mustache	(revision 43fd35cf3f21ed781b31e4e1056072bbeced8e55)
@@ -0,0 +1,141 @@
+import datetime
+
+import six
+import typing
+
+
+def _deserialize(data, klass):
+    """Deserializes dict, list, str into an object.
+
+    :param data: dict, list or str.
+    :param klass: class literal, or string of class name.
+
+    :return: object.
+    """
+    if data is None:
+        return None
+
+    if klass in six.integer_types or klass in (float, str, bool):
+        return _deserialize_primitive(data, klass)
+    elif klass == object:
+        return _deserialize_object(data)
+    elif klass == datetime.date:
+        return deserialize_date(data)
+    elif klass == datetime.datetime:
+        return deserialize_datetime(data)
+    elif type(klass) == typing.GenericMeta:
+        if klass.__extra__ == list:
+            return _deserialize_list(data, klass.__args__[0])
+        if klass.__extra__ == dict:
+            return _deserialize_dict(data, klass.__args__[1])
+    else:
+        return deserialize_model(data, klass)
+
+
+def _deserialize_primitive(data, klass):
+    """Deserializes to primitive type.
+
+    :param data: data to deserialize.
+    :param klass: class literal.
+
+    :return: int, long, float, str, bool.
+    :rtype: int | long | float | str | bool
+    """
+    try:
+        value = klass(data)
+    except UnicodeEncodeError:
+        value = six.u(data)
+    except TypeError:
+        value = data
+    return value
+
+
+def _deserialize_object(value):
+    """Return an original value.
+
+    :return: object.
+    """
+    return value
+
+
+def deserialize_date(string):
+    """Deserializes string to date.
+
+    :param string: str.
+    :type string: str
+    :return: date.
+    :rtype: date
+    """
+    try:
+        from dateutil.parser import parse
+        return parse(string).date()
+    except ImportError:
+        return string
+
+
+def deserialize_datetime(string):
+    """Deserializes string to datetime.
+
+    The string should be in iso8601 datetime format.
+
+    :param string: str.
+    :type string: str
+    :return: datetime.
+    :rtype: datetime
+    """
+    try:
+        from dateutil.parser import parse
+        return parse(string)
+    except ImportError:
+        return string
+
+
+def deserialize_model(data, klass):
+    """Deserializes list or dict to model.
+
+    :param data: dict, list.
+    :type data: dict | list
+    :param klass: class literal.
+    :return: model object.
+    """
+    instance = klass()
+
+    if not instance.openapi_types:
+        return data
+
+    for attr, attr_type in six.iteritems(instance.openapi_types):
+        if data is not None \
+                and instance.attribute_map[attr] in data \
+                and isinstance(data, (list, dict)):
+            value = data[instance.attribute_map[attr]]
+            setattr(instance, attr, _deserialize(value, attr_type))
+
+    return instance
+
+
+def _deserialize_list(data, boxed_type):
+    """Deserializes a list and its elements.
+
+    :param data: list to deserialize.
+    :type data: list
+    :param boxed_type: class literal.
+
+    :return: deserialized list.
+    :rtype: list
+    """
+    return [_deserialize(sub_data, boxed_type)
+            for sub_data in data]
+
+
+def _deserialize_dict(data, boxed_type):
+    """Deserializes a dict and its elements.
+
+    :param data: dict to deserialize.
+    :type data: dict
+    :param boxed_type: class literal.
+
+    :return: deserialized dict.
+    :rtype: dict
+    """
+    return {k: _deserialize(v, boxed_type)
+            for k, v in six.iteritems(data)}
