• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python session.check_csrf_token函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid.session.check_csrf_token函数的典型用法代码示例。如果您正苦于以下问题:Python check_csrf_token函数的具体用法?Python check_csrf_token怎么用?Python check_csrf_token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了check_csrf_token函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: mappings_direct_map

def mappings_direct_map(context, request):
    check_csrf_token(request)
    db_session = request.db_session

    target_study = (
        db_session.query(studies.Study)
        .join(studies.Study.schemata)
        .filter(datastore.Schema.name == request.json['source_schema'])
        .filter(datastore.Schema.publish_date == request.json['source_schema_publish_date']).one())

    data = request.json

    if request.json['choices_mapping']:
        adj_choices_mapping = []
        for mapping in request.json['choices_mapping']:
            for name in mapping['mapped'].split(','):
                adj_choices_mapping.append({'source': name, 'target': mapping['name']})

        data['choices_mapping'] = adj_choices_mapping

    # add default review status to mapping
    status = db_session.query(models.Status).filter_by(name=u'review').one()

    mapped_obj = models.Mapping(
        study=target_study,
        status=status,
        type=u'direct',
        logic=data
    )

    db_session.add(mapped_obj)
    db_session.flush()

    return {'id': mapped_obj.id}
开发者ID:razorlabs,项目名称:occams_imports,代码行数:34,代码来源:mappings.py


示例2: delete_mappings

def delete_mappings(context, request):
    check_csrf_token(request)
    db_session = request.db_session

    mappings = request.json['mapped_delete']

    records = []

    # only delete if all records can be deleted
    for mapping in mappings:
        if mapping['deleteRow'] is True:
            try:
                mapped = db_session.query(models.Mapping).filter(
                    models.Mapping.id == mapping['mappedId']).one()

            except NoResultFound:
                request.response.status = 400
                return json.dumps(
                    {'error': 'No record found for id: '.format(
                        mapping['mappedId'])})

            except MultipleResultsFound:
                request.response.status = 400
                return json.dumps(
                    {'error': 'Multiple records found for id: '.format(
                        mapping['mappedId'])})

            else:
                records.append(mapped)

    for record in records:
        db_session.delete(record)

    return {}
开发者ID:jkrooskos,项目名称:occams_imports,代码行数:34,代码来源:mapping.py


示例3: detail

def detail(request: Request):

    # Convert base64 encoded UUID string from request path to Python UUID object
    question_uuid = slug_to_uuid(request.matchdict["question_uuid"])

    question = request.dbsession.query(Question).filter_by(uuid=question_uuid).first()
    if not question:
        raise HTTPNotFound()

    if request.method == "POST":

        # Check that CSRF token was good
        check_csrf_token(request)

        question = request.dbsession.query(Question).filter_by(uuid=question_uuid).first()
        if not question:
            raise HTTPNotFound()

        if "choice" in request.POST:
            # Extracts the form choice and turn it to UUID object
            chosen_uuid = slug_to_uuid(request.POST["choice"])
            selected_choice = question.choices.filter_by(uuid=chosen_uuid).first()
            selected_choice.votes += 1
            messages.add(request, msg="Thank you for your vote", kind="success")
            return HTTPFound(request.route_url("results", question_uuid=uuid_to_slug(question.uuid)))
        else:
            error_message = "You did not select any choice."

    return locals()
开发者ID:websauna,项目名称:myapp,代码行数:29,代码来源:views.py


示例4: edit_json

def edit_json(context, request):
    check_csrf_token(request)
    db_session = request.db_session

    form = StudySchema(context, request).from_json(request.json_body)

    if not form.validate():
        raise HTTPBadRequest(json={'errors': wtferrors(form)})

    if isinstance(context, models.StudyFactory):
        study = models.Study()
        db_session.add(study)
    else:
        study = context

    study.name = slugify(form.title.data)
    study.title = form.title.data
    study.code = form.code.data
    study.short_title = form.short_title.data
    study.consent_date = form.consent_date.data
    study.termination_schema = form.termination_form.data
    study.is_randomized = form.is_randomized.data
    study.is_blinded = \
        None if not study.is_randomized else form.is_blinded.data
    study.randomization_schema = \
        None if not study.is_randomized else form.randomization_form.data

    db_session.flush()

    return view_json(study, request)
