Python flask.request.view_args() Examples

The following are 30 code examples of flask.request.view_args(). 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: test_permissions.py    From notifications-admin with MIT License 6 votes vote down vote up
def test_user_has_permissions_for_organisation(
    client,
    mocker,
):
    user = _user_with_permissions()
    user['organisations'] = ['org_1', 'org_2']
    mocker.patch('app.user_api_client.get_user', return_value=user)
    client.login(user)

    request.view_args = {'org_id': 'org_2'}

    @user_has_permissions()
    def index():
        pass

    index() 
Example #2
Source File: test_permissions.py    From notifications-admin with MIT License 6 votes vote down vote up
def _test_permissions(
    client,
    usr,
    permissions,
    will_succeed,
    kwargs=None,
):
    request.view_args.update({'service_id': 'foo'})
    if usr:
        client.login(usr)

    decorator = user_has_permissions(*permissions, **(kwargs or {}))
    decorated_index = decorator(index)

    if will_succeed:
        decorated_index()
    else:
        try:
            if (
                decorated_index().location != '/sign-in?next=%2F' or
                decorated_index().status_code != 302
            ):
                pytest.fail("Failed to throw a forbidden or unauthorised exception")
        except (Forbidden, Unauthorized):
            pass 
Example #3
Source File: read_only.py    From huskar with MIT License 6 votes vote down vote up
def check_config_and_switch_read_only():
    method = request.method
    view_args = request.view_args
    appid = view_args and view_args.get('application_name')

    response = api_response(
        message='Config and switch write inhibit',
        status="Forbidden")
    response.status_code = 403

    if method in READ_METHOD_SET:
        return
    if request.endpoint not in config_and_switch_readonly_endpoints:
        return
    if appid and appid in settings.CONFIG_AND_SWITCH_READONLY_BLACKLIST:
        return response
    if switch.is_switched_on(SWITCH_ENABLE_CONFIG_AND_SWITCH_WRITE, True):
        return
    if appid and appid in settings.CONFIG_AND_SWITCH_READONLY_WHITELIST:
        return
    return response 
Example #4
Source File: routing.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def lazy_raise_or_redirect():
    '''
    Raise exception lazily to ensure request.endpoint is set
    Also perform redirect if needed
    '''
    if not request.view_args:
        return
    for name, value in request.view_args.items():
        if isinstance(value, NotFound):
            request.routing_exception = value
            break
        elif isinstance(value, LazyRedirect):
            new_args = request.view_args
            new_args[name] = value.arg
            new_url = url_for(request.endpoint, **new_args)
            return redirect(new_url) 
Example #5
Source File: __init__.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def log_exception(self, exc_info):
        self.logger.error("""
Path:                 %s
HTTP Method:          %s
Client IP Address:    %s
User Agent:           %s
User Platform:        %s
User Browser:         %s
User Browser Version: %s
GET args:             %s
view args:            %s
URL:                  %s
""" % (
            request.path,
            request.method,
            request.remote_addr,
            request.user_agent.string,
            request.user_agent.platform,
            request.user_agent.browser,
            request.user_agent.version,
            dict(request.args),
            request.view_args,
            request.url
        ), exc_info=exc_info) 
Example #6
Source File: pagination.py    From cookiecutter-flask-restful with MIT License 6 votes vote down vote up
def paginate(query, schema):
    page = request.args.get("page", DEFAULT_PAGE_NUMBER)
    per_page = request.args.get("page_size", DEFAULT_PAGE_SIZE)
    page_obj = query.paginate(page=page, per_page=per_page)
    next_ = url_for(
        request.endpoint,
        page=page_obj.next_num if page_obj.has_next else page_obj.page,
        per_page=per_page,
        **request.view_args
    )
    prev = url_for(
        request.endpoint,
        page=page_obj.prev_num if page_obj.has_prev else page_obj.page,
        per_page=per_page,
        **request.view_args
    )

    return {
        "total": page_obj.total,
        "pages": page_obj.pages,
        "next": next_,
        "prev": prev,
        "results": schema.dump(page_obj.items),
    } 
