本文整理汇总了Python中website.util.web_url_for函数的典型用法代码示例。如果您正苦于以下问题:Python web_url_for函数的具体用法?Python web_url_for怎么用?Python web_url_for使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了web_url_for函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: auth_login
def auth_login(auth, **kwargs):
"""If GET request, show login page. If POST, attempt to log user in if
login form passsed; else send forgot password email.
"""
next_url = request.args.get('next')
if auth.logged_in:
if not request.args.get('logout'):
if next_url:
return redirect(next_url)
return redirect(web_url_for('dashboard'))
# redirect user to CAS for logout, return here w/o authentication
return auth_logout(redirect_url=request.url)
if kwargs.get('first', False):
status.push_status_message('You may now log in', 'info')
status_message = request.args.get('status', '')
if status_message == 'expired':
status.push_status_message('The private link you used is expired.')
code = http.OK
if next_url:
status.push_status_message(language.MUST_LOGIN)
# Don't raise error if user is being logged out
if not request.args.get('logout'):
code = http.UNAUTHORIZED
# set login_url to form action, upon successful authentication specifically w/o logout=True,
# allows for next to be followed or a redirect to the dashboard.
redirect_url = web_url_for('auth_login', next=next_url, _absolute=True)
login_url = cas.get_login_url(redirect_url, auto=True)
return {'login_url': login_url}, code
示例2: user_account_password
def user_account_password(auth, **kwargs):
user = auth.user
old_password = request.form.get('old_password', None)
new_password = request.form.get('new_password', None)
confirm_password = request.form.get('confirm_password', None)
# It has been more than 1 hour since last invalid attempt to change password. Reset the counter for invalid attempts.
if throttle_period_expired(user.change_password_last_attempt, settings.TIME_RESET_CHANGE_PASSWORD_ATTEMPTS):
user.reset_old_password_invalid_attempts()
# There have been more than 3 failed attempts and throttle hasn't expired.
if user.old_password_invalid_attempts >= settings.INCORRECT_PASSWORD_ATTEMPTS_ALLOWED and not throttle_period_expired(user.change_password_last_attempt, settings.CHANGE_PASSWORD_THROTTLE):
push_status_message(
message='Too many failed attempts. Please wait a while before attempting to change your password.',
kind='warning',
trust=False
)
return redirect(web_url_for('user_account'))
try:
user.change_password(old_password, new_password, confirm_password)
if user.verification_key_v2:
user.verification_key_v2['expires'] = timezone.now()
user.save()
except ChangePasswordError as error:
for m in error.messages:
push_status_message(m, kind='warning', trust=False)
else:
push_status_message('Password updated successfully.', kind='success', trust=False)
user.save()
return redirect(web_url_for('user_account'))
示例3: test_get_revisions
def test_get_revisions(self):
with patch_client('website.addons.dropbox.views.crud.get_node_addon_client'):
path = 'foo.rst'
url = self.project.api_url_for('dropbox_get_revisions', path=path)
res = self.app.get(url, auth=self.user.auth)
json_data = res.json
result = json_data['result']
expected = [
rev for rev in mock_responses['revisions']
if not rev.get('is_deleted')
]
assert_equal(len(result), len(expected))
for each in result:
download_link = each['download']
assert_equal(
download_link,
web_url_for(
'dropbox_download',
pid=self.project._primary_key,
path=path, rev=each['rev']
)
)
view_link = each['view']
assert_equal(
view_link,
web_url_for(
'dropbox_view_file',
pid=self.project._primary_key,
path=path, rev=each['rev']
)
)
示例4: auth_login
def auth_login(auth, **kwargs):
"""If GET request, show login page. If POST, attempt to log user in if
login form passsed; else send forgot password email.
"""
campaign = request.args.get('campaign')
next_url = request.args.get('next')
if campaign:
next_url = campaigns.campaign_url_for(campaign)
if auth.logged_in:
if not request.args.get('logout'):
if next_url:
return redirect(next_url)
return redirect(web_url_for('dashboard'))
# redirect user to CAS for logout, return here w/o authentication
return auth_logout(redirect_url=request.url)
if kwargs.get('first', False):
status.push_status_message('You may now log in', 'info')
status_message = request.args.get('status', '')
if status_message == 'expired':
status.push_status_message('The private link you used is expired.')
if next_url:
status.push_status_message(language.MUST_LOGIN)
# set login_url to form action, upon successful authentication specifically w/o logout=True,
# allows for next to be followed or a redirect to the dashboard.
redirect_url = web_url_for('auth_login', next=next_url, _absolute=True)
data = {}
if campaign and campaign in campaigns.CAMPAIGNS:
data['campaign'] = campaign
data['login_url'] = cas.get_login_url(redirect_url, auto=True)
return data, http.OK
示例5: confirm_email_get
def confirm_email_get(token, auth=None, **kwargs):
"""View for email confirmation links.
Authenticates and redirects to user settings page if confirmation is
successful, otherwise shows an "Expired Link" error.
methods: GET
"""
user = User.load(kwargs['uid'])
is_merge = 'confirm_merge' in request.args
is_initial_confirmation = not user.date_confirmed
if user is None:
raise HTTPError(http.NOT_FOUND)
if auth and auth.user and (auth.user._id == user._id or auth.user._id == user.merged_by._id):
if not is_merge:
# determine if the user registered through a campaign
campaign = campaigns.campaign_for_user(user)
if campaign:
return redirect(
campaigns.campaign_url_for(campaign)
)
status.push_status_message(language.WELCOME_MESSAGE, 'default', jumbotron=True)
# Go to dashboard
return redirect(web_url_for('dashboard'))
status.push_status_message(language.MERGE_COMPLETE, 'success')
return redirect(web_url_for('user_account'))
try:
user.confirm_email(token, merge=is_merge)
except exceptions.EmailConfirmTokenError as e:
raise HTTPError(http.BAD_REQUEST, data={
'message_short': e.message_short,
'message_long': e.message_long
})
if is_initial_confirmation:
user.date_last_login = datetime.datetime.utcnow()
user.save()
# Send out our welcome message
mails.send_mail(
to_addr=user.username,
mail=mails.WELCOME,
mimetype='html',
user=user
)
# Redirect to CAS and authenticate the user with a verification key.
user.verification_key = security.random_string(20)
user.save()
return redirect(cas.get_login_url(
request.url,
auto=True,
username=user.username,
verification_key=user.verification_key
))
示例6: test_web_url_for_guid_case_sensitive
def test_web_url_for_guid_case_sensitive(self):
with self.app.test_request_context():
# check /project/<pid>
assert_equal('/ABCdef/', web_url_for('dummy_guid_project_view', pid='ABCdef', _guid=True))
# check /project/<pid>/node/<nid>
assert_equal('/GHIjkl/', web_url_for('dummy_guid_project_view', pid='ABCdef', nid='GHIjkl', _guid=True))
# check /profile/<pid>
assert_equal('/MNOpqr/', web_url_for('dummy_guid_profile_view', pid='MNOpqr', _guid=True))
示例7: setUp
def setUp(self):
super(TestForgotPassword, self).setUp()
self.user = UserFactory()
self.auth_user = AuthUserFactory()
self.get_url = web_url_for('forgot_password_get')
self.post_url = web_url_for('forgot_password_post')
self.user.verification_key_v2 = {}
self.user.save()
示例8: claim_user_registered
def claim_user_registered(auth, node, **kwargs):
"""View that prompts user to enter their password in order to claim
contributorship on a project.
A user must be logged in.
"""
current_user = auth.user
sign_out_url = web_url_for('auth_login', logout=True, next=request.url)
if not current_user:
return redirect(sign_out_url)
# Logged in user should not be a contributor the project
if node.is_contributor(current_user):
logout_url = web_url_for('auth_logout', redirect_url=request.url)
data = {
'message_short': 'Already a contributor',
'message_long': ('The logged-in user is already a contributor to this '
'project. Would you like to <a href="{}">log out</a>?').format(logout_url)
}
raise HTTPError(http.BAD_REQUEST, data=data)
uid, pid, token = kwargs['uid'], kwargs['pid'], kwargs['token']
unreg_user = User.load(uid)
if not verify_claim_token(unreg_user, token, pid=node._primary_key):
raise HTTPError(http.BAD_REQUEST)
# Store the unreg_user data on the session in case the user registers
# a new account
session.data['unreg_user'] = {
'uid': uid, 'pid': pid, 'token': token
}
form = PasswordForm(request.form)
if request.method == 'POST':
if form.validate():
if current_user.check_password(form.password.data):
node.replace_contributor(old=unreg_user, new=current_user)
node.save()
status.push_status_message(
'You are now a contributor to this project.',
kind='success',
trust=False
)
return redirect(node.url)
else:
status.push_status_message(language.LOGIN_FAILED, kind='warning', trust=False)
else:
forms.push_errors_to_status(form.errors)
if is_json_request():
form_ret = forms.utils.jsonify(form)
user_ret = profile_utils.serialize_user(current_user, full=False)
else:
form_ret = form
user_ret = current_user
return {
'form': form_ret,
'user': user_ret,
'signOutUrl': sign_out_url
}
示例9: claim_user_form
def claim_user_form(auth, **kwargs):
"""
View for rendering the set password page for a claimed user.
Must have ``token`` as a querystring argument.
Renders the set password form, validates it, and sets the user's password.
HTTP Method: GET, POST
"""
uid, pid = kwargs['uid'], kwargs['pid']
token = request.form.get('token') or request.args.get('token')
user = User.load(uid)
# If unregistered user is not in database, or url bears an invalid token raise HTTP 400 error
if not user or not verify_claim_token(user, token, pid):
error_data = {
'message_short': 'Invalid url.',
'message_long': 'Claim user does not exists, the token in the URL is invalid or has expired.'
}
raise HTTPError(http.BAD_REQUEST, data=error_data)
# If user is logged in, redirect to 're-enter password' page
if auth.logged_in:
return redirect(web_url_for('claim_user_registered',
uid=uid, pid=pid, token=token))
unclaimed_record = user.unclaimed_records[pid]
user.fullname = unclaimed_record['name']
user.update_guessed_names()
# The email can be the original referrer email if no claimer email has been specified.
claimer_email = unclaimed_record.get('claimer_email') or unclaimed_record.get('email')
form = SetEmailAndPasswordForm(request.form, token=token)
if request.method == 'POST':
if form.validate():
username, password = claimer_email, form.password.data
user.register(username=username, password=password)
# Clear unclaimed records
user.unclaimed_records = {}
user.verification_key = generate_verification_key()
user.save()
# Authenticate user and redirect to project page
status.push_status_message(language.CLAIMED_CONTRIBUTOR, kind='success', trust=True)
# Redirect to CAS and authenticate the user with a verification key.
return redirect(cas.get_login_url(
web_url_for('view_project', pid=pid, _absolute=True),
username=user.username,
verification_key=user.verification_key
))
else:
forms.push_errors_to_status(form.errors)
return {
'firstname': user.given_name,
'email': claimer_email if claimer_email else '',
'fullname': user.fullname,
'form': forms.utils.jsonify(form) if is_json_request() else form,
}
示例10: box_oauth_finish
def box_oauth_finish(auth, **kwargs):
"""View called when the Oauth flow is completed. Adds a new BoxUserSettings
record to the user and saves the user's access token and account info.
"""
user = auth.user
node = Node.load(session.data.pop('box_auth_nid', None))
# Handle request cancellations from Box's API
if request.args.get('error'):
flash('Box authorization request cancelled.')
if node:
return redirect(node.web_url_for('node_setting'))
return redirect(web_url_for('user_addons'))
result = finish_auth()
# If result is a redirect response, follow the redirect
if isinstance(result, BaseResponse):
return result
client = BoxClient(CredentialsV2(
result['access_token'],
result['refresh_token'],
settings.BOX_KEY,
settings.BOX_SECRET,
))
about = client.get_user_info()
oauth_settings = BoxOAuthSettings.load(about['id'])
if not oauth_settings:
oauth_settings = BoxOAuthSettings(user_id=about['id'], username=about['name'])
oauth_settings.save()
oauth_settings.refresh_token = result['refresh_token']
oauth_settings.access_token = result['access_token']
oauth_settings.expires_at = datetime.utcfromtimestamp(time.time() + 3600)
# Make sure user has box enabled
user.add_addon('box')
user.save()
user_settings = user.get_addon('box')
user_settings.oauth_settings = oauth_settings
user_settings.save()
flash('Successfully authorized Box', 'success')
if node:
# Automatically use newly-created auth
if node.has_addon('box'):
node_addon = node.get_addon('box')
node_addon.set_user_auth(user_settings)
node_addon.save()
return redirect(node.web_url_for('node_setting'))
return redirect(web_url_for('user_addons'))
示例11: claim_user_registered
def claim_user_registered(auth, node, **kwargs):
"""
View that prompts user to enter their password in order to claim being a contributor on a project.
A user must be logged in.
"""
current_user = auth.user
sign_out_url = web_url_for("auth_register", logout=True, next=request.url)
if not current_user:
return redirect(sign_out_url)
# Logged in user should not be a contributor the project
if node.is_contributor(current_user):
logout_url = web_url_for("auth_logout", redirect_url=request.url)
data = {
"message_short": "Already a contributor",
"message_long": (
"The logged-in user is already a contributor to this "
'project. Would you like to <a href="{}">log out</a>?'
).format(logout_url),
}
raise HTTPError(http.BAD_REQUEST, data=data)
uid, pid, token = kwargs["uid"], kwargs["pid"], kwargs["token"]
unreg_user = User.load(uid)
if not verify_claim_token(unreg_user, token, pid=node._primary_key):
error_data = {
"message_short": "Invalid url.",
"message_long": "The token in the URL is invalid or has expired.",
}
raise HTTPError(http.BAD_REQUEST, data=error_data)
# Store the unreg_user data on the session in case the user registers
# a new account
session.data["unreg_user"] = {"uid": uid, "pid": pid, "token": token}
form = PasswordForm(request.form)
if request.method == "POST":
if form.validate():
if current_user.check_password(form.password.data):
node.replace_contributor(old=unreg_user, new=current_user)
node.save()
status.push_status_message("You are now a contributor to this project.", kind="success", trust=False)
return redirect(node.url)
else:
status.push_status_message(language.LOGIN_FAILED, kind="warning", trust=False)
else:
forms.push_errors_to_status(form.errors)
if is_json_request():
form_ret = forms.utils.jsonify(form)
user_ret = profile_utils.serialize_user(current_user, full=False)
else:
form_ret = form
user_ret = current_user
return {"form": form_ret, "user": user_ret, "signOutUrl": sign_out_url}
示例12: claim_user_form
def claim_user_form(auth, **kwargs):
"""View for rendering the set password page for a claimed user.
Must have ``token`` as a querystring argument.
Renders the set password form, validates it, and sets the user's password.
"""
uid, pid = kwargs['uid'], kwargs['pid']
token = request.form.get('token') or request.args.get('token')
# If user is logged in, redirect to 're-enter password' page
if auth.logged_in:
return redirect(web_url_for('claim_user_registered',
uid=uid, pid=pid, token=token))
user = User.load(uid) # The unregistered user
# user ID is invalid. Unregistered user is not in database
if not user:
raise HTTPError(http.BAD_REQUEST)
# If claim token not valid, redirect to registration page
if not verify_claim_token(user, token, pid):
return redirect(web_url_for('auth_login'))
unclaimed_record = user.unclaimed_records[pid]
user.fullname = unclaimed_record['name']
user.update_guessed_names()
# The email can be the original referrer email if no claimer email has been specified.
claimer_email = unclaimed_record.get('claimer_email') or unclaimed_record.get('email')
form = SetEmailAndPasswordForm(request.form, token=token)
if request.method == 'POST':
if form.validate():
username, password = claimer_email, form.password.data
user.register(username=username, password=password)
# Clear unclaimed records
user.unclaimed_records = {}
user.verification_key = security.random_string(20)
user.save()
# Authenticate user and redirect to project page
node = Node.load(pid)
status.push_status_message(language.CLAIMED_CONTRIBUTOR.format(node=node),
kind='success',
trust=True)
# Redirect to CAS and authenticate the user with a verification key.
return redirect(cas.get_login_url(
web_url_for('user_profile', _absolute=True),
auto=True,
username=user.username,
verification_key=user.verification_key
))
else:
forms.push_errors_to_status(form.errors)
return {
'firstname': user.given_name,
'email': claimer_email if claimer_email else '',
'fullname': user.fullname,
'form': forms.utils.jsonify(form) if is_json_request() else form,
}
示例13: setUp
def setUp(self):
super(TestResetPassword, self).setUp()
self.user = AuthUserFactory()
self.another_user = AuthUserFactory()
self.osf_key = generate_verification_key()
self.user.verification_key = self.osf_key
self.user.save()
self.cas_key = None
self.get_url = web_url_for('reset_password_get', verification_key=self.osf_key)
self.get_url_invalid_key = web_url_for('reset_password_get', verification_key=generate_verification_key())
示例14: googledrive_oauth_finish
def googledrive_oauth_finish(auth, **kwargs):
"""View called when the Oauth flow is completed. Adds a new GoogleDriveUserSettings
record to the user and saves the user's access token and account info.
"""
user = auth.user
node = Node.load(session.data.pop('googledrive_auth_nid', None))
# Handle request cancellations from Google's API
if request.args.get('error'):
flash('Google Drive authorization request cancelled.')
if node:
return redirect(node.web_url_for('node_setting'))
return redirect(web_url_for('user_addons'))
user.add_addon('googledrive')
user.save()
code = request.args.get('code')
user_settings = user.get_addon('googledrive')
state = session.data.pop('googledrive_auth_state')
if state != request.args.get('state'):
raise HTTPError(http.BAD_REQUEST)
if code is None:
raise HTTPError(http.BAD_REQUEST)
auth_client = GoogleAuthClient()
token = auth_client.finish(code)
info = auth_client.userinfo(token['access_token'])
# Attempt to attach an existing oauth settings model
oauth_settings = GoogleDriveOAuthSettings.load(info['sub'])
# Create a new oauth settings model
if not oauth_settings:
oauth_settings = GoogleDriveOAuthSettings()
oauth_settings.user_id = info['sub']
oauth_settings.save()
user_settings.oauth_settings = oauth_settings
user_settings.username = info['name']
user_settings.access_token = token['access_token']
user_settings.refresh_token = token['refresh_token']
user_settings.expires_at = datetime.utcfromtimestamp(token['expires_at'])
user_settings.save()
flash('Successfully authorized Google Drive', 'success')
if node:
if node.has_addon('googledrive'):
node_addon = node.get_addon('googledrive')
node_addon.set_user_auth(user_settings)
node_addon.save()
return redirect(node.web_url_for('node_setting'))
return redirect(web_url_for('user_addons'))
示例15: auth_login
def auth_login(auth, **kwargs):
"""If GET request, show login page. If POST, attempt to log user in if
login form passsed; else send forgot password email.
"""
campaign = request.args.get('campaign')
next_url = request.args.get('next')
must_login_warning = True
if campaign:
next_url = campaigns.campaign_url_for(campaign)
if not next_url:
next_url = request.args.get('redirect_url')
must_login_warning = False
if next_url:
# Only allow redirects which are relative root or full domain, disallows external redirects.
if not (next_url[0] == '/' or next_url.startsWith(settings.DOMAIN)):
raise HTTPError(http.InvalidURL)
if auth.logged_in:
if not request.args.get('logout'):
if next_url:
return redirect(next_url)
return redirect(web_url_for('dashboard'))
# redirect user to CAS for logout, return here w/o authentication
return auth_logout(redirect_url=request.url)
if kwargs.get('first', False):
status.push_status_message('You may now log in', 'info')
status_message = request.args.get('status', '')
if status_message == 'expired':
status.push_status_message('The private link you used is expired.')
if next_url and must_login_warning:
status.push_status_message(language.MUST_LOGIN)
# set login_url to form action, upon successful authentication specifically w/o logout=True,
# allows for next to be followed or a redirect to the dashboard.
redirect_url = web_url_for('auth_login', next=next_url, _absolute=True)
data = {}
if campaign and campaign in campaigns.CAMPAIGNS:
if (campaign == 'institution' and settings.ENABLE_INSTITUTIONS) or campaign != 'institution':
data['campaign'] = campaign
data['login_url'] = cas.get_login_url(redirect_url, auto=True)
data['institution_redirect'] = cas.get_institution_target(redirect_url)
data['redirect_url'] = next_url
data['sign_up'] = request.args.get('sign_up', False)
return data, http.OK