Python flask.request.blueprint() Examples

The following are 16 code examples of flask.request.blueprint(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: unit.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def json(self):
        unit = [('id', self._id), ('name', self.name),
                ('description', self.description),
                ('expansion', self.expansion),
                ('age', self.age),
                ('created_in',
                '{}structure/{}'.format(request.url_root + request.blueprint,
                                        self.format_name_to_query(self.structure.first().name))
                 if self.structure.first() else self.created_in),
                ('cost', json.loads(self.cost.replace(";", ","))),
                ('build_time', self.build_time),
                ('reload_time', self.reload_time),
                ('attack_delay', self.attack_delay),
                ('movement_rate', self.movement_rate),
                ('line_of_sight', self.line_of_sight),
                ('hit_points', self.hit_points),
                ('range', int(self.range) if self.range.isdigit() else self.range),
                ('attack', self.attack), ('armor', self.armor),
                ('attack_bonus', self.attack_bonus.split(";") if self.attack_bonus else None),
                ('armor_bonus', self.armor_bonus.split(";") if self.armor_bonus else None),
                ('search_radius', self.search_radius),
                ('accuracy', self.accuracy),
                ('blast_radius', self.blast_radius)]
        return OrderedDict([(k, v) for k, v in unit if v]) 
Example #2
Source File: civilization.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def json(self):
        civilization = [('id', self._id),
                        ('name', self.name),
                        ('expansion', self.expansion),
                        ('army_type', self.army_type),
                        ('unique_unit', self.parse_array_field(self.unique_unit)
                         if not self.unit.first()
                         else ['{}unit/{}'.format(request.url_root + request.blueprint,
                                                  self.format_name_to_query(self.unit.first().name))]
                         ),
                        ('unique_tech', self.parse_array_field(self.unique_tech)
                         if not self.technology.first()
                         else ['{}technology/{}'.format(request.url_root + request.blueprint,
                               self.format_name_to_query(self.technology.first().name))]
                         ),
                        ('team_bonus', self.team_bonus),
                        ('civilization_bonus', self.civilization_bonus.split(";"))
                        ]
        return OrderedDict(civilization) 
Example #3
Source File: technology.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def map_to_resource_url(self):
        out = []
        for item in self.applies_to.split(';'):
            unit = get_model('units').query.filter_by(name=item).first()
            structure = get_model('structures').query.filter_by(name=item).first()
            civilization = get_model('civilizations').query.filter_by(name=item).first()

            if unit:
                out.append('{}unit/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(unit.name)))
            elif structure:
                out.append('{}structure/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(structure.name)))
            elif civilization:
                out.append('{}civilization/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(civilization.name)))
            else:
                out.append(item)
        return out 
Example #4
Source File: plugin.py    From indico-plugins with MIT License 6 votes vote down vote up
def _get_event_tracking_params(self):
        site_id_events = PiwikPlugin.settings.get('site_id_events')
        if not self.settings.get('enabled_for_events') or not site_id_events:
            return {}
        params = {'site_id_events': site_id_events}
        if request.blueprint in ('event', 'events', 'contributions') and 'confId' in request.view_args:
            if not unicode(request.view_args['confId']).isdigit():
                return {}
            params['event_id'] = request.view_args['confId']
            contrib_id = request.view_args.get('contrib_id')
            if contrib_id is not None and unicode(contrib_id).isdigit():
                contribution = Contribution.find_first(event_id=params['event_id'], id=contrib_id)
                if contribution:
                    cid = (contribution.legacy_mapping.legacy_contribution_id if contribution.legacy_mapping
                           else contribution.id)
                    params['contrib_id'] = '{}t{}'.format(contribution.event_id, cid)
        return params 
Example #5
Source File: extension.py    From flask-limiter with MIT License 6 votes vote down vote up
def exempt(self, obj):
        """
        decorator to mark a view or all views in a blueprint as exempt from
        rate limits.
        """
        if not isinstance(obj, Blueprint):
            name = "%s.%s" % (obj.__module__, obj.__name__)

            @wraps(obj)
            def __inner(*a, **k):
                return obj(*a, **k)

            self._exempt_routes.add(name)
            return __inner
        else:
            self._blueprint_exempt.add(obj.name) 
Example #6
Source File: civilization.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_array_field(self, field):
            out = []
            for item in [x for x in field.split(";")]:
                unit = get_model('units').query.filter_by(name=item).first()
                technology = get_model('technologies').query.filter_by(name=item).first()
                if unit:
                    out.append('{}unit/{}'.format(request.url_root + request.blueprint,
                                                  self.format_name_to_query(unit.name)))
                elif technology:
                    out.append('{}technology/{}'.format(request.url_root + request.blueprint,
                                                        self.format_name_to_query(technology.name)))
            return out 
Example #7
Source File: technology.py    From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def json(self):
        technology = [('id', self._id),
                      ('name', self.name),
                      ('description', self.description),
                      ('expansion', self.expansion),
                      ('age', self.age),
                      ('develops_in',
                      '{}structure/{}'.format(request.url_root + request.blueprint, self.format_name_to_query(self.structure.first().name))
                       if self.structure.first() else self.develops_in),
                      ('cost', json.loads(self.cost.replace(";", ","))),
                      ('build_time', self.build_time),
                      ('applies_to', self.map_to_resource_url() if self.applies_to else None),
                      ]
        return OrderedDict([(k, v) for k, v in technology if v]) 
Example #8
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def exempt(self, view):
        """Mark a view or blueprint to be excluded from CSRF protection.

        ::

            @app.route('/some-view', methods=['POST'])
            @csrf.exempt
            def some_view():
                ...

        ::

            bp = Blueprint(...)
            csrf.exempt(bp)

        """

        if isinstance(view, Blueprint):
            self._exempt_blueprints.add(view.name)
            return view

        if isinstance(view, string_types):
            view_location = view
        else:
            view_location = '%s.%s' % (view.__module__, view.__name__)

        self._exempt_views.add(view_location)
        return view 
Example #9
Source File: plugin.py    From indico-plugins with MIT License 5 votes vote down vote up
def _add_category_search_box(self, category, **kwargs):
        if request.blueprint != 'plugin_search':
            form = self.engine_plugin.search_form(prefix='search-', csrf_enabled=False)
            return render_engine_or_search_template('searchbox_category.html', category=category, form=form) 
Example #10
Source File: application.py    From fava with MIT License 5 votes vote down vote up
def _perform_global_filters() -> None:
    ledger = getattr(g, "ledger", None)
    if ledger:
        # check (and possibly reload) source file
        if request.blueprint != "json_api":
            ledger.changed()

        ledger.filter(
            account=request.args.get("account"),
            filter=request.args.get("filter"),
            time=request.args.get("time"),
        ) 
Example #11
Source File: error_handlers.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _is_api(request):
    ''' Checks if the error comes from the api '''
    return request.blueprint == 'api' or 'api' in request.url 
Example #12
Source File: angular.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def template(template_name, *dependency_urls, **initial_data):
    # find and load the template, based on the current request
    if request.blueprint:
        parent = current_app.blueprints[request.blueprint]
    else:
        parent = current_app
    if not parent.has_static_folder:
        raise RuntimeError("No static folder for angular template")
    template_path = os.path.join(parent.static_folder, template_name)
    template = open(template_path).read().decode('utf-8')

    # calculate the stylesheet and script links, based on suffix
    stylesheets = [u for u in dependency_urls if u.endswith('.css')]
    scripts = [u for u in dependency_urls if u.endswith('.js')]
    scripts.append(url_for('static', filename='js/relengapi.js'))
    if set(dependency_urls) - set(stylesheets) - set(scripts):
        raise RuntimeError("dependency_urls must all be .css and .js files")

    # include info on the current user
    user = {}
    user['permissions'] = [permissions.JsonPermission(name='.'.join(prm), doc=prm.__doc__)
                           for prm in current_user.permissions]
    user['type'] = current_user.type
    if current_user.type == 'human':
        user['authenticated_email'] = current_user.authenticated_email
    initial_data['user'] = user

    # include the full list of available permissions
    initial_data['perms'] = {str(prm): doc for prm, doc in p}

    return render_template('angular.html',
                           template=template,
                           stylesheets=stylesheets,
                           scripts=scripts,
                           initial_data=initial_data) 
Example #13
Source File: layout.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, app):
        self.extra_head_content = []

        @app.context_processor
        def _context_processor():
            if request.blueprint:
                blueprint = current_app.blueprints[request.blueprint]
            else:
                blueprint = current_app.blueprints['base']
            return {
                'blueprint': blueprint,
                'layout_extra_head_content': self.extra_head_content,
            } 
Example #14
Source File: csrf.py    From jbox with MIT License 4 votes vote down vote up
def init_app(self, app):
        self._app = app
        app.jinja_env.globals['csrf_token'] = generate_csrf
        app.config.setdefault(
            'WTF_CSRF_HEADERS', ['X-CSRFToken', 'X-CSRF-Token']
        )
        app.config.setdefault('WTF_CSRF_SSL_STRICT', True)
        app.config.setdefault('WTF_CSRF_ENABLED', True)
        app.config.setdefault('WTF_CSRF_CHECK_DEFAULT', True)
        app.config.setdefault('WTF_CSRF_METHODS', ['POST', 'PUT', 'PATCH'])

        # expose csrf_token as a helper in all templates
        @app.context_processor
        def csrf_token():
            return dict(csrf_token=generate_csrf)

        if not app.config['WTF_CSRF_ENABLED']:
            return

        if not app.config['WTF_CSRF_CHECK_DEFAULT']:
            return

        @app.before_request
        def _csrf_protect():
            # many things come from django.middleware.csrf
            if request.method not in app.config['WTF_CSRF_METHODS']:
                return

            if self._exempt_views or self._exempt_blueprints:
                if not request.endpoint:
                    return

                view = app.view_functions.get(request.endpoint)
                if not view:
                    return

                dest = '%s.%s' % (view.__module__, view.__name__)
                if dest in self._exempt_views:
                    return
                if request.blueprint in self._exempt_blueprints:
                    return

            self.protect() 
Example #15
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 4 votes vote down vote up
def init_app(self, app):
        app.extensions['csrf'] = self

        app.config.setdefault('WTF_CSRF_ENABLED', True)
        app.config.setdefault('WTF_CSRF_CHECK_DEFAULT', True)
        app.config['WTF_CSRF_METHODS'] = set(app.config.get(
            'WTF_CSRF_METHODS', ['POST', 'PUT', 'PATCH', 'DELETE']
        ))
        app.config.setdefault('WTF_CSRF_FIELD_NAME', 'csrf_token')
        app.config.setdefault(
            'WTF_CSRF_HEADERS', ['X-CSRFToken', 'X-CSRF-Token']
        )
        app.config.setdefault('WTF_CSRF_TIME_LIMIT', 3600)
        app.config.setdefault('WTF_CSRF_SSL_STRICT', True)

        app.jinja_env.globals['csrf_token'] = generate_csrf
        app.context_processor(lambda: {'csrf_token': generate_csrf})

        @app.before_request
        def csrf_protect():
            if not app.config['WTF_CSRF_ENABLED']:
                return

            if not app.config['WTF_CSRF_CHECK_DEFAULT']:
                return

            if request.method not in app.config['WTF_CSRF_METHODS']:
                return

            if not request.endpoint:
                return

            view = app.view_functions.get(request.endpoint)

            if not view:
                return

            if request.blueprint in self._exempt_blueprints:
                return

            dest = '%s.%s' % (view.__module__, view.__name__)

            if dest in self._exempt_views:
                return

            self.protect() 
Example #16
Source File: csrf.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def init_app(self, app):
        app.extensions['csrf'] = self

        app.config.setdefault('WTF_CSRF_ENABLED', True)
        app.config.setdefault('WTF_CSRF_CHECK_DEFAULT', True)
        app.config['WTF_CSRF_METHODS'] = set(app.config.get(
            'WTF_CSRF_METHODS', ['POST', 'PUT', 'PATCH', 'DELETE']
        ))
        app.config.setdefault('WTF_CSRF_FIELD_NAME', 'csrf_token')
        app.config.setdefault(
            'WTF_CSRF_HEADERS', ['X-CSRFToken', 'X-CSRF-Token']
        )
        app.config.setdefault('WTF_CSRF_TIME_LIMIT', 3600)
        app.config.setdefault('WTF_CSRF_SSL_STRICT', True)

        app.jinja_env.globals['csrf_token'] = generate_csrf
        app.context_processor(lambda: {'csrf_token': generate_csrf})

        def _set_csrf_valid_true():
            """设置验证通过, 满足 _FlaskFormCSRF.validate_csrf_token 内判断"""
            g.csrf_valid = True
            return

        @app.before_request
        def csrf_protect():
            if not app.config['WTF_CSRF_ENABLED']:
                return _set_csrf_valid_true()

            if not app.config['WTF_CSRF_CHECK_DEFAULT']:
                return _set_csrf_valid_true()

            if request.method not in app.config['WTF_CSRF_METHODS']:
                return _set_csrf_valid_true()

            if not request.endpoint:
                return _set_csrf_valid_true()

            view = app.view_functions.get(request.endpoint)

            if not view:
                return _set_csrf_valid_true()

            if request.blueprint in self._exempt_blueprints:
                return _set_csrf_valid_true()

            dest = '%s.%s' % (view.__module__, view.__name__)

            if dest in self._exempt_views:
                return _set_csrf_valid_true()

            self.protect()