Example #7
Source File: test_permissions.py    From notifications-admin with MIT License 6 votes vote down vote up
def test_platform_admin_can_see_orgs_they_dont_have(
    client,
    platform_admin_user,
    mocker,
):
    platform_admin_user['organisations'] = []
    mocker.patch('app.user_api_client.get_user', return_value=platform_admin_user)
    client.login(platform_admin_user)

    request.view_args = {'org_id': 'org_2'}

    @user_has_permissions()
    def index():
        pass

    index() 
Example #8
Source File: controllers_test.py    From indico-plugins with MIT License 6 votes vote down vote up
def test_ipn_process(mocker, fail):
    rt = mocker.patch('indico_payment_paypal.controllers.register_transaction')
    post = mocker.patch('indico_payment_paypal.controllers.requests.post')
    mocker.patch('indico_payment_paypal.controllers.notify_amount_inconsistency')
    post.return_value.text = 'INVALID' if fail == 'verify' else 'VERIFIED'
    rh = RHPaypalIPN()
    rh._is_transaction_duplicated = lambda: fail == 'dup_txn'
    rh.event = MagicMock(id=1)
    rh.registration = MagicMock()
    rh.registration.getTotal.return_value = 10.00
    payment_status = {'fail': 'Failed', 'refund': 'Refunded', 'status': 'Foobar'}.get(fail, 'Completed')
    amount = '-10.00' if fail == 'negative' else '10.00'
    request.view_args = {'confId': rh.event.id}
    request.args = {'registrantId': '1'}
    request.form = {'payment_status': payment_status, 'txn_id': '12345', 'mc_gross': amount,
                    'mc_currency': 'EUR', 'business': 'foo@bar.com'}
    with PaypalPaymentPlugin.instance.plugin_context():
        rh._process()
        assert post.called
        assert rt.called == (fail is None) 
Example #9
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 #10
Source File: test_permissions.py    From notifications-admin with MIT License 6 votes vote down vote up
def test_cant_use_decorator_without_view_args(
    client,
    platform_admin_user,
    mocker,
):
    mocker.patch('app.user_api_client.get_user', return_value=platform_admin_user)
    client.login(platform_admin_user)

    request.view_args = {}

    @user_has_permissions()
    def index():
        pass

    with pytest.raises(NotImplementedError):
        index() 
Example #11
Source File: test_permissions.py    From notifications-admin with MIT License 6 votes vote down vote up
def test_user_doesnt_have_permissions_for_organisation(
    client,
    mocker,
):
    user = _user_with_permissions()
    user['organisations'] = ['org_1', 'org_2']
    mocker.patch('app.user_api_client.get_user', return_value=user)
    client.login(user)

    request.view_args = {'org_id': 'org_3'}

    @user_has_permissions()
    def index():
        pass

    with pytest.raises(Forbidden):
        index() 
Example #12
Source File: flask.py    From dodotable with MIT License 5 votes vote down vote up
def build_url(self, **kwargs):
        arg = request.args.copy()
        view_args = request.view_args
        arg.update(view_args)
        for attr in kwargs.keys():
            if attr in arg:
                arg.pop(attr)
        arg.update(kwargs.items())
        rule = request.url_rule
        result = rule.build({k: v for k, v in arg.items()})
        return result[1] 
Example #13
Source File: resource.py    From flask-rest-jsonapi with MIT License 5 votes vote down vote up
def get(self, *args, **kwargs):
        """Retrieve a collection of objects"""
        self.before_get(args, kwargs)

        qs = QSManager(request.args, self.schema)

        objects_count, objects = self.get_collection(qs, kwargs)

        schema_kwargs = getattr(self, 'get_schema_kwargs', dict())
        schema_kwargs.update({'many': True})

        self.before_marshmallow(args, kwargs)

        schema = compute_schema(self.schema,
                                schema_kwargs,
                                qs,
                                qs.include)

        result = schema.dump(objects).data

        view_kwargs = request.view_args if getattr(self, 'view_kwargs', None) is True else dict()
        add_pagination_links(result,
                             objects_count,
                             qs,
                             url_for(self.view, _external=True, **view_kwargs))

        result.update({'meta': {'count': objects_count}})

        final_result = self.after_get(result)

        return final_result 
Example #14
Source File: application.py    From fava with MIT License 5 votes vote down vote up
def url_for_current(**kwargs):
    """URL for current page with updated request args."""
    if not kwargs:
        return url_for(request.endpoint, **request.view_args)
    args = request.view_args.copy()
    args.update(kwargs)
    return url_for(request.endpoint, **args) 
Example #15
Source File: application.py    From fava with MIT License 5 votes vote down vote up
def _incognito(response):
    """Replace all numbers with 'X'."""
    if app.config.get("INCOGNITO") and response.content_type.startswith(
        "text/html"
    ):
        is_editor = (
            request.endpoint == "report"
            and request.view_args["report_name"] == "editor"
        )
        if not is_editor:
            original_text = response.get_data(as_text=True)
            response.set_data(replace_numbers(original_text))
    return response 
Example #16
Source File: base.py    From flasgger with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        view_args = kwargs.pop('view_args', {})
        self.config = view_args.get('config')
        super(APIDocsView, self).__init__(*args, **kwargs) 
Example #17
Source File: http.py    From quay with Apache License 2.0 5 votes vote down vote up
def abort(status_code, message=None, issue=None, headers=None, **kwargs):
    message = str(message) % kwargs if message else DEFAULT_MESSAGE.get(status_code, "")

    params = dict(request.view_args or {})
    params.update(kwargs)

    params["url"] = request.url
    params["status_code"] = status_code
    params["message"] = message

    # Add the user information.
    auth_context = get_authenticated_context()
    if auth_context is not None:
        message = "%s (authorized: %s)" % (message, auth_context.description)

    # Log the abort.
    logger.error("Error %s: %s; Arguments: %s" % (status_code, message, params))

    # Create the final response data and message.
    data = {}
    data["error"] = message

    if headers is None:
        headers = {}

    _abort(status_code, data, message, headers) 
Example #18
Source File: app_factory.py    From vulncode-db with Apache License 2.0 5 votes vote down vote up
def register_custom_helpers(app):
    def url_for_self(**args):
        return url_for(request.endpoint, **dict(request.view_args, **args))

    def url_for_no_querystring(endpoint, **args):
        full_url = url_for(endpoint, **args)
        return urljoin(full_url, urlparse(full_url).path)

    app.jinja_env.globals['url_for_self'] = url_for_self
    app.jinja_env.globals['is_admin'] = is_admin
    app.jinja_env.globals['url_for_no_querystring'] = url_for_no_querystring
    app.jinja_env.globals['vuln_helper'] = Vulnerability 
Example #19
Source File: local_service.py    From scfcli with Apache License 2.0 5 votes vote down vote up
def _generate_api_event(request):
        req_context = {
            'path': PathConverter.convert_path_to_api_gateway(request.endpoint),
            'httpMethod': request.method,
            'requestId': str(uuid.uuid1()),
            'sourceIp': request.remote_addr,
            'stage': 'prod',
        }

        headers = dict(request.headers)

        body = request.get_data()
        if body:
            body = body.decode('utf-8')

        queries = LocalService._generate_query_dict(request)

        event = ApigwEvent(method=request.method,
                           path=request.path,
                           path_paras=request.view_args,
                           body=body,
                           headers=headers,
                           req_context=req_context,
                           queries_dict=queries)

        return event.to_str() 