开发者ID:jkrooskos,项目名称:occams_studies,代码行数:30,代码来源:study.py


示例5: removeListing

    def removeListing(self):
        """Deal with the listing removal page. The user is asked to give the reason they are removing
        the listing, then it is removed.
        """
        listing_id = self.request.matchdict.get('listing_id', None)

        if listing_id:
            listing = self.jobs_lib.getListingById(listing_id)
            if listing.user_id != self.request.authenticated_userid:
                return HTTPForbidden()

        myform = Form(removeSchema, buttons=('Remove Listing',))

        if self.request.method == 'POST':
            check_csrf_token(self.request)
            controls = self.request.POST.items()  # get the form controls

            try:
                appstruct = myform.validate(controls)  # call validate
            except deform.ValidationFailure as e:  # catch the exception
                return {'form':e.render()}  # re-render the form with an exception

            user = self.jobs_lib.getUserById(self.request.authenticated_userid)
            if not listing.removal_reason:
                self.jobs_lib.removeListing(user, listing, appstruct['removal_reason'])

            self.request.override_renderer = 'generic_message.mako'

            return dict(heading="Listing Removed",
                        messageList=["Your listing will no longer appear on the site.",
                                     "Thank you for using %s." % self.request.registry.settings['jobs.sitename']])
        else:
            appstruct = dict(csrf_token=self.request.session.get_csrf_token())
            return dict(form=myform.render(appstruct))
开发者ID:trimastone,项目名称:jobs,代码行数:34,代码来源:addlisting.py


示例6: delete

def delete(context, request):
    check_csrf_token(request)
    db_session = request.db_session
    db_session.remove(context)
    next_url = request.current_route_path(_route_name='imports.project_list')
    result = HTTPSeeOther(location=next_url)
    return result
开发者ID:jkrooskos,项目名称:occams_imports,代码行数:7,代码来源:project.py


示例7: upload

def upload(context, request):
    """
    Allows the user to upload a JSON file form.
    """
    check_csrf_token(request)

    db_session = request.db_session

    files = request.POST.getall('files')

    if len(files) < 1:
        raise HTTPBadRequest(json={'user_message': _(u'Nothing uploaded')})

    names = []

    for file_info in files:
        try:
            data = json.load(file_info.file)
        except ValueError:
            raise HTTPBadRequest(
                json={'user_message': _(u'Invalid file format uploaded')})
        else:
            schema = datastore.Schema.from_json(data)
            schema.publish_date = schema.retract_date = None
            db_session.add(schema)
            db_session.flush()
            names.append(schema.name)

    return get_list_data(request, names=names)
开发者ID:jkrooskos,项目名称:occams_forms,代码行数:29,代码来源:form.py


示例8: merge

def merge(request):
    '''A simple merge view. The merge.mako template does the work.'''
    s = DBSession()

    # only do a merge if we have all of the required data
    if request.params.has_key("csrf_token"):
        # check the token to prevent request forgery
        st = request.session.get_csrf_token()
        check_csrf_token(request)

        if request.params.has_key("w_pid") and request.params.has_key("l_pid"):
            w_pid = request.params.get("w_pid")
            l_pid = request.params.get("l_pid")

            # do the merge, hope for the best!
            try:
                s.execute("select merge_players(:w_pid, :l_pid)",
                    {"w_pid": w_pid, "l_pid": l_pid})

                s.commit()

                request.session.flash(
                    "Successfully merged player %s into %s!" % (l_pid, w_pid),
                    "success")

            except:
                s.rollback()

                request.session.flash(
                    "Could not merge player %s into %s." % (l_pid, w_pid),
                    "failure")

    return {}
