Python flask.has_request_context() Examples
The following are 30
code examples of flask.has_request_context().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask
, or try the search function
.
Example #1
Source File: search_permissions.py From invenio-app-ils with MIT License | 7 votes |
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])
Example #2
Source File: util.py From FlowKit with Mozilla Public License 2.0 | 6 votes |
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
Example #3
Source File: storage_manager.py From cloudify-manager with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: _cache.py From bowtie with MIT License | 6 votes |
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')
Example #5
Source File: changed_by.py From invenio-app-ils with MIT License | 6 votes |
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
Example #6
Source File: message.py From bowtie with MIT License | 6 votes |
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()
Example #7
Source File: base.py From safrs with GNU General Public License v3.0 | 6 votes |
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
Example #8
Source File: _component.py From bowtie with MIT License | 6 votes |
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
Example #9
Source File: mail.py From osm-wikidata with GNU General Public License v3.0 | 6 votes |
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)
Example #10
Source File: _component.py From bowtie with MIT License | 6 votes |
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
Example #11
Source File: __init__.py From Ocean-Data-Map-Project with GNU General Public License v3.0 | 5 votes |
def init_db(uri, echo=False): if flask.has_request_context(): raise RuntimeError("Do not call this from inside the Flask application") app = flask.Flask("CMDLINE") app.config["SQLALCHEMY_DATABASE_URI"] = uri app.config["SQLALCHEMY_ECHO"] = echo app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.app_context().push() db.init_app(app)
Example #12
Source File: reqctx.py From data with GNU General Public License v3.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #13
Source File: reqctx.py From data with GNU General Public License v3.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #14
Source File: __init__.py From notifications-admin with MIT License | 5 votes |
def _add_request_id_header(headers): if not has_request_context(): return headers headers['X-B3-TraceId'] = request.request_id headers['X-B3-SpanId'] = request.span_id return headers
Example #15
Source File: reqctx.py From syntheticmass with Apache License 2.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #16
Source File: flask_raml.py From flask-raml with MIT License | 5 votes |
def get_response_mimetype(self, response, accept=None, request=request): if accept is None: if request and has_request_context(): accept = map(itemgetter(0), request.accept_mimetypes) return super(API, self).get_response_mimetype(response, accept)
Example #17
Source File: __init__.py From Mastering-Flask-Web-Development-Second-Edition with MIT License | 5 votes |
def get_locale(): if has_request_context(): locale = session.get('locale') if locale: return locale session['locale'] = 'en' return session['locale']
Example #18
Source File: reqctx.py From data with GNU General Public License v3.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #19
Source File: reqctx.py From data with GNU General Public License v3.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #20
Source File: reqctx.py From data with GNU General Public License v3.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #21
Source File: pager.py From bowtie with MIT License | 5 votes |
def notify(self): """Notify the client. The function passed to ``App.respond`` will get called. """ if flask.has_request_context(): emit(_NAME + str(self._uuid)) else: sio = flask.current_app.extensions['socketio'] sio.emit(_NAME + str(self._uuid)) eventlet.sleep()
Example #22
Source File: reqctx.py From Flask with Apache License 2.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #23
Source File: reqctx.py From Flask with Apache License 2.0 | 5 votes |
def test_context_test(self): app = flask.Flask(__name__) self.assert_false(flask.request) self.assert_false(flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assert_true(flask.request) self.assert_true(flask.has_request_context()) finally: ctx.pop()
Example #24
Source File: app.py From Hands-On-Docker-for-Microservices-with-Python with MIT License | 5 votes |
def format(self, record): record.request_id = 'NA' if has_request_context(): record.request_id = request.environ.get("HTTP_X_REQUEST_ID") return super().format(record)
Example #25
Source File: app.py From Hands-On-Docker-for-Microservices-with-Python with MIT License | 5 votes |
def format(self, record): record.request_id = 'NA' if has_request_context(): record.request_id = request.environ.get("HTTP_X_REQUEST_ID") return super().format(record)
Example #26
Source File: test_flask.py From python-dockerflow with Mozilla Public License 2.0 | 5 votes |
def test_request_summary_exception(caplog, app): Dockerflow(app) with app.test_request_context("/", headers=headers): assert has_request_context() app.preprocess_request() app.handle_exception(ValueError("exception message")) response = Response("") response = app.process_response(response) for record in caplog.records: if record != "request.summary": continue assert_log_record(request, record, level=logging.ERROR, errno=500) assert record.getMessage() == "exception message"
Example #27
Source File: database.py From Penny-Dreadful-Tools with GNU General Public License v3.0 | 5 votes |
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
Example #28
Source File: logger.py From picoCTF with MIT License | 5 votes |
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
Example #29
Source File: search_permissions.py From invenio-app-ils with MIT License | 5 votes |
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
Example #30
Source File: borrowing_request.py From invenio-app-ils with MIT License | 5 votes |
def preserve_patron_loan(data, prev_record=None): """Preserve `patron_loan` system field.""" if not has_request_context(): return data if prev_record and "patron_loan" in prev_record: data["patron_loan"] = deepcopy(prev_record["patron_loan"]) return data