Example #20
Source File: decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def auth_required_same_user(*args, **kwargs):
    """Decorator for requiring an authenticated user to be the same as the
    user in the URL parameters. By default the user url parameter name to
    lookup is 'id', but this can be customized by passing an argument:

    @auth_require_same_user('user_id')
    @bp.route('/users/<int:user_id>/foo/<int:id>')
    def get(user_id, id):
        # do stuff

    Any keyword arguments are passed along to the @auth_required decorator,
    so roles can also be specified in the same was as it, eg:
    @auth_required_same_user('user_id', role='ROLE_ADMIN')

    Aborts with HTTP 403: Forbidden if the user-check fails
    """
    auth_kwargs = {}
    user_id_parameter_name = 'id'
    if not was_decorated_without_parenthesis(args):
        auth_kwargs = kwargs
        if args and isinstance(args[0], str):
            user_id_parameter_name = args[0]

    def wrapper(fn):
        @wraps(fn)
        @auth_required(**auth_kwargs)
        def decorated(*args, **kwargs):
            try:
                user_id = request.view_args[user_id_parameter_name]
            except KeyError:
                raise KeyError('Unable to find the user lookup parameter '
                               f'{user_id_parameter_name} in the url args')
            if not Permission(UserNeed(user_id)).can():
                abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated

    if was_decorated_without_parenthesis(args):
        return wrapper(args[0])
    return wrapper 
Example #21
Source File: flask_utils.py    From WatchPeopleCode with MIT License 5 votes vote down vote up
def url_for_other_page(page):
    args = dict(request.view_args, **request.args)
    args['page'] = page
    return url_for(request.endpoint, **args) 
Example #22
Source File: flask_utils.py    From WatchPeopleCode with MIT License 5 votes vote down vote up
def url_change_args(**kwargs):
    args = dict(request.view_args, **request.args)
    for key in kwargs.keys():
        args[key] = kwargs[key]
    return url_for(request.endpoint, **args) 
Example #23
Source File: helpers.py    From flask-blog with MIT License 5 votes vote down vote up
def page_url(page):
    """根据页码返回URL"""
    _kwargs = request.view_args
    if 'page' in _kwargs:
        _kwargs.pop('page')
    if page > 1:
        return url_for(request.endpoint, page=page, **_kwargs)
    return url_for(request.endpoint, **_kwargs) 
Example #24
Source File: app.py    From sqlalchemy-jsonapi with MIT License 5 votes vote down vote up
def prevent_edit(self):
        """ Prevent editing for no reason. """
        if request.view_args['api_type'] == 'blog-posts':
            return True
        return False 
Example #25
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _process_args(self):
        self.agent = LiveSyncAgent.get_or_404(request.view_args['agent_id'])
        if self.agent.backend is None:
            flash(_('Cannot edit an agent that is not loaded'), 'error')
            return redirect(url_for('plugins.details', plugin='livesync')) 
Example #26
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _process_args(self):
        self.backend_name = request.view_args['backend']
        try:
            self.backend = current_plugin.backend_classes[self.backend_name]
        except KeyError:
            raise NotFound 
Example #27
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _process_args(self):
        self.agent = LiveSyncAgent.get_or_404(request.view_args['agent_id']) 
Example #28
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _process_args(self):
        RHEndTimeBase._process_args(self)
        self.date = timezone(self.event.timezone).localize(datetime.strptime(request.args['selectedDay'], '%Y/%m/%d'))
        self.timetable_entry = (self.event.timetable_entries
                                .filter_by(type=TimetableEntryType.SESSION_BLOCK,
                                           id=request.view_args['entry_id'])
                                .first_or_404()) 
Example #29
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _process(self):
        size = request.args.get('size', 10)
        query = request.args.get('query')
        importer, plugin = current_plugin.importer_engines.get(request.view_args['importer_name'])
        with plugin.plugin_context():
            data = {'records': importer.import_data(query, size)}
        return jsonify(data) 
Example #30
Source File: controllers.py    From indico-plugins with MIT License 5 votes vote down vote up
def _process_args(self):
        if 'confId' in request.view_args:
            self.obj = Event.get_or_404(request.view_args['confId'], is_deleted=False)
            self.obj_type = 'event'
        elif 'category_id' in request.view_args:
            self.obj = Category.get_or_404(request.view_args['category_id'], is_deleted=False)
            self.obj_type = 'category' if not self.obj.is_root else None
        else:
            self.obj = Category.get_root()
            self.obj_type = None