开发者ID:dark-saber,项目名称:XonStat,代码行数:33,代码来源:admin.py


示例9: patch

def patch(context, request):
    check_csrf_token(request)
    db_session = request.db_session

    is_new = isinstance(context, models.ProjectFactory)
    project = context if not is_new else None

    schema = ProjectSchema().bind(project=project, request=request)

    try:
        data = schema.deserialize(request.POST)
    except colander.Invalid as e:
        return HTTPBadRequest(json=e.asdict())

    if is_new:
        project = models.Project(
            # We don't care about these for mappings
            short_title=data['name'],
            consent_date=date.today()
        )
        db_session.add(project)

    project.name = data['name'],
    project.title = data['title'],

    next_url = request.current_route_path(
        _route_name='imports.project_detail',
        project=project.name
    )

    result = HTTPSeeOther(location=next_url)
    return result
开发者ID:jkrooskos,项目名称:occams_imports,代码行数:32,代码来源:project.py


示例10: machine_reconfigure

def machine_reconfigure(request):
    """
    Handler for POST requests to ``/{org}/machine/{id}/reconfigure``.

    The user must be authenticated for the organisation in the URL to reach here.

    Attempt to reconfigure the specified machine with the given amount of CPU
    and RAM.
    """
    # Request must pass a CSRF test
    check_csrf_token(request)
    try:
        cpus = int(request.params['cpus'])
        ram = int(request.params['ram'])
        if cpus < 1 or ram < 1:
            raise ValueError('CPU and RAM must be at least 1')
    except (ValueError, KeyError):
        # If the user has used the UI without modification, this should never happen
        request.session.flash('Error with inputs', 'error')
        return HTTPSeeOther(location = request.route_url('machines'))
    # Reconfigure the machine
    machine_id = request.matchdict['id']
    request.active_cloud_session.reconfigure_machine(machine_id, cpus, ram)
    request.session.flash('Machine reconfigured successfully', 'success')
    return HTTPSeeOther(location = request.route_url('machines'))
开发者ID:rakesh-p,项目名称:jasmin-cloud,代码行数:25,代码来源:views.py


示例11: delete_json

def delete_json(context, request):
    check_csrf_token(request)
    dbsession = request.dbsession

    for entity in context.entities:
        dbsession.delete(entity)
    dbsession.flush()

    dbsession.delete(context)
    dbsession.flush()

    viewed = request.session.setdefault('viewed', OrderedDict())

    try:
        del viewed[context.pid]
    except KeyError:
        log.warn('This patient was never viewed in the browser')
    else:
        request.session.changed()

    msg = request.localizer.translate(
        _('Patient ${pid} was successfully removed'),
        mapping={'pid': context.pid})
    request.session.flash(msg, 'success')
    return {
        '__next__': request.current_route_path(_route_name='studies.index')
    }
开发者ID:m-martinez,项目名称:occams,代码行数:27,代码来源:patient.py


示例12: add

 def add(self):
     check_csrf_token(self.request)
     objectmap = find_objectmap(self.context)
     verb = self.request.POST['verb']
     principal_id_str = self.request.POST['principal']
     if principal_id_str in (Everyone, Authenticated):
         principal_id = principal_id_str
     else:
         try:
             principal_id = int(principal_id_str)
         except ValueError:
             principal_id = None
             
     if principal_id is None:
         self.request.sdiapi.flash('No principal selected', 'danger')
         
     else:
         if principal_id not in (Everyone, Authenticated):
             if objectmap.object_for(principal_id) is None:
                 self.request.sdiapi.flash(
                     'Unknown user or group when adding ACE',
                     'danger')
                 principal_id = None
                 
         if principal_id is not None:
             permissions = self.request.POST.getall('permissions')
             if not permissions:
                 permissions = ()
             if '-- ALL --' in permissions:
                 permissions = ALL_PERMISSIONS
             new = self.acl[:]
             new.append((verb, principal_id, permissions))
             self.acl = new
             self.request.sdiapi.flash_with_undo('New ACE added', 'success')
     return self.finish_acl_edit()
开发者ID:calwi,项目名称:substanced,代码行数:35,代码来源:acl.py


示例13: login

def login(context, request):
    login_url = request.sdiapi.mgmt_path(request.context, 'login')
    referrer = request.url
    if login_url in referrer: # pragma: no cover
        # never use the login form itself as came_from
        referrer = request.sdiapi.mgmt_path(request.root) 
    came_from = request.session.setdefault('sdi.came_from', referrer)
    login = ''
    password = ''
    if 'form.submitted' in request.params:
        try:
            check_csrf_token(request)
        except:
            request.session.flash('Failed login (CSRF)', 'error')
        else:
            login = request.params['login']
            password = request.params['password']
            principals = find_service(context, 'principals')
            users = principals['users']
            user = users.get(login)
            if user is not None and user.check_password(password):
                request.session.pop('sdi.came_from', None)
                headers = remember(request, get_oid(user))
                return HTTPFound(location = came_from, headers = headers)
            request.session.flash('Failed login', 'error')

    return dict(
        url = request.sdiapi.mgmt_path(request.root, 'login'),
        came_from = came_from,
        login = login,
        password = password,
        )
开发者ID:mindreframer,项目名称:python-pyramid-stuff,代码行数:32,代码来源:login.py


示例14: changePassword

    def changePassword(self):
        """Deal with password changes. To access the form, the correct val_token must be given as one of the
        parameters to ensure that only users with access to the email account associated with the account
        will be able to change the password.
        """
        user_id = self.request.matchdict['user_id']
        val_token = self.request.params.get('val_token', '')
        myform = deform.Form(change_schema, buttons=('submit',))
        appstruct = dict(req=dict(val_token=val_token, csrf_token=self.request.session.get_csrf_token()))
        if self.request.method == 'POST':
            check_csrf_token(self.request)
            controls = self.request.POST.items()  # get the form controls

            try:
                appstruct = myform.validate(controls)  # call validate
            except deform.ValidationFailure as e:  # catch the exception
                return {'form':e.render()}  # re-render the form with an exception

            password = appstruct['req']['password']
            val_token = appstruct['req']['val_token']
            try:
                self.jobs_lib.changePassword(user_id, password, val_token)
                self.request.override_renderer = 'generic_message.mako'
                return dict(heading="Your Password Has Been Changed",
                            messageList=["Click the Login link above to log in."])
            except jobslib.JobsPasswordChangeTokenWrongException:
                return HTTPNotFound()
        else:
            return dict(form=myform.render(appstruct))
开发者ID:trimastone,项目名称:jobs,代码行数:29,代码来源:user.py


示例15: edit_json

def edit_json(context, request):
    check_csrf_token(request)
    db_session = request.db_session

    form = EnrollmentSchema(context, request).from_json(request.json_body)

    if not form.validate():
        raise HTTPBadRequest(json={'errors': wtferrors(form)})

    if isinstance(context, models.EnrollmentFactory):
        enrollment = models.Enrollment(
            patient=context.__parent__, study=form.study.data)
    else:
        enrollment = context

    enrollment.patient.modify_date = datetime.now()
    enrollment.consent_date = form.consent_date.data
    enrollment.latest_consent_date = form.latest_consent_date.data
    enrollment.reference_number = form.reference_number.data

    if not form.study.data.termination_schema:
        enrollment.termination_date = form.termination_date.data

    db_session.flush()
    return view_json(enrollment, request)
开发者ID:davidmote,项目名称:occams_studies,代码行数:25,代码来源:enrollment.py


示例16: edit_json

def edit_json(context, request):
    """
    Add/Edit form for fields.
    """
    check_csrf_token(request)

    dbsession = request.dbsession

    form = FieldFormFactory(context, request).from_json(request.json_body)

    if not form.validate():
        raise HTTPBadRequest(json={'errors': wtferrors(form)})

    is_new = isinstance(context, models.AttributeFactory)

    if not is_new:
        attribute = context
    else:
        # Add the attribute and temporarily set to large display order
        attribute = models.Attribute(schema=context.__parent__, order=-1)
        dbsession.add(attribute)

    attribute.apply(form.data)

    if is_new:
        # now we can move the attribute
        move_json(attribute, request)

    dbsession.flush()

    return view_json(attribute, request)
开发者ID:m-martinez,项目名称:occams,代码行数:31,代码来源:field.py


示例17: wrapper

        def wrapper(cls):
            request = cls.request
            errors = cls.validation_errors = dict()
            cls.validation_results = dict()

            if request.method.upper() in self.methods:
                if self.allow_json and \
                   request.content_type.startswith('application/json'):
                    # Parse JSON body instead of HTTP POST vars
                    try:
                        params = request.json
                    except:
                        raise HTTPBadRequest
                    else:
                        # Don't verify CSRF for JSON requests, as Auth headers
                        # should always be sent.
                        self.verify_csrf = False
                elif len(self.methods) > 1:
                    params = request.params.mixed()
                else:
                    params = getattr(request, self.methods[0])

                # Validate CSRF
                if self.verify_csrf and request.method.upper() == 'POST':
                    check_csrf_token(request)
                    del params['csrf_token']

                # Validate Schema
                if self.schema:
                    try:
                        cls.validation_results = self.schema.to_python(
                            params,
                            self.state
                        )
                    except Invalid as err:
                        if NestedVariables in getattr(self.schema,
                                                      'pre_validators', []):
                            try:
                                errors = err.unpack_errors(True)
                            except:
                                errors = err.unpack_errors(False)
                        else:
                            errors = err.unpack_errors(False)

                # Validate Validators
                if self.validators:
                    for field, validator in self.validators.items():
                        try:
                            cls.validation_results[field] = \
                                validator.to_python(params.get(field),
                                                    self.state)
                        except Invalid as err:
                            errors[field] = err

                if errors:
                    cls.validation_errors = errors if isinstance(errors, dict) \
                                                   else dict(_global=errors)

            return fn(cls)
开发者ID:seedifferently,项目名称:python-pyramid-starter,代码行数:59,代码来源:validation.py


示例18: delete_json

def delete_json(context, request):
    """
    Deletes the field from the form
    """
    check_csrf_token(request)
    dbsession = request.dbsession
    dbsession.delete(context)
    return HTTPOk()
开发者ID:m-martinez,项目名称:occams,代码行数:8,代码来源:field.py


示例19: logout

 def logout(self):
     # Don't allow <img src="http://server/logout">
     assert self.request.method == "POST"
     check_csrf_token(self.request)
     self.request.session.invalidate()
     messages.add(self.request, msg="You are now logged out.", kind="success", msg_id="msg-logged-out")
     headers = forget(self.request)
     return HTTPFound(location=self.logout_redirect_view, headers=headers)
开发者ID:rmoorman,项目名称:websauna,代码行数:8,代码来源:views.py


示例20: delete_json

def delete_json(context, request):
    check_csrf_token(request)
    dbsession = request.dbsession
    dbsession.delete(context)
    dbsession.flush()
    msg = _(u'Successfully deleted: ${site}', mapping={'site': context.title})
    request.session.flash(msg)
    return HTTPOk(body=msg)
开发者ID:m-martinez,项目名称:occams,代码行数:8,代码来源:site.py



注:本文中的pyramid.session.check_csrf_token函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python settings.asbool函数代码示例发布时间:2022-05-27
下一篇:
Python security.unauthenticated_userid函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap