本文整理汇总了Python中pyramid.session.check_csrf_token函数的典型用法代码示例。如果您正苦于以下问题:Python check_csrf_token函数的具体用法?Python check_csrf_token怎么用?Python check_csrf_token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了check_csrf_token函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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}
示例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 {}
示例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()
示例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)
示例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))
示例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
示例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)
示例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 {}
示例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
示例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'))
示例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')
}
示例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()
示例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,
)
示例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))
示例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)