本文整理汇总了Python中itsdangerous.URLSafeSerializer.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python URLSafeSerializer.dumps方法的具体用法?Python URLSafeSerializer.dumps怎么用?Python URLSafeSerializer.dumps使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itsdangerous.URLSafeSerializer
的用法示例。
在下文中一共展示了URLSafeSerializer.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_api_key
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def get_api_key(request):
s1 = URLSafeSerializer(settings.API_SECRET, salt="rolf-ipaddress-key")
k1 = s1.dumps(dict(username=request.user.username, remote_addr=request.META["REMOTE_ADDR"]))
s2 = URLSafeTimedSerializer(settings.API_SECRET, salt="rolf-timed-key")
k2 = s2.dumps(dict(username=request.user.username))
k3 = None
ip = request.GET.get("ip", None)
if ip:
k3 = s1.dumps(dict(username=request.user.username, remote_addr=ip))
return dict(k1=k1, k2=k2, k3=k3, ip=ip, remote_addr=request.META["REMOTE_ADDR"])
示例2: resetpassword
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def resetpassword():
form = PasswordResetForm()
if form.validate_on_submit():
if form.username.data:
user = Users.query.filter_by(username=form.username.data).first()
elif form.email.data:
user = Users.query.filter_by(email=form.email.data).first()
else:
flash("Username or password doesn't exists")
if user:
if user.email:
s = URLSafeSerializer('serliaizer_code')
key = s.dumps([user.username, user.email])
msg = Message("Password reset", sender="[email protected]_host.com", recipients=[user.email])
msg.html = "<b>Click on this link to reset your password.</b> \
#<a href='http://127.0.0.1:5000/passwordreset/ \
" + key + "'>http://127.0.0.1:5000/passwordreset/ \
" + key + "</a>"
send_async_email(msg)
flash('Email sent to: ' + user.email)
return redirect(url_for('resetpassword'))
else:
flash('No such user')
return redirect(url_for('resetpassword'))
flash(u'Enter your email or username')
return render_template('reset_password.html', form=form)
示例3: login_as_user
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def login_as_user(id):
s = URLSafeSerializer(app.config['SECRET_KEY'])
payload = {"id": id, "stamp": time.time()}
token = s.dumps(payload)
pieces = [app.config["LIME_URL"], 'trowel', token]
url = '/'.join(piece.strip('/') for piece in pieces)
return redirect(url)
示例4: send_confirmmail_to_unregistered_users
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def send_confirmmail_to_unregistered_users(items):
"""Send a confirmation email for external signups(email only)
Args:
item: The item, which was just inserted into the database
"""
for item in items:
if 'user' not in item:
event = current_app.data.find_one(
'events', None,
**{current_app.config['ID_FIELD']: item['event']})
title = event.get('title_en') or event.get('title_de')
s = URLSafeSerializer(get_token_secret())
token = s.dumps(str(item['_id']))
if current_app.config.get('SERVER_NAME') is None:
current_app.logger.warning("SERVER_NAME is not set. E-Mail "
"links will not work!")
confirm_link = url_for('emails.on_confirm_email', token=token,
_external=True)
mail([item['email']],
'Registration for %s' % title,
current_app.config['CONFIRM_EMAIL_TEXT'].format(
title=title,
link=confirm_link))
示例5: create_reset_link
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def create_reset_link(user):
l = "http://localhost:5001/reset/"
s = URLSafeSerializer("hacker-bees")
token = s.dumps(user.id)
l += token
user.reset_time = datetime.today()
return l
示例6: register
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def register():
form = RegisterUserForm()
if form.validate_on_submit():
user = User.create(
username=form.data['username'],
email=form.data['email'],
password=form.data['password'],
remote_addr=request.remote_addr,
)
s = URLSafeSerializer(current_app.secret_key)
token = s.dumps(user.id)
send_registration_email.delay(user, token)
flash(
gettext(
'Sent verification email to {email}'.format(
email=user.email
)
),
'success'
)
return redirect(url_for('index'))
return render_template('register.html', form=form)
示例7: new_task
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def new_task(app_id):
# Check if the request has an arg:
try:
app = db.session.query(model.App).get(app_id)
if app is None:
raise NotFound
if request.args.get('offset'):
offset = int(request.args.get('offset'))
else:
offset = 0
user_id = None if current_user.is_anonymous() else current_user.id
user_ip = request.remote_addr if current_user.is_anonymous() else None
task = sched.new_task(app_id, user_id, user_ip, offset)
# If there is a task for the user, return it
if task:
s = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
r = make_response(json.dumps(task.dictize()))
r.mimetype = "application/json"
cookie_id = 'task_run_for_task_id_%s' % task.id
r.set_cookie(cookie_id, s.dumps(task.dictize()))
return r
else:
return Response(json.dumps({}), mimetype="application/json")
except Exception as e:
return error.format_exception(e, target='app', action='GET')
示例8: generate_auth_token
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def generate_auth_token(self):
"""generate a token"""
s = Serializer(
current_app.config['SECRET_KEY']
# expiration
)
return s.dumps({'id': self.id})
示例9: send_invite
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def send_invite(user):
s = URLSafeSerializer(app.config['SECRET_KEY'])
payload = s.dumps(str(user.id))
link_href = url_for("root.confirm", payload=payload, _external=True)
InviteEmail(user.email, link_href).send()
flash("Successfully sent invitation.")
示例10: resetpassword
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def resetpassword():
form = PasswordResetForm()
if form.validate_on_submit():
if form.username.data:
user = Users.query.filter_by(username=form.username.data).first()
elif form.email.data:
user = Users.query.filter_by(email=form.email.data).first()
else:
flash("Username or password not in system")
if user:
if user.email:
s = URLSafeSerializer('12fe454t')
key = s.dumps([user.username, user.email])
#s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo')
msg = Message("Password reset", sender="[email protected]", recipients=[user.email])
msg.html = "<b>testing</b> \
#<a href='http://127.0.0.1:5000/passwordreset/" + key + "'>http://127.0.0.1:5000/passwordreset/" + key + "</a>"
print msg.html
mail.send(msg)
flash('Email sent to: ' + user.email)
return redirect(url_for('resetpassword'))
else:
flash('No such user')
return redirect(url_for('resetpassword'))
else:
flash('No such user')
return redirect(url_for('resetpassword'))
return render_template('reset_password.html', form=form)
示例11: get_context_data
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def get_context_data(self, **kwargs):
context = super(AlbumView, self).get_context_data(**kwargs)
serializer = URLSafeSerializer(settings.SECRET_KEY)
token = serializer.dumps({'album_id': self.object.id})
context['token'] = token
context['album'] = self.object
return context
示例12: reset_request
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def reset_request(self, **kw):
user = model.provider.query(app_model.User, filters=dict(email_address=kw['email_address']))[1][0]
password_frag = user.password[0:4]
serializer = URLSafeSerializer(tg.config['beaker.session.secret'])
serialized_data = serializer.dumps(dict(request_date=datetime.utcnow().strftime('%m/%d/%Y %H:%M'),
email_address=kw['email_address'], password_frag=password_frag))
password_reset_link = tg.url(self.mount_point + "/change_password/", params=dict(data=serialized_data),
qualified=True)
reset_password_config = tg.config.get('_pluggable_resetpassword_config')
mail_body = reset_password_config.get('mail_body', _('''
We've received a request to reset the password for this account.
Please click this link to reset your password:
%(password_reset_link)s
If you no longer wish to make the above change, or if you did not initiate this request, please disregard and/or delete this e-mail.
'''))
email_data = {'sender': tg.config['resetpassword.email_sender'],
'subject': reset_password_config.get('mail_subject', _('Password reset request')),
'body': mail_body,
'rich': reset_password_config.get('mail_rich', '')}
tg.hooks.notify('resetpassword.on_request', args=(user, email_data, password_reset_link))
email_data['body'] = email_data['body'] % dict(password_reset_link=password_reset_link)
email_data['rich'] = email_data['rich'] % dict(password_reset_link=password_reset_link)
send_email(user.email_address, **email_data)
flash(_('Password reset request sent'))
return plug_redirect('resetpassword', '/')
示例13: toggle_choice
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def toggle_choice(request):
campaign = get_active_campaign_or_404()
volunteer = get_object_or_404(Volunteer, pk=request.POST.get('volunteer_id'))
with transaction.atomic():
cursor = connection.cursor()
cursor.execute('LOCK TABLE %s' % VolunteerCampaign._meta.db_table)
created = False
try:
obj = VolunteerCampaign.objects.get(
Q(accepted__isnull=True) | Q(accepted=True),
campaign=campaign, volunteer=volunteer,
)
except VolunteerCampaign.DoesNotExist:
obj, created = VolunteerCampaign.objects.get_or_create(
campaign=campaign, volunteer=volunteer,
organisation=request.user.organisation,
)
if created:
serializer = URLSafeSerializer(settings.SECRET_KEY)
confirm_invite_url = reverse('confirm_invite', args=[serializer.dumps(obj.pk)])
get_adapter().send_mail('emails/volunteer_invitation', volunteer.user.email, {
'organisation': request.user.organisation,
'confirm_invite_url': request.build_absolute_uri(confirm_invite_url),
})
state, label = get_volunteer_status(obj, request.user.organisation)
return JsonResponse({
'state': state,
'label': label,
})
示例14: resend_activation_email
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def resend_activation_email(email_to_activate):
"""
Function to resend the activation email
"""
#check local database
loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username==email_to_activate) #@UndefinedVariable
#get the user object
user_rec = loc_db_user.first()
if user_rec:
#create an itsdangerous object to sign the verification email
itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)
#send the confirmation email
act_code = itsd.dumps(email_to_activate)
message_html = """<h3>Dear %(name)s %(lastname)s, thank you for registering to the NASA ADS</h3>
<p>Your activation code is <strong>%(code)s</strong></p>
<p>To activate your account, please click <a href="%(act_url)s">here</a></p>
<p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(act_url)s</p>
<p>Please do not replay to this email: to contact us please use our <a href="%(feedb_url)s">feedback form</a></p>
<p>Regards,<br/>The ADS team</p>
""" % {'name':user_rec.firstname, 'lastname':user_rec.lastname, 'code':act_code,
'act_url': '%s%s?id=%s' % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('user.activate'), act_code),
'feedb_url' : '%s%s'%(config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('feedback.feedback'))
}
try:
send_email_to_user(u"NASA ADS Account confirmation required", message_html, [email_to_activate])
except:
app.logger.error('Failed to re-send confirmation email for user creation')
return False, 'There are some technical problems: please try later.', 'error'
return True, 'A new email with the activation code has been sent to your email address.', 'success'
else:
app.logger.error('Tried to re-send confirmation email for user creation for user not yet created or not stored in the DB. Email used %s' % email_to_activate)
return False, 'The user with the given email does not exist', 'error'
示例15: generate_jwt
# 需要导入模块: from itsdangerous import URLSafeSerializer [as 别名]
# 或者: from itsdangerous.URLSafeSerializer import dumps [as 别名]
def generate_jwt(claims, lifetime=None, expires=None, not_before=None):
"""
Generate a JSON Web Token.
- **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC.
- **iat** (*IntDate*) -- The UTC date and time at which the token was generated.
- **nbf** (*IntDate*) -- The UTC valid-from date and time of the token.
- **jti** (*str*) -- A unique identifier for the token.
"""
claims = dict(claims)
now = datetime.utcnow()
claims['iat'] = timegm(now.utctimetuple())
claims['nbf'] = timegm((not_before or now).utctimetuple())
claims['jti'] = urlsafe_b64encode(urandom(128))
if lifetime:
claims['exp'] = timegm((now + lifetime).utctimetuple())
elif expires:
claims['exp'] = timegm(expires.utctimetuple())
signer = URLSafeSerializer(SECRET_KEY)
return signer.dumps(claims)