本文整理汇总了Python中flask.g方法的典型用法代码示例。如果您正苦于以下问题:Python flask.g方法的具体用法?Python flask.g怎么用?Python flask.g使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.g方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_admin
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def is_admin():
""" Return whether the user is admin for this application or not. """
if not authenticated():
return False
user = flask.g.fas_user
auth_method = pagure_config.get("PAGURE_AUTH", None)
if auth_method == "fas":
if not user.cla_done:
return False
admin_users = pagure_config.get("PAGURE_ADMIN_USERS", [])
if not isinstance(admin_users, list):
admin_users = [admin_users]
if user.username in admin_users:
return True
admins = pagure_config["ADMIN_GROUP"]
if not isinstance(admins, list):
admins = [admins]
admins = set(admins or [])
groups = set(flask.g.fas_user.groups)
return not groups.isdisjoint(admins)
示例2: is_repo_admin
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def is_repo_admin(repo_obj, username=None):
""" Return whether the user is an admin of the provided repo. """
if not authenticated():
return False
if username:
user = username
else:
user = flask.g.fas_user.username
if is_admin():
return True
usergrps = [usr.user for grp in repo_obj.admin_groups for usr in grp.users]
return (
user == repo_obj.user.user
or (user in [usr.user for usr in repo_obj.admins])
or (user in usergrps)
)
示例3: admin_session_timedout
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def admin_session_timedout():
""" Check if the current user has been authenticated for more than what
is allowed (defaults to 15 minutes).
If it is the case, the user is logged out and the method returns True,
otherwise it returns False.
"""
timedout = False
if not pagure.utils.authenticated():
return True
login_time = flask.g.fas_user.login_time
# This is because flask_fas_openid will store this as a posix timestamp
if not isinstance(login_time, datetime.datetime):
login_time = datetime.datetime.utcfromtimestamp(login_time)
if (datetime.datetime.utcnow() - login_time) > pagure_config.get(
"ADMIN_SESSION_LIFETIME", datetime.timedelta(minutes=15)
):
timedout = True
logout()
return timedout
示例4: logout
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def logout():
""" Log out the user currently logged in in the application
"""
auth = pagure_config.get("PAGURE_AUTH", None)
if auth in ["fas", "openid"]:
if hasattr(flask.g, "fas_user") and flask.g.fas_user is not None:
from pagure.ui.fas_login import FAS
FAS.logout()
elif auth == "oidc":
from pagure.ui.oidc_login import oidc_logout
oidc_logout()
elif auth == "local":
import pagure.ui.login as login
login.logout()
示例5: after_request
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def after_request(response):
""" After request callback, adjust the headers returned """
csp_headers = pagure_config["CSP_HEADERS"]
try:
style_csp = "nonce-" + flask.g.nonce
script_csp = (
"unsafe-inline"
if "unsafe_javascript" in flask.g and flask.g.unsafe_javascript
else "nonce-" + flask.g.nonce
)
csp_headers = csp_headers.format(
nonce_script=script_csp, nonce_style=style_csp
)
except (KeyError, IndexError):
pass
response.headers.set(str("Content-Security-Policy"), csp_headers)
return response
示例6: confirm_user
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def confirm_user(token):
""" Confirm a user account.
"""
user_obj = pagure.lib.query.search_user(flask.g.session, token=token)
if not user_obj:
flask.flash("No user associated with this token.", "error")
else:
user_obj.token = None
flask.g.session.add(user_obj)
try:
flask.g.session.commit()
flask.flash("Email confirmed, account activated")
return flask.redirect(flask.url_for("auth_login"))
except SQLAlchemyError as err: # pragma: no cover
flask.flash(
"Could not set the account as active in the db, "
"please report this error to an admin",
"error",
)
_log.exception(err)
return flask.redirect(flask.url_for("ui_ns.index"))
示例7: get_locale
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
# user = None
if user is not None and hasattr(user, "locale"):
if user.nickname != 'Guest': # if the account is the guest account bypass the config lang settings
return user.locale
preferred = list()
if request.accept_languages:
for x in request.accept_languages.values():
try:
preferred.append(str(LC.parse(x.replace('-', '_'))))
except (UnknownLocaleError, ValueError) as e:
log.debug('Could not parse locale "%s": %s', x, e)
return negotiate_locale(preferred or ['en'], _BABEL_TRANSLATIONS)
示例8: send_onboarding_sms_messages
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def send_onboarding_sms_messages(user):
# First send the intro message
organisation = getattr(g, 'active_organisation', None) or user.default_organisation
intro_message = i18n_for(
user,
"general_sms.welcome.{}".format(organisation.custom_welcome_message_key or 'generic'),
first_name=user.first_name,
balance=rounded_dollars(user.transfer_account.balance),
token=user.transfer_account.token.name
)
send_message(user.phone, intro_message)
send_terms_message_if_required(user)
示例9: _make_initial_disbursement
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def _make_initial_disbursement(self, initial_disbursement, auto_resolve=False):
from server.utils.credit_transfer import make_payment_transfer
active_org = getattr(g, 'active_organisation', Organisation.master_organisation())
initial_disbursement = initial_disbursement or active_org.default_disbursement
if not initial_disbursement:
return None
user_id = get_authorising_user_id()
if user_id is not None:
sender = User.query.execution_options(show_all=True).get(user_id)
else:
sender = self.primary_user
disbursement = make_payment_transfer(
initial_disbursement, token=self.token, send_user=sender, receive_user=self.primary_user,
transfer_subtype=TransferSubTypeEnum.DISBURSEMENT, transfer_mode=TransferModeEnum.WEB,
is_ghost_transfer=False, require_sender_approved=False,
require_recipient_approved=False, automatically_resolve_complete=auto_resolve)
return disbursement
示例10: set_request_decorators
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def set_request_decorators(self) -> None:
# pylint: disable=inconsistent-return-statements
@self._app.before_request
def _check_for_ott_or_cookie(): # type: ignore[no-untyped-def]
if not self._ott_validated and self._ott == flask.request.args.get("ott"):
self._ott_validated = True
flask.g.set_cookie_token = True
return flask.redirect(flask.request.base_url)
if self._cookie_token == flask.request.cookies.get(
f"cookie_token_{self._port}"
):
self._ott_validated = True
else:
flask.abort(401)
@self._app.after_request
def _set_cookie_token_in_response(
response: flask.wrappers.Response,
) -> flask.wrappers.Response:
if "set_cookie_token" in flask.g and flask.g.set_cookie_token:
response.set_cookie(
key=f"cookie_token_{self._port}", value=self._cookie_token
)
return response
示例11: per_request_callbacks
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def per_request_callbacks(response):
if response.headers["Content-Type"] != "application/json":
return response
try:
data = json.loads(response.data.decode("utf8"))
validate(data, schema)
data["meta"] = data.get("meta", {})
data["meta"]["validation"] = "ok"
response.data = json.dumps(data, indent=4)
except Exception as exc:
print(exc)
response.data = b'{"result" : "validation failed"}'
for func in getattr(g, "call_after_request", ()):
response = func(response)
return response
示例12: open_changeset_error
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def open_changeset_error(place, changeset, r):
url = place.candidates_url(_external=True)
username = g.user.username
body = f'''
user: {username}
name: {place.display_name}
page: {url}
message user: https://www.openstreetmap.org/message/new/{username}
sent:
{changeset}
reply:
{r.text}
'''
send_mail('error creating changeset:' + place.name, body)
示例13: update_tag
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def update_tag(tag):
res = None
if request.method in ('PUT', 'POST'):
new_tags = request.form.getlist('tags')
result_flag = getattr(flask.g, 'bukudb', get_bukudb()).replace_tag(tag, new_tags)
op_text = 'replace tag [{}] with [{}]'.format(tag, ', '.join(new_tags))
if request.method == 'PUT' and result_flag and request.path.startswith('/api/'):
res = (jsonify(response.response_template['success']),
status.HTTP_200_OK,
{'ContentType': 'application/json'})
elif request.method == 'PUT' and request.path.startswith('/api/'):
res = (jsonify(response.response_template['failure']),
status.HTTP_400_BAD_REQUEST,
{'ContentType': 'application/json'})
elif request.method == 'POST' and result_flag:
flash(Markup('Success {}'.format(op_text)), 'success')
res = redirect(url_for('get_tags-html'))
elif request.method == 'POST':
flash(Markup('Failed {}'.format(op_text)), 'danger')
res = redirect(url_for('get_tags-html'))
else:
abort(400, description="Unknown Condition")
return res
示例14: put
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def put(self, rec_id: int):
bukudb = getattr(flask.g, 'bukudb', get_bukudb())
result_flag = bukudb.update_rec(
rec_id,
request.form.get('url'),
request.form.get('title'),
request.form.get('tags'),
request.form.get('description'))
if result_flag:
res = (jsonify(response.response_template['success']),
status.HTTP_200_OK,
{'ContentType': 'application/json'})
else:
res = (jsonify(response.response_template['failure']),
status.HTTP_400_BAD_REQUEST,
{'ContentType': 'application/json'})
return res
示例15: delete
# 需要导入模块: import flask [as 别名]
# 或者: from flask import g [as 别名]
def delete(self, rec_id: Union[int, None]):
if rec_id is None:
bukudb = getattr(flask.g, 'bukudb', get_bukudb())
with mock.patch('buku.read_in', return_value='y'):
result_flag = bukudb.cleardb()
if result_flag:
res = jsonify(response.response_template['success'])
else:
res = jsonify(response.response_template['failure'])
res.status_code = status.HTTP_400_BAD_REQUEST
else:
bukudb = getattr(flask.g, 'bukudb', get_bukudb())
result_flag = bukudb.delete_rec(rec_id)
if result_flag:
res = (jsonify(response.response_template['success']),
status.HTTP_200_OK,
{'ContentType': 'application/json'})
else:
res = (jsonify(response.response_template['failure']),
status.HTTP_400_BAD_REQUEST,
{'ContentType': 'application/json'})
return res