Ejemplo n.º 1
0
# Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals

from werkzeug.routing import Rule

urls = [
    Rule(
        "/search/<doctype>/",
        methods=["GET"],
        endpoint="warehouse.search.views.search",
    ),
]
Ejemplo n.º 2
0
 def set_route(self, method, path, handler, middlewares=()):
     key = "%s:%s" % (method.upper(), path)
     self.__router[key] = (handler, middlewares)
     self.__url_map.add(Rule(path, endpoint=path, strict_slashes=False))
Ejemplo n.º 3
0
 def decorate(f):
     kw['endpoint'] = f.__name__
     url_map.add(Rule(rule, **kw))
     return f
Ejemplo n.º 4
0
 def decorator(func):
     self.url_map.add(Rule(string, endpoint=func, methods=methods))
     return func
Ejemplo n.º 5
0
    return Response(
        'Paste successfully removed. Thanks for choosing paste.posativ.org.',
        200)


def index(app, request):
    """Return / -- basic stuff."""

    return Response(app.render_template('main.html'),
                    200,
                    content_type='text/html')


urlmap = Map([
    Rule('/', endpoint=index, methods=[
        'GET',
    ]),
    Rule('/', endpoint=create, methods=[
        'POST',
    ]),
    Rule('/<string(minlength=3):pasteid>', endpoint=show),
    Rule('/<string(minlength=3):pasteid>/remove', endpoint=remove),
])


class Pastie:

    SECRET_KEY = '\x85\xe1Pc\x11n\xe0\xc76\xa1\xd9\x93$\x1ei\x06'
    HTTBL_KEY = 'THIS IS NOT A VALID HTTPBL KEY'

    def __init__(self, data_dir='pastes/', host='http://localhost/'):
Ejemplo n.º 6
0
def test_adapter_match_return_rule():
    """Returning the matched Rule"""
    rule = Rule('/foo/', endpoint='foo')
    map = Map([rule])
    adapter = map.bind('localhost', '/')
    assert adapter.match('/foo/', return_rule=True) == (rule, {})
Ejemplo n.º 7
0
def test_allowed_methods_querying():
    """Make sure it's possible to test for allowed methods"""
    m = Map([Rule('/<foo>', methods=['GET', 'HEAD']),
             Rule('/foo', methods=['POST'])])
    a = m.bind('example.org')
    assert sorted(a.allowed_methods('/foo')) == ['GET', 'HEAD', 'POST']
Ejemplo n.º 8
0
def get_routes():
    yield Rule('/report', methods=['POST'], endpoint=report)
Ejemplo n.º 9
0
import datetime
import logging
import sys
from dateutil.tz import tzlocal
from flask import Flask, request
from werkzeug.routing import Map, Rule

# We'll do our own logging, thanks
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

app = Flask(__name__)
app.url_map.add(Rule('/', endpoint='catch_all'))
app.url_map.add(Rule('/<path:path>', endpoint='catch_all'))


@app.endpoint('catch_all')
def catch_all(path="/"):
    write("[{:%Y-%m-%d %H:%M:%S %z}] {} {}".format(
        datetime.datetime.now(tzlocal()), request.method, request.url))
    printTable({k: repr(v)
                for k, v in request.headers.items()},
               "Header",
               "Value",
               prefix="\t")
    data = request.get_data()
    if len(data) == 0:
        write("No request body")
    else:
        write("Request data:")
        write("\t" + repr(data))
Ejemplo n.º 10
0
class ExportHelpWizard(models.TransientModel):
    _name = "export.help.wizard"
    _description = 'Export Help Online'

    data = fields.Binary('XML', readonly=True)
    export_filename = fields.Char('Export XML Filename', size=128)

    binary = Binary()
    websiteBinary = WebsiteBinary()

    img_url_map = Map([
        Rule('/web/image'),
        Rule('/web/image/<string:xmlid>'),
        Rule('/web/image/<string:xmlid>/<string:filename>'),
        Rule('/web/image/<string:xmlid>/<int:width>x<int:height>'),
        Rule('/web/image/<string:xmlid>/<int:width>x<int:height>/'
             '<string:filename>'),
        Rule('/web/image/<string:model>/<int:id>/<string:field>'),
        Rule('/web/image/<string:model>/<int:id>/<string:field>/'
             '<string:filename>'),
        Rule('/web/image/<string:model>/<int:id>/<string:field>/'
             '<int:width>x<int:height>'),
        Rule('/web/image/<string:model>/<int:id>/<string:field>/'
             '<int:width>x<int:height>/<string:filename>'),
        Rule('/web/image/<int:id>'),
        Rule('/web/image/<int:id>/<string:filename>'),
        Rule('/web/image/<int:id>/<int:width>x<int:height>'),
        Rule('/web/image/<int:id>/<int:width>x<int:height>/<string:filename>'),
        Rule('/web/image/<int:id>-<string:unique>'),
        Rule('/web/image/<int:id>-<string:unique>/<string:filename>'),
        Rule('/web/image/<int:id>-<string:unique>/<int:width>x<int:height>'),
        Rule('/web/image/<int:id>-<string:unique>/<int:width>x<int:height>'
             '/<string:filename>'),
        Rule('/website/image'),
        Rule('/website/image/<xmlid>'),
        Rule('/website/image/<xmlid>/<int:width>x<int:height>'),
        Rule('/website/image/<xmlid>/<field>'),
        Rule('/website/image/<xmlid>/<field>/<int:width>x<int:height>'),
        Rule('/website/image/<model>/<id>/<field>'),
        Rule('/website/image/<model>/<id>/<field>/<int:width>x<int:height>')
    ])

    def _manage_images_on_page(self, page_node, data_node, exported_resources):
        """
            - Extract images from page and generate an xml node
            - Replace db id in url with xml id
        """
        img_model = 'ir.attachment'
        urls = self.img_url_map.bind("dummy.org", "/")
        for img_elem in page_node.iter('img'):
            img_src = img_elem.get('src')
            parse_result = urlparse.urlparse(img_src)
            path = parse_result.path
            query_args = parse_result.query
            if urls.test(parse_result.path, "GET"):
                endpoint, kwargs = urls.match(path,
                                              "GET",
                                              query_args=query_args)
                kwargs.update(dict(urlparse.parse_qsl(query_args)))
                image = None
                # get the binary object
                xml_id = kwargs.get('xmlid')
                if xml_id:
                    image = self.env.ref(xml_id, False)
                else:
                    _id = kwargs.get('id')
                    model = kwargs.get('model', 'ir.attachment')
                    if _id and model:
                        _id, _, unique = str(_id).partition('_')
                        image = self.env[model].browse(int(_id))
                if (not image or not image.exists()
                        or image._name != img_model):
                    raise exceptions.UserError(
                        _('Only images from ir.attachment are supported when '
                          'exporting help pages'))
                exported_data = image.export_data([
                    'id', 'datas', 'datas_fname', 'name', 'res_model',
                    'mimetype'
                ],
                                                  raw_data=False)['datas'][0]
                xml_id = exported_data[0]
                new_src = '/web/image/%s' % xml_id
                img_elem.attrib['src'] = new_src
                if xml_id in exported_resources:
                    continue
                img_node = ET.SubElement(data_node,
                                         'record',
                                         attrib={
                                             'id': xml_id,
                                             'model': image._name
                                         })
                field_node = ET.SubElement(img_node,
                                           'field',
                                           attrib={'name': 'datas'})
                field_node.text = str(exported_data[1])
                field_node = ET.SubElement(img_node,
                                           'field',
                                           attrib={'name': 'datas_fname'})
                field_node.text = exported_data[2]
                field_node = ET.SubElement(img_node,
                                           'field',
                                           attrib={'name': 'name'})
                field_node.text = exported_data[3]
                field_node = ET.SubElement(img_node,
                                           'field',
                                           attrib={'name': 'res_model'})
                field_node.text = exported_data[4]
                field_node = ET.SubElement(img_node,
                                           'field',
                                           attrib={'name': 'mimetype'})
                field_node.text = exported_data[5]
                data_node.append(img_node)
                exported_resources.add(xml_id)

    def _clean_href_urls(self, page_node, page_prefix, template_prefix):
        """
            Remove host address for href urls
        """
        for a_elem in page_node.iter('a'):
            if not a_elem.get('href'):
                continue
            href = a_elem.get('href')
            if not href.startswith('http'):
                continue
            page_url = '/page/%s' % page_prefix
            template_url = '/page/%s' % template_prefix
            if page_url not in href and template_url not in href:
                continue
            elif page_url in href and template_url not in href:
                pass
            elif page_url not in href and template_url in href:
                page_url = template_url
            else:
                if page_prefix in template_prefix:
                    page_url = template_url
                else:
                    pass

            if page_url:
                trail = href.split(page_url, 1)[1]
                a_elem.attrib['href'] = page_url + trail

    def _generate_snippet_from_template(self, page_node, template_id,
                                        template_prefix):
        """
            Generate a website snippet from a template
        """
        page = copy.deepcopy(page_node)
        snippet = ET.Element('template')
        snippet.attrib['id'] = template_id + '_snippet'
        snippet.attrib['inherit_id'] = 'website.snippets'
        snippet.attrib['name'] = page_node.attrib['name']

        xpath = ET.SubElement(snippet,
                              'xpath',
                              attrib={
                                  'expr': "//div[@id='snippet_structure']",
                                  'position': 'inside'
                              })
        main_div = ET.SubElement(xpath, 'div')
        thumbnail = ET.SubElement(main_div,
                                  'div',
                                  attrib={'class': 'oe_snippet_thumbnail'})
        ET.SubElement(thumbnail,
                      'img',
                      attrib={
                          'class': 'oe_snippet_thumbnail_img',
                          'src': HELP_ONLINE_SNIPPET_IMAGE_PATH
                      })
        span = ET.SubElement(thumbnail,
                             'span',
                             attrib={'class': 'oe_snippet_thumbnail_title'})
        span.text = page_node.attrib['name'].replace(template_prefix, '')
        body = ET.SubElement(
            main_div,
            'section',
            attrib={'class': 'oe_snippet_body '
                    'mt_simple_snippet'})

        template = page.find(".//div[@id='wrap']")

        for node in template.getchildren():
            body.append(node)

        return snippet

    def _get_qweb_views_data(self):
        parameter_model = self.env['ir.config_parameter']
        page_prefix = parameter_model.get_param(PAGE_PREFIX_PARAMETER, False)
        template_prefix = parameter_model.get_param(TEMPLATE_PREFIX_PARAMETER,
                                                    False)

        if not page_prefix or not template_prefix:
            return False

        domain = [('type', '=', 'qweb'), ('page', '=', True), '|',
                  ('name', 'like', '%s%%' % page_prefix),
                  ('name', 'like', '%s%%' % template_prefix)]

        ir_ui_views = self.env['ir.ui.view'].search(domain, order='name')
        xml_to_export = ET.Element('openerp')
        data_node = ET.SubElement(xml_to_export, 'data')
        exported_resources = set()
        for ir_ui_view in ir_ui_views:
            parser = ET.XMLParser(remove_blank_text=True)
            root = ET.XML(ir_ui_view.arch, parser=parser)
            root.tag = 'template'
            xml_id = self._get_ir_ui_view_xml_id(ir_ui_view,
                                                 root.attrib.pop('t-name'))
            root.attrib['name'] = ir_ui_view.name.replace('website.', '')
            root.attrib['id'] = xml_id
            root.attrib['page'] = 'True'

            self._manage_images_on_page(root, data_node, exported_resources)
            self._clean_href_urls(root, page_prefix, template_prefix)
            data_node.append(root)

            if root.attrib['name'].startswith(template_prefix):
                snippet = self._generate_snippet_from_template(
                    root, xml_id, template_prefix)
                data_node.append(snippet)

        if len(ir_ui_views) > 0:
            return ET.tostring(xml_to_export,
                               encoding='utf-8',
                               xml_declaration=True,
                               pretty_print=True)
        else:
            return False

    @api.model
    def _get_ir_ui_view_xml_id(self, ir_ui_view, template_name):
        """This method check if an xml_id exists for the given ir.ui.view
        If no xml_id exists, a new one is created with template name as
        value to ensure that the import of the generated file will update
        the existing view in place of creating new copies.
        """
        ir_model_data = self.sudo().env['ir.model.data']
        data = ir_model_data.search([('model', '=', ir_ui_view._name),
                                     ('res_id', '=', ir_ui_view.id)])
        if data:
            if data[0].module:
                return '%s.%s' % (data[0].module, data[0].name)
            else:
                return data[0].name
        else:
            module, name = template_name.split('.')
            postfix = ir_model_data.search_count([('module', '=', module),
                                                  ('name', 'like', name)])
            if postfix:
                name = '%s_%s' % (name, postfix)
            ir_model_data.create({
                'model': ir_ui_view._name,
                'res_id': ir_ui_view.id,
                'module': module,
                'name': name,
            })
            return module + '.' + name

    @api.multi
    def export_help(self):
        """
        Export all Qweb views related to help online in a Odoo
        data XML file
        """
        xml_data = self._get_qweb_views_data()
        if not xml_data:
            raise exceptions.Warning(_('No data to export !'))
        out = base64.encodestring(xml_data)

        self.write({'data': out, 'export_filename': 'help_online_data.xml'})

        return {
            'name': _('Export Help'),
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': self.id,
            'views': [(False, 'form')],
            'target': 'new',
        }

    @api.model
    def auto_backup(self):
        """
            Export data to a file on home directory of user
        """
        parameter_model = self.env['ir.config_parameter']
        autobackup_path = parameter_model.get_param(AUTOBACKUP_PARAMETER,
                                                    False)

        if autobackup_path:
            xml_data = self._get_qweb_views_data()
            try:
                timestr = time.strftime("%Y%m%d-%H%M%S")
                filename = '%s/help_online_backup-%s.xml' % (autobackup_path,
                                                             timestr)
                backup_file = open(filename, 'w')
                backup_file.write(xml_data)
                backup_file.close()
            except:
                _logger.warning(
                    _('Unable to write autobackup file '
                      'in given directory: %s' % autobackup_path))
Ejemplo n.º 11
0
from werkzeug.routing import Rule
from optparse import OptionParser
from pprint import pprint
import time
from loggerlib.logger import logg

VERBOSE = 'verbose'
BASIC_AUTH = 'basic_auth'
AUTH_USERNAME = '******'
AUTH_PASSWORD = '******'

config = {BASIC_AUTH: False, VERBOSE: False}

app = Flask(__name__)

app.url_map.add(Rule('/', defaults={'path': ''}, endpoint='index'))
app.url_map.add(Rule('/<path:path>', endpoint='index'))


def validate_status_code(status_code):
    if status_code < 600:
        return True
    return False


def extract(d):
    return {key: value for (key, value) in d.items()}


def check_auth(username, password):
    if AUTH_USERNAME not in config or AUTH_PASSWORD not in config:
Ejemplo n.º 12
0
 def add_url_rule(self, rule, _, f, **options):
     self.url_map.add(Rule(rule, endpoint=f))
Ejemplo n.º 13
0
def make_urls(app):
    """Make the URLs for a new zine application."""
    blog_urls = [
        Rule('/', defaults={'page': 1}, endpoint='blog/index'),
        Rule('/feed.atom', endpoint='blog/atom_feed'),
        Rule('/page/<int:page>', endpoint='blog/index'),
        Rule('/archive', endpoint='blog/archive'),
        Submount(app.cfg['profiles_url_prefix'], [
            Rule('/', endpoint='blog/authors'),
            Rule('/<string:username>',
                 defaults={'page': 1},
                 endpoint='blog/show_author'),
            Rule('/<string:username>/page/<int:page>',
                 endpoint='blog/show_author'),
            Rule('/<string:author>/feed.atom', endpoint='blog/atom_feed'),
        ]),
        Submount(app.cfg['category_url_prefix'], [
            Rule('/<string:slug>',
                 defaults={'page': 1},
                 endpoint='blog/show_category'),
            Rule('/<string:slug>/page/<int:page>',
                 endpoint='blog/show_category'),
            Rule('/<string:category>/feed.atom', endpoint='blog/atom_feed')
        ]),
        Submount(app.cfg['tags_url_prefix'], [
            Rule('/', endpoint='blog/tags'),
            Rule('/<string:slug>',
                 defaults={'page': 1},
                 endpoint='blog/show_tag'),
            Rule('/<string:slug>/page/<int:page>', endpoint='blog/show_tag'),
            Rule('/<string:tag>/feed.atom', endpoint='blog/atom_feed')
        ])
    ]
    admin_urls = [
        Rule('/', endpoint='admin/index'),
        Rule('/login', endpoint='admin/login'),
        Rule('/logout', endpoint='admin/logout'),
        Rule('/_bookmarklet', endpoint='admin/bookmarklet'),
        Rule('/entries/',
             endpoint='admin/manage_entries',
             defaults={'page': 1}),
        Rule('/entries/page/<int:page>', endpoint='admin/manage_entries'),
        Rule('/entries/new', endpoint='admin/new_entry'),
        Rule('/pages/', endpoint='admin/manage_pages', defaults={'page': 1}),
        Rule('/pages/page/<int:page>', endpoint='admin/manage_pages'),
        Rule('/pages/new', endpoint='admin/new_page'),
        Rule('/p/<int:post_id>', endpoint='admin/edit_post'),
        Rule('/p/<int:post_id>/delete', endpoint='admin/delete_post'),
        Rule('/p/<int:post_id>/comments',
             endpoint='admin/show_post_comments',
             defaults={'page': 1}),
        Rule('/comments/',
             endpoint='admin/manage_comments',
             defaults={'page': 1}),
        Rule('/comments/page/<int:page>', endpoint='admin/manage_comments'),
        Rule('/comments/unmoderated',
             defaults={'page': 1},
             endpoint='admin/show_unmoderated_comments'),
        Rule('/comments/unmoderated/page/<int:page>',
             endpoint='admin/show_unmoderated_comments'),
        Rule('/comments/approved',
             defaults={'page': 1},
             endpoint='admin/show_approved_comments'),
        Rule('/comments/approved/page/<int:page>',
             endpoint='admin/show_approved_comments'),
        Rule('/comments/blocked',
             defaults={'page': 1},
             endpoint='admin/show_blocked_comments'),
        Rule('/comments/blocked/page/<int:page>',
             endpoint='admin/show_blocked_comments'),
        Rule('/comments/spam',
             defaults={'page': 1},
             endpoint='admin/show_spam_comments'),
        Rule('/comments/spam/page/<int:page>',
             endpoint='admin/show_spam_comments'),
        Rule('/comments/<int:comment_id>', endpoint='admin/edit_comment'),
        Rule('/comments/<int:comment_id>/delete',
             endpoint='admin/delete_comment'),
        Rule('/comments/<int:comment_id>/approve',
             endpoint='admin/approve_comment'),
        Rule('/comments/<int:comment_id>/block',
             endpoint='admin/block_comment'),
        Rule('/comments/<int:comment_id>/spam',
             endpoint='admin/report_comment_spam'),
        Rule('/comments/<int:comment_id>/ham',
             endpoint='admin/report_comment_ham'),
        Rule('/categories/',
             endpoint='admin/manage_categories',
             defaults={'page': 1}),
        Rule('/categories/page/<int:page>',
             endpoint='admin/manage_categories'),
        Rule('/categories/new', endpoint='admin/new_category'),
        Rule('/categories/<int:category_id>', endpoint='admin/edit_category'),
        Rule('/categories/<int:category_id>/delete',
             endpoint='admin/delete_category'),
        Rule('/users/', endpoint='admin/manage_users', defaults={'page': 1}),
        Rule('/users/page/<int:page>', endpoint='admin/manage_users'),
        Rule('/users/new', endpoint='admin/new_user'),
        Rule('/users/<int:user_id>', endpoint='admin/edit_user'),
        Rule('/users/<int:user_id>/delete', endpoint='admin/delete_user'),
        Rule('/groups/', endpoint='admin/manage_groups'),
        Rule('/groups/new', endpoint='admin/new_group'),
        Rule('/groups/<int:group_id>', endpoint='admin/edit_group'),
        Rule('/groups/<int:group_id>/delete', endpoint='admin/delete_group'),
        Rule('/options/', endpoint='admin/options'),
        Rule('/options/basic', endpoint='admin/basic_options'),
        Rule('/options/urls', endpoint='admin/urls'),
        Rule('/options/theme/', endpoint='admin/theme'),
        Rule('/options/theme/configure', endpoint='admin/configure_theme'),
        Rule('/options/plugins/', endpoint='admin/plugins'),
        Rule('/options/plugins/<plugin>/remove',
             endpoint='admin/remove_plugin'),
        Rule('/options/cache', endpoint='admin/cache'),
        Rule('/system/', endpoint='admin/information'),
        Rule('/system/maintenance/', endpoint='admin/maintenance'),
        Rule('/system/log', defaults={'page': 1}, endpoint='admin/log'),
        Rule('/system/log/page/<int:page>', endpoint='admin/log'),
        Rule('/system/import/', endpoint='admin/import'),
        Rule('/system/import/<int:id>', endpoint='admin/inspect_import'),
        Rule('/system/import/<int:id>/delete', endpoint='admin/delete_import'),
        Rule('/system/export', endpoint='admin/export'),
        Rule('/system/about', endpoint='admin/about_zine'),
        Rule('/system/help/', endpoint='admin/help'),
        Rule('/system/help/<path:page>', endpoint='admin/help'),
        Rule('/system/configuration', endpoint='admin/configuration'),
        Rule('/change_password', endpoint='admin/change_password')
    ]
    other_urls = [
        Rule('/<slug>', endpoint='blog/post', build_only=True),
        Rule('/_services/', endpoint='blog/service_rsd'),
        Rule('/_services/json/<path:identifier>',
             endpoint='blog/json_service'),
        Rule('/_services/xml/<path:identifier>', endpoint='blog/xml_service'),
        Rule('/_translations.js', endpoint='blog/serve_translations')
    ]

    # add the more complex url rule for archive and show post
    tmp = '/'
    for digits, part in zip(
            app.cfg['fixed_url_date_digits'] and (4, 2, 2) or (0, 0, 0),
        ('year', 'month', 'day')):
        tmp += '<int(fixed_digits=%d):%s>/' % (digits, part)
        blog_urls.extend([
            Rule(tmp, defaults={'page': 1}, endpoint='blog/archive'),
            Rule(tmp + 'page/<int:page>', endpoint='blog/archive'),
            Rule(tmp + 'feed.atom', endpoint='blog/atom_feed')
        ])

    return [
        Submount(app.cfg['blog_url_prefix'], blog_urls),
        Submount(app.cfg['admin_url_prefix'], admin_urls)
    ] + other_urls
Ejemplo n.º 14
0
 def add_url_rule(self, url, endpt, func):
     self.url_map.add(Rule(url, endpoint=endpt))
     self.views[endpt] = func
Ejemplo n.º 15
0
    def __init__(self,
                 routes: RoutesConfig,
                 initial_types: List[type] = None) -> None:
        required_type = wsgi.WSGIResponse

        initial_types = initial_types or []
        initial_types += [wsgi.WSGIEnviron, URLPathArgs, Exception]

        rules = []
        views = {}

        for (path, method, view) in walk(routes):
            view_signature = inspect.signature(view)
            uritemplate = URITemplate(path)

            # Ensure view arguments include all URL arguments
            for arg in uritemplate.variable_names:
                assert arg in view_signature.parameters, (
                    'URL argument "%s" in path "%s" must be included as a '
                    'keyword argument in the view function "%s"' %
                    (arg, path, view.__name__))

            # Create a werkzeug path string
            werkzeug_path = path[:]
            for arg in uritemplate.variable_names:
                param = view_signature.parameters[arg]
                if param.annotation is inspect.Signature.empty:
                    converter = 'string'
                elif issubclass(param.annotation, (schema.String, str)):
                    if getattr(param.annotation, 'format', None) == 'path':
                        converter = 'path'
                    else:
                        converter = 'string'
                elif issubclass(param.annotation, (schema.Number, float)):
                    converter = 'float'
                elif issubclass(param.annotation, (schema.Integer, int)):
                    converter = 'int'
                else:
                    msg = 'Invalid type for path parameter, %s.' % param.annotation
                    raise exceptions.ConfigurationError(msg)

                werkzeug_path = werkzeug_path.replace(
                    '{%s}' % arg, '<%s:%s>' % (converter, arg))

            # Create a werkzeug routing rule
            name = view.__name__
            rule = Rule(werkzeug_path, methods=[method], endpoint=name)
            rules.append(rule)

            # Determine any inferred type annotations for the view
            extra_annotations = {}  # type: Dict[str, type]
            for param in view_signature.parameters.values():

                if param.annotation is inspect.Signature.empty:
                    annotated_type = str
                else:
                    annotated_type = param.annotation

                if param.name in uritemplate.variable_names:

                    class TypedURLPathArg(URLPathArg):
                        schema = annotated_type

                    extra_annotations[param.name] = TypedURLPathArg
                elif (annotated_type in primitive_types) or issubclass(
                        annotated_type, schema_types):
                    if method in ('POST', 'PUT', 'PATCH'):
                        if issubclass(annotated_type, schema.Object):

                            class TypedDataParam(http.RequestData):
                                schema = annotated_type

                            extra_annotations[param.name] = TypedDataParam
                        else:

                            class TypedFieldParam(http.RequestField):
                                schema = annotated_type

                            extra_annotations[param.name] = TypedFieldParam
                    else:

                        class TypedQueryParam(http.QueryParam):
                            schema = annotated_type

                        extra_annotations[param.name] = TypedQueryParam

            return_annotation = view_signature.return_annotation
            if return_annotation is inspect.Signature.empty:
                extra_annotations['return'] = http.ResponseData
            elif issubclass(
                    return_annotation,
                (schema_types, primitive_types, typing_types)):  # type: ignore
                extra_annotations['return'] = http.ResponseData

            # Determine the pipeline for the view.
            pipeline = pipelines.build_pipeline(view, initial_types,
                                                required_type,
                                                extra_annotations)
            views[name] = Endpoint(view, pipeline)

        self.exception_pipeline = pipelines.build_pipeline(
            exception_handler, initial_types, required_type, {})
        self.routes = routes
        self.adapter = Map(rules).bind('example.com')
        self.views = views
Ejemplo n.º 16
0
from werkzeug.exceptions import HTTPException
from werkzeug.routing import Map, Rule, NotFound, RequestRedirect

# http://werkzeug.pocoo.org/docs/0.11/routing/
url_map = Map([
    Rule('/', endpoint='blog/index'),
    Rule('/<int:year>/', endpoint='blog/archive'),
    Rule('/<int:year>/<int:month>/', endpoint='blog/archive'),
    Rule('/<int:year>/<int:month>/<int:day>/', endpoint='blog/archive'),
    Rule('/<int:year>/<int:month>/<int:day>/<slug>',
         endpoint='blog/show_post'),
    Rule('/about', endpoint='blog/about_me'),
    Rule('/feeds/', endpoint='blog/feeds'),
    Rule('/feeds/<feed_name>.rss', endpoint='blog/show_feed')
])


def application(environ, start_response):
    urls = url_map.bind_to_environ(environ)
    try:
        endpoint, args = urls.match()
    except HTTPException as e:
        return e(environ, start_response)
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Rule points to %r with arguments %r' % (endpoint, args)]


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, application)
Ejemplo n.º 17
0
def test_path():
    """URL routing path converter behavior"""
    map = Map([
        Rule('/', defaults={'name': 'FrontPage'}, endpoint='page'),
        Rule('/Special', endpoint='special'),
        Rule('/<int:year>', endpoint='year'),
        Rule('/<path:name>', endpoint='page'),
        Rule('/<path:name>/edit', endpoint='editpage'),
        Rule('/<path:name>/silly/<path:name2>', endpoint='sillypage'),
        Rule('/<path:name>/silly/<path:name2>/edit', endpoint='editsillypage'),
        Rule('/Talk:<path:name>', endpoint='talk'),
        Rule('/User:<username>', endpoint='user'),
        Rule('/User:<username>/<path:name>', endpoint='userpage'),
        Rule('/Files/<path:file>', endpoint='files'),
    ])
    adapter = map.bind('example.org', '/')

    assert adapter.match('/') == ('page', {'name':'FrontPage'})
    assert_raises(RequestRedirect, lambda: adapter.match('/FrontPage'))
    assert adapter.match('/Special') == ('special', {})
    assert adapter.match('/2007') == ('year', {'year':2007})
    assert adapter.match('/Some/Page') == ('page', {'name':'Some/Page'})
    assert adapter.match('/Some/Page/edit') == ('editpage', {'name':'Some/Page'})
    assert adapter.match('/Foo/silly/bar') == ('sillypage', {'name':'Foo', 'name2':'bar'})
    assert adapter.match('/Foo/silly/bar/edit') == ('editsillypage', {'name':'Foo', 'name2':'bar'})
    assert adapter.match('/Talk:Foo/Bar') == ('talk', {'name':'Foo/Bar'})
    assert adapter.match('/User:thomas') == ('user', {'username':'******'})
    assert adapter.match('/User:thomas/projects/werkzeug') == ('userpage', {'username':'******', 'name':'projects/werkzeug'})
    assert adapter.match('/Files/downloads/werkzeug/0.2.zip') == ('files', {'file':'downloads/werkzeug/0.2.zip'})
Ejemplo n.º 18
0
from werkzeug.routing import Map, Rule
"""
APP_URLS contain all urls of the app. 
"""
APP_URLS = {
    'ads_urls':
    Map([
        Rule('/', endpoint='display_advertisements'),
        Rule('/add', endpoint='add_advertisement'),
        Rule('/admin', endpoint='get_admin_panel')
    ]),
}
Ejemplo n.º 19
0
def test_protocol_joining_bug():
    """Make sure the protocol joining bug is fixed"""
    m = Map([Rule('/<foo>', endpoint='x')])
    a = m.bind('example.org')
    assert a.build('x', {'foo': 'x:y'}) == '/x:y'
    assert a.build('x', {'foo': 'x:y'}, force_external=True) == 'http://example.org/x:y'
import requests
from flask import Flask, request, Response, abort
from werkzeug.routing import Rule

from Controllers.elro_controller import ElroController
from HttpsEnforcer import HSTS
from Knowledge_Base import log, to_json, ControllerResponseCode, LogLevel
from Detectors import SQLDetector, BruteForce, BotsDetector, XSSDetector, XMLDetector
from Detectors.csrf import CSRF
from Parser.parser import FlaskHTTPRequestParser, HTTPResponseParser

app = Flask(__name__)
app.url_map.add(Rule('/', endpoint='proxy', defaults={'path': ""}))
app.url_map.add(Rule('/<path:path>', endpoint='proxy'))

# The available detectors for the Controller
detectors = {
    "sql_detector": SQLDetector,
    "xss_detector": XSSDetector,
    "xml_detector": XMLDetector,
    "csrf_detector": CSRF,
    "bruteforce_detector": BruteForce,
    "bots_detector": BotsDetector,
}

hsts = HSTS()


def request_handler():
    # try:
    log("Is the request is HTTPS? ", LogLevel.INFO, request_handler)
Ejemplo n.º 21
0
 def decorator(f):
     print(1)
     endpoint = options.setdefault('endpoint', f.__name__)
     self.url_map.add(Rule(rule, **options))
     self.view_functions[endpoint] = f
     return f
Ejemplo n.º 22
0
class ForecastResource(AccountsRequired, RESTResource):
    url_map = Map([Rule('/', endpoint='index')], strict_slashes=False)

    parents = {
        UserResource: '/<string:id_user>/forecast',
        MeUserResource: '/forecast',
    }

    def projection_categories(self, query, categories, start_date, end_date,
                              income):
        s = Decimal('0')

        for cluster in query(TransactionsCluster):
            if not cluster.enabled or (income is not None and
                                       ((cluster.mean_amount < 0) == income)):
                continue

            transactions = query(Transaction).filter(
                Transaction.id_cluster == cluster.id,
                Transaction.rdate.between(start_date, end_date))

            tables = []
            for tr in transactions:
                table = {
                    'text': tr.wording,
                    'tdate': tr.rdate,
                    'debited': True,
                    'disabled': False,
                    'thisMonth': True,
                    'category': cluster.category,
                    'value': tr.value,
                    'cluster': cluster,
                }
                tables.append(table)

            current_date = cluster.next_date
            interval = None
            if cluster.median_increment:
                interval = timedelta(days=cluster.median_increment)

            today = datetime.date.today()
            while (interval and current_date <= end_date) or len(tables) == 0:
                disabled = False
                if current_date and current_date < today:
                    if (today - current_date).days > (
                            cluster.median_increment /
                            2 if cluster.median_increment else 3):
                        disabled = True
                    else:
                        current_date = today + timedelta(days=1)

                table = {
                    'text': cluster.wording,
                    'tdate': current_date if cluster.next_date else None,
                    'debited': False,
                    'thisMonth': current_date and current_date <= end_date,
                    'disabled': disabled,
                    'category': cluster.category,
                    'value': cluster.mean_amount,
                    'cluster': cluster,
                }
                tables.append(table)

                if not disabled and table['thisMonth']:
                    s += int(round(cluster.mean_amount))

                if interval:
                    current_date += interval
                else:
                    break

            for table in tables:
                if cluster.id_category in categories:
                    categories[cluster.id_category].append(table)
                else:
                    categories[cluster.id_category] = [table]

        return s

    def compute_projection(self, query, start_date, end_date, income=False):
        projection = {
            'categories': {},
        }
        sumA = self.projection_categories(query, projection['categories'],
                                          start_date, end_date, income)
        projection['catsum'] = int(round(abs(sumA)))

        predSumL = predSumH = predSumA = Decimal('0')
        for p in query(Prediction).filter(
                Prediction.day == datetime.date.today().day):
            if income:
                continue

            predSumL += p.mean_amount - p.std_amount
            predSumH += p.mean_amount + p.std_amount
            predSumA += p.mean_amount
            sumA += p.mean_amount

        projection['predsumL'] = int(round(abs(predSumL)))
        projection['predsumH'] = int(round(abs(predSumH)))
        projection['predsumA'] = int(round(abs(predSumA)))
        projection['sum'] = int(round(abs(sumA)))

        return projection

    def get_collection(self, request, query, **values):
        query.add_filter((Account.display == True)
                         & (Account.disabled == None))
        query.add_join(Account)

        today = datetime.date.today()
        start_date = first_month_day(today)
        end_date = last_month_day(start_date)

        tq = query(func.sum(Transaction.value)).filter(
            Transaction.application_date.between(start_date, end_date),
            Transaction.deleted == None)
        actualExpenses = -(tq.filter(Transaction.value < 0).scalar()
                           or Decimal('0'))
        actualIncomes = tq.filter(
            Transaction.value >= 0).scalar() or Decimal('0')

        balance = query(func.sum(Account.balance),
                        Account).scalar() or Decimal('0')
        anticipated_balance = balance + (query(func.sum(
            Transaction.value)).filter(
                Transaction.coming == True, Transaction.rdate < end_date,
                Transaction.deleted == None).scalar() or Decimal('0'))

        income = self.compute_projection(query, start_date, end_date, True)
        outcome = self.compute_projection(query, start_date, end_date, False)

        balanceL = anticipated_balance + income['catsum'] + income[
            'predsumL'] - outcome['catsum'] - outcome['predsumL']
        balanceH = anticipated_balance + income['catsum'] + income[
            'predsumH'] - outcome['catsum'] - outcome['predsumH']
        balanceA = anticipated_balance + income['catsum'] + income[
            'predsumA'] - outcome['catsum'] - outcome['predsumA']

        restL = (actualIncomes + income['catsum'] + income['predsumL']) - (
            actualExpenses + outcome['catsum'] + outcome['predsumL'])
        restH = (actualIncomes + income['catsum'] + income['predsumH']) - (
            actualExpenses + outcome['catsum'] + outcome['predsumH'])
        restA = (actualIncomes + income['catsum'] + income['predsumA']) - (
            actualExpenses + outcome['catsum'] + outcome['predsumA'])

        response = {
            'actualExpenses': -int(round(actualExpenses)),
            'anticipatedExpenses': -int(round(outcome['sum'])),
            'actualIncomes': int(round(actualIncomes)),
            'anticipatedIncomes': int(round(income['sum'])),
            'actualBalance': int(round(anticipated_balance)),
            'anticipatedBalanceMin': int(round(balanceL)),
            'anticipatedBalanceMax': int(round(balanceH)),
            'anticipatedBalance': int(round(balanceA)),
            'actualResult': int(round(actualIncomes - actualExpenses)),
            'anticipatedResultMin': int(round(restL)),
            'anticipatedResultMax': int(round(restH)),
            'anticipatedResult': int(round(restA)),
            'anticipatedVarExpensesMin': -int(round(outcome['predsumL'])),
            'anticipatedVarExpensesMax': -int(round(outcome['predsumH'])),
            'anticipatedVarExpenses': -int(round(outcome['predsumA'])),
            'totalFixedExpenses': -int(round(outcome['catsum'])),
            'expenses': self.format_clusters(outcome['categories']),
            'anticipatedVarIncomesMin': int(round(income['predsumL'])),
            'anticipatedVarIncomesMax': int(round(income['predsumH'])),
            'anticipatedVarIncomes': int(round(income['predsumA'])),
            'totalFixedIncomes': int(round(income['catsum'])),
            'incomes': self.format_clusters(income['categories']),
            'anticipatedValuesDate': end_date,
            'balances': [],
        }

        start_date = today - timedelta(days=2 * 30)
        end_date = today + timedelta(days=1 * 30)
        predictions = {
            r[0]: {
                'mean_amount': r[1],
                'std_amount': r[2]
            }
            for r in query(Prediction.day, func.sum(Prediction.mean_amount),
                           func.sum(Prediction.std_amount)).group_by(
                               Prediction.day)
        }

        date = start_date
        while date <= end_date:
            data = {}
            data['date'] = date
            data['value'] = balance - (query(
                func.sum(Transaction.value)).filter(
                    Transaction.rdate > date, Transaction.coming == False,
                    Transaction.deleted == None).scalar() or Decimal('0'))
            data['value'] += query(func.sum(Transaction.value)).filter(
                Transaction.coming == True, Transaction.rdate < date,
                Transaction.deleted == None).scalar() or Decimal('0')
            if date > today:
                bmin = bmax = data['value']
                d = today
                last_pred = None
                while d < date:
                    try:
                        pred = predictions[d.day - 1]
                    except KeyError:
                        pred = {
                            'mean_amount': Decimal('0.0'),
                            'std_amount': Decimal('0.0')
                        }

                    if last_pred is not None:
                        if d.day != 1:
                            bmin += (
                                last_pred['mean_amount'] - pred['mean_amount']
                            ) - (last_pred['std_amount'] - pred['std_amount'])
                            bmax += (
                                last_pred['mean_amount'] - pred['mean_amount']
                            ) + (last_pred['std_amount'] - pred['std_amount'])
                    last_pred = pred

                    for lines in chain(outcome['categories'].itervalues(),
                                       income['categories'].itervalues()):
                        for line in lines:
                            if not line['tdate']:
                                continue

                            if not line['disabled'] and not line[
                                    'debited'] and line['tdate'] == d:
                                bmin += line['value']
                                bmax += line['value']
                    d += timedelta(days=1)

                data['value'] = (bmin + bmax) / 2

            data['value'] = int(round(data['value']))

            response['balances'].append(data)
            date += timedelta(days=2)

        first_date, last_date = query(func.min(Transaction.date),
                                      func.max(Transaction.date)).one()
        if not all([first_date, last_date
                    ]) or (last_date - first_date).days < 90:
            response['warning'] = True

        return JsonResponse(response)

    def format_clusters(self, categories):
        operations = []
        for id, ops in categories.iteritems():
            if not id:
                id = 9998

            for op in ops:
                if not op['tdate']:
                    continue

                no = {
                    'wording': op['text'],
                    'value': int(round(op['cluster'].mean_amount)),
                    'date': op['tdate'],
                    'done': op['debited'],
                    'category': None,
                }
                if op['category']:
                    no['category'] = {
                        'id': op['category'].id,
                        'name': op['category'].name,
                        'color': op['category'].color,
                    }
                else:
                    no['category'] = {
                        'id': 9998,
                        'name': u'Indéfini',
                        'color': 'D7D3BC',
                    }
                operations.append(no)

        operations.sort(key=lambda no: no['date'])
        return operations
Ejemplo n.º 23
0
    def __init__(self):
        self.handlers = {
            "contest": ContestHandler(),
            "info": InfoHandler(),
            "upload": UploadHandler(),
            "admin": AdminHandler(),
        }

        # The router tries to match the rules, the endpoint MUST be a string
        # with this format
        #     CONTROLLER#ACTION
        # Where CONTROLLER is an handler registered in self.handlers and
        # ACTION is a valid
        # method of that handler
        self.router = Map([
            Rule("/contest", methods=["GET"], endpoint="info#get_contest"),
            Rule("/input/<input_id>",
                 methods=["GET"],
                 endpoint="info#get_input"),
            Rule("/output/<output_id>",
                 methods=["GET"],
                 endpoint="info#get_output"),
            Rule("/source/<source_id>",
                 methods=["GET"],
                 endpoint="info#get_source"),
            Rule(
                "/submission/<submission_id>",
                methods=["GET"],
                endpoint="info#get_submission",
            ),
            Rule("/user/<token>", methods=["GET"], endpoint="info#get_user"),
            Rule(
                "/user/<token>/submissions/<task>",
                methods=["GET"],
                endpoint="info#get_submissions",
            ),
            Rule(
                "/generate_input",
                methods=["POST"],
                endpoint="contest#generate_input",
            ),
            Rule("/submit", methods=["POST"], endpoint="contest#submit"),
            Rule(
                "/internet_detected",
                methods=["POST"],
                endpoint="contest#internet_detected",
            ),
            Rule("/upload_source",
                 methods=["POST"],
                 endpoint="upload#upload_source"),
            Rule("/upload_output",
                 methods=["POST"],
                 endpoint="upload#upload_output"),
            Rule("/admin/upload_pack",
                 methods=["POST"],
                 endpoint="admin#upload_pack"),
            Rule(
                "/admin/download_results",
                methods=["POST"],
                endpoint="admin#download_results",
            ),
            Rule("/admin/login", methods=["POST"], endpoint="admin#login"),
            Rule("/admin/log", methods=["POST"], endpoint="admin#log"),
            Rule("/admin/append_log",
                 methods=["POST"],
                 endpoint="admin#append_log"),
            Rule("/admin/start", methods=["POST"], endpoint="admin#start"),
            Rule(
                "/admin/set_extra_time",
                methods=["POST"],
                endpoint="admin#set_extra_time",
            ),
            Rule("/admin/status", methods=["POST"], endpoint="admin#status"),
            Rule("/admin/pack_status",
                 methods=["GET"],
                 endpoint="admin#pack_status"),
            Rule("/admin/user_list",
                 methods=["POST"],
                 endpoint="admin#user_list"),
            Rule(
                "/admin/drop_contest",
                methods=["POST"],
                endpoint="admin#drop_contest",
            ),
        ])
Ejemplo n.º 24
0
    def __init__(self):
        QuickSettings.__init__(self)

        self.routes = ([
            Rule('/disabled/notthere', endpoint='disabled:NotThere'),
        ])
Ejemplo n.º 25
0
@app.route('/scripts/<fn>')
def script(fn):
    try:
        if not fn.endswith('.js'):
            return ''

        fn = 'scripts/' + fn[:-3]
        if os.path.exists(fn + '.js'):
            return file(fn + '.js', 'rb').read()
        return ''
    except:
        import traceback
        traceback.print_exc()


app.url_map.add(Rule('/x/<link>', endpoint='hit'))


@app.endpoint('hit')
def hit(link):
    if '.' in link:
        link, ext = link.split('.', 1)
    else:
        ext = ''

    req = '%s %s HTTP/1.1\r\n' % (request.method, request.url)
    for k, v in request.headers:
        req += '%s: %s\r\n' % (k, v)
    req += '\r\n'
    req += request.get_data()
Ejemplo n.º 26
0
def add(url, endpoint):
    rule = Rule(url, endpoint=endpoint)
    _url_map.add(rule)
Ejemplo n.º 27
0
from werkzeug.routing import Map, Rule
from sqlalchemy import MetaData
from sqlalchemy.orm import create_session, scoped_session


TEMPLATE_PATH = path.join(path.dirname(__file__), 'templates')
STATIC_PATH = path.join(path.dirname(__file__), 'static')
ALLOWED_SCHEMES = frozenset(['http', 'https', 'ftp', 'ftps'])
URL_CHARS = 'abcdefghijkmpqrstuvwxyzABCDEFGHIJKLMNPQRST23456789'

local = Local()
local_manager = LocalManager([local])
application = local('application')

metadata = MetaData()
url_map = Map([Rule('/static/<file>', endpoint='static', build_only=True)])

session = scoped_session(lambda: create_session(application.database_engine,
                                                autocommit=False,
                                                autoflush=False))
jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_PATH))


def expose(rule, **kw):
    def decorate(f):
        kw['endpoint'] = f.__name__
        url_map.add(Rule(rule, **kw))
        return f

    return decorate
 def __init__(self, nichtparasoup: NichtParasoup):
     super().__init__(nichtparasoup)
     self.url_map = Map([
         Rule("/", redirect_to="/index.html"),
         Rule('/get', endpoint=self.on_get),
     ])
Ejemplo n.º 29
0
"""
import time
from os import path
from threading import Thread
from cupoftee.db import Database
from cupoftee.network import ServerBrowser
from werkzeug.templates import Template
from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import SharedDataMiddleware
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.routing import Map, Rule


templates = path.join(path.dirname(__file__), 'templates')
pages = {}
url_map = Map([Rule('/shared/<file>', endpoint='shared')])


def make_app(database, interval=60):
    return SharedDataMiddleware(Cup(database), {
        '/shared':  path.join(path.dirname(__file__), 'shared')
    })


class PageMeta(type):

    def __init__(cls, name, bases, d):
        type.__init__(cls, name, bases, d)
        if d.get('url_rule') is not None:
            pages[cls.identifier] = cls
            url_map.add(Rule(cls.url_rule, endpoint=cls.identifier,
Ejemplo n.º 30
0
    def __init__(self, package_name):
        #: the debug flag.  Set this to `True` to enable debugging of
        #: the application.  In debug mode the debugger will kick in
        #: when an unhandled exception ocurrs and the integrated server
        #: will automatically reload the application if changes in the
        #: code are detected.
        self.debug = False

        #: the name of the package or module.  Do not change this once
        #: it was set by the constructor.
        self.package_name = package_name

        #: where is the app root located?
        self.root_path = _get_package_path(self.package_name)

        #: a dictionary of all view functions registered.  The keys will
        #: be function names which are also used to generate URLs and
        #: the values are the function objects themselves.
        #: to register a view function, use the :meth:`route` decorator.
        self.view_functions = {}

        #: a dictionary of all registered error handlers.  The key is
        #: be the error code as integer, the value the function that
        #: should handle that error.
        #: To register a error handler, use the :meth:`errorhandler`
        #: decorator.
        self.error_handlers = {}

        #: a list of functions that should be called at the beginning
        #: of the request before request dispatching kicks in.  This
        #: can for example be used to open database connections or
        #: getting hold of the currently logged in user.
        #: To register a function here, use the :meth:`before_request`
        #: decorator.
        self.before_request_funcs = []

        #: a list of functions that are called at the end of the
        #: request.  Tha function is passed the current response
        #: object and modify it in place or replace it.
        #: To register a function here use the :meth:`after_request`
        #: decorator.
        self.after_request_funcs = []

        #: a list of functions that are called without arguments
        #: to populate the template context.  Each returns a dictionary
        #: that the template context is updated with.
        #: To register a function here, use the :meth:`context_processor`
        #: decorator.
        self.template_context_processors = [_default_template_ctx_processor]

        self.url_map = Map()

        if self.static_path is not None:
            self.url_map.add(
                Rule(self.static_path + '/<filename>',
                     build_only=True,
                     endpoint='static'))
            if pkg_resources is not None:
                target = (self.package_name, 'static')
            else:
                target = os.path.join(self.root_path, 'static')
            self.wsgi_app = SharedDataMiddleware(self.wsgi_app,
                                                 {self.static_path: target})

        #: the Jinja2 environment.  It is created from the
        #: :attr:`jinja_options` and the loader that is returned
        #: by the :meth:`create_jinja_loader` function.
        self.jinja_env = Environment(loader=self.create_jinja_loader(),
                                     **self.jinja_options)
        self.jinja_env.globals.update(
            url_for=url_for, get_flashed_messages=get_flashed_messages)