本文整理汇总了Python中flask.has_request_context方法的典型用法代码示例。如果您正苦于以下问题:Python flask.has_request_context方法的具体用法?Python flask.has_request_context怎么用?Python flask.has_request_context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.has_request_context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: search_filter_record_permissions
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def search_filter_record_permissions():
"""Filter list of results by `_access` and `restricted` fields."""
if not has_request_context() or backoffice_permission().allows(g.identity):
return Q()
# A record is public if `restricted` field False or missing
restricted_field_missing = ~Q("exists", field="restricted")
is_restricted = restricted_field_missing | Q("term", restricted=False)
combined_filter = is_restricted
if current_app.config.get("ILS_RECORDS_EXPLICIT_PERMISSIONS_ENABLED"):
# if `_access`, check `_access.read` against the user. It takes
# precedence over `restricted`.
# if not `_access`, check if open access as before.
_access_field_exists = Q("exists", field="_access.read")
provides = _get_user_provides()
user_can_read = _access_field_exists & Q(
"terms", **{"_access.read": provides}
)
combined_filter = user_can_read | (
~_access_field_exists & ~is_restricted
)
return Q("bool", filter=[combined_filter])
示例2: set_changed_by
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def set_changed_by(data, prev_record=None):
"""Automatically add the `created_by` and `updated_by` fields."""
if not has_request_context():
return data
changed_by = dict(type="user_id", value=str(current_user.id))
if prev_record:
# updating an already existing record
if "created_by" in prev_record:
data["created_by"] = prev_record["created_by"]
data["updated_by"] = changed_by
else:
# creating a new record
data["created_by"] = changed_by
return data
示例3: _s_columns
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def _s_columns(cls):
"""
:return: list of columns that are exposed by the api
"""
mapper = getattr(cls, "__mapper__", None)
if mapper is None:
return []
result = cls.__mapper__.columns
if has_request_context():
# In the web context we only return the attributes that are exposable and readable
# i.e. where the "expose" attribute is set on the db.Column instance
# and the "r" flag is in the permissions
result = [c for c in result if cls._s_check_perm(c.name)]
return result
示例4: error_mail
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def error_mail(subject, data, r, via_web=True):
body = '''
remote URL: {r.url}
status code: {r.status_code}
request data:
{data}
status code: {r.status_code}
content-type: {r.headers[content-type]}
reply:
{r.text}
'''.format(r=r, data=data)
if not has_request_context():
via_web = False
if via_web:
user = get_username()
body = 'site URL: {}\nuser: {}\n'.format(request.url, user) + body
send_mail(subject, body)
示例5: inject_span_in_headers
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def inject_span_in_headers(headers):
if has_request_context():
# FLASK https://github.com/opentracing-contrib/python-flask
tracer = current_app.tracer if getattr(current_app, "tracer") else None
# Add traces
span = None
current_app.app_context()
if tracer:
span = tracer.get_span(request=request)
if not span: # pragma: no cover
span = get_current_span()
if not span:
span = tracer.tracer.start_span()
context = span.context if span else None
tracer.tracer.inject(context, opentracing.Format.HTTP_HEADERS, headers)
return headers
示例6: _add_permissions_filter
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def _add_permissions_filter(self, query, model_class):
"""Filter by the users present in either the `viewers` or `owners`
lists
"""
# not used from a request handler - no relevant user
if not has_request_context():
return query
# Queries of elements that aren't resources (tenants, users, etc.),
# shouldn't be filtered
if not model_class.is_resource:
return query
# For users that are allowed to see all resources, regardless of tenant
is_admin = is_administrator(self.current_tenant)
if is_admin:
return query
# Only get resources that are public - not private (note that ~ stands
# for NOT, in SQLA), *or* those where the current user is the creator
user_filter = sql_or(
model_class.visibility != VisibilityState.PRIVATE,
model_class.creator == current_user
)
return query.filter(user_filter)
示例7: request_context_processor
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def request_context_processor(logger, method_name, event_dict) -> dict:
"""
Pre-processor for structlog which injects details about the current request and user,
if any.
"""
if has_request_context():
try:
user = dict(
username=g.user.username, id=g.user.id, is_admin=g.user.is_admin,
)
except AttributeError as exc:
user = None
event_dict = dict(
**event_dict,
user=user,
session=session,
session_id=session.get("_id", None),
request_id=request.id if hasattr(request, "id") else None
)
return event_dict
示例8: _message
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def _message(status, content):
"""Send message interface.
Parameters
----------
status : str
The type of message
content : str
"""
event = f'message.{status}'
if flask.has_request_context():
emit(event, dict(data=pack(content)))
else:
sio = flask.current_app.extensions['socketio']
sio.emit(event, dict(data=pack(content)))
eventlet.sleep()
示例9: make_command
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def make_command(command: Callable) -> Callable:
"""Create an command from a method signature."""
# docstyle
@wraps(command)
def actualcommand(self, *args, **kwds): # pylint: disable=missing-docstring
data = command(self, *args, **kwds)
name = command.__name__[3:]
signal = '{uuid}{sep}{event}'.format(
uuid=self._uuid, sep=SEPARATOR, event=name # pylint: disable=protected-access
)
if flask.has_request_context():
emit(signal, {'data': pack(data)})
else:
sio = flask.current_app.extensions['socketio']
sio.emit(signal, {'data': pack(data)})
eventlet.sleep()
return actualcommand
示例10: make_getter
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def make_getter(getter: Callable) -> Callable:
"""Create an command from a method signature."""
# docstyle
def get(self, timeout=10): # pylint: disable=missing-docstring
name = getter.__name__
signal = '{uuid}{sep}{event}'.format(
uuid=self._uuid, sep=SEPARATOR, event=name # pylint: disable=protected-access
)
event = LightQueue(1)
if flask.has_request_context():
emit(signal, callback=lambda x: event.put(unpack(x)))
else:
sio = flask.current_app.extensions['socketio']
sio.emit(signal, callback=lambda x: event.put(unpack(x)))
data = event.get(timeout=timeout)
return getter(self, data)
# don't want to copy the signature in this case
get.__doc__ = getter.__doc__
return get
示例11: __getitem__
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def __getitem__(self, key):
"""Load the value stored with the key.
Parameters
----------
key : str
The key to lookup the value stored.
Returns
-------
object
The value if the key exists in the cache, otherwise None.
"""
validate(key)
signal = 'cache_load'
event = LightQueue(1)
if flask.has_request_context():
emit(signal, {'data': pack(key)}, callback=event.put)
else:
sio = flask.current_app.extensions['socketio']
sio.emit(signal, {'data': pack(key)}, callback=event.put)
return msgpack.unpackb(bytes(event.get(timeout=10)), encoding='utf8')
示例12: guess_endpoint_uri
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def guess_endpoint_uri(rq, gh_repo):
"""
Guesses the endpoint URI from (in this order):
- An endpoint parameter in URL
- An #+endpoint decorator
- A endpoint.txt file in the repo
Otherwise assigns a default one
"""
auth = (static.DEFAULT_ENDPOINT_USER, static.DEFAULT_ENDPOINT_PASSWORD)
if auth == ('none', 'none'):
auth = None
if has_request_context() and "endpoint" in request.args:
endpoint = request.args['endpoint']
glogger.info("Endpoint provided in request: " + endpoint)
return endpoint, auth
# Decorator
try:
decorators = get_yaml_decorators(rq)
endpoint = decorators['endpoint']
auth = None
glogger.info("Decorator guessed endpoint: " + endpoint)
except (TypeError, KeyError):
# File
try:
endpoint_content = gh_repo.getTextFor({'download_url': 'endpoint.txt'})
endpoint = endpoint_content.strip().splitlines()[0]
auth = None
glogger.info("File guessed endpoint: " + endpoint)
# TODO: except all is really ugly
except:
# Default
endpoint = static.DEFAULT_ENDPOINT
auth = (static.DEFAULT_ENDPOINT_USER, static.DEFAULT_ENDPOINT_PASSWORD)
if auth == ('none', 'none'):
auth = None
glogger.warning("No endpoint specified, using default ({})".format(endpoint))
return endpoint, auth
示例13: db
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def db() -> Database:
if has_request_context(): # type: ignore
ctx = request
elif g:
ctx = g
else:
ctx = Container() # Fallback context for testing.
if not hasattr(ctx, 'database'):
ctx.database = get_database(configuration.get_str('decksite_database')) # type: ignore
return ctx.database # type: ignore
示例14: get_request_information
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def get_request_information():
"""
Return a dictionary of information about the user at the time of logging.
Returns:
The dictionary.
"""
information = {}
if has_request_context():
information["request"] = {
"api_endpoint_method": request.method,
"api_endpoint": request.path,
"ip": request.remote_addr,
"platform": request.user_agent.platform,
"browser": request.user_agent.browser,
"browser_version": request.user_agent.version,
"user_agent": request.user_agent.string,
}
if api.user.is_logged_in():
user = api.user.get_user()
team = api.user.get_team()
groups = api.team.get_groups(user["tid"])
information["user"] = {
"username": user["username"],
"email": user["email"],
"team_name": team["team_name"],
"groups": [group["name"] for group in groups],
}
return information
示例15: _filter_by_current_patron
# 需要导入模块: import flask [as 别名]
# 或者: from flask import has_request_context [as 别名]
def _filter_by_current_patron(search, query_string=None):
"""Filter search results by patron_pid."""
# if the logged in user is not librarian or admin, validate the query
if has_request_context() and not backoffice_permission().allows(
g.identity
):
return _filter_by_patron(g.identity.id, search, query_string)
return search, query_string