Python flask._request_ctx_stack.top() Examples
The following are 30
code examples of flask._request_ctx_stack.top().
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._request_ctx_stack
, or try the search function
.
Example #1
Source File: tracing.py From python-flask with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _after_request_fn(self, response=None, error=None): request = stack.top.request # the pop call can fail if the request is interrupted by a # `before_request` method so we need a default scope = self._current_scopes.pop(request, None) if scope is None: return if response is not None: scope.span.set_tag(tags.HTTP_STATUS_CODE, response.status_code) if error is not None: scope.span.set_tag(tags.ERROR, True) scope.span.log_kv({ 'event': tags.ERROR, 'error.object': error, }) scope.close()
Example #2
Source File: __init__.py From Flask-Fixtures with MIT License | 6 votes |
def push_ctx(app=None): """Creates new test context(s) for the given app If the app is not None, it overrides any existing app and/or request context. In other words, we will use the app that was passed in to create a new test request context on the top of the stack. If, however, nothing was passed in, we will assume that another app and/or request context is already in place and use that to run the test suite. If no app or request context can be found, an AssertionError is emitted to let the user know that they must somehow specify an application for testing. """ if app is not None: ctx = app.test_request_context() ctx.fixtures_request_context = True ctx.push() if _app_ctx_stack is not None: _app_ctx_stack.top.fixtures_app_context = True # Make sure that we have an application in the current context if (_app_ctx_stack is None or _app_ctx_stack.top is None) and _request_ctx_stack.top is None: raise AssertionError('A Flask application must be specified for Fixtures to work.')
Example #3
Source File: flask_gopher.py From flask-gopher with GNU General Public License v3.0 | 6 votes |
def float_right(self, text_left, text_right, fillchar=' ', width=None): """ Left-justifies text, and then overlays right justified text on top of it. This gives the effect of having a floating div on both sides of the screen. """ width = width or self.default_width left_lines = text_left.splitlines() right_lines = text_right.splitlines() lines = [] for left, right in zip_longest(left_lines, right_lines, fillvalue=''): padding = width - len(right) line = (left.ljust(padding, fillchar) + right)[-width:] lines.append(line) return '\r\n'.join(lines)
Example #4
Source File: flask_gopher.py From flask-gopher with GNU General Public License v3.0 | 6 votes |
def banner(self, text, ch='=', side='-', width=None): """ Surrounds the text with an ascii banner: ======================================== - Hello World! - ======================================== """ width = width or self.default_width offset = len(side) lines = [] for line in text.splitlines(): if side: lines.append(side + line.center(width)[offset:-offset] + side) else: lines.append(line.center(width)) if ch: # Add the top & bottom top = bottom = (ch * width)[:width] lines = [top] + lines + [bottom] return '\r\n'.join(lines)
Example #5
Source File: flask_sapb1.py From Flask-SAPB1 with MIT License | 6 votes |
def getContacts(self, num=1, columns=[], cardCode=None, contact={}): """Retrieve contacts under a business partner by CardCode from SAP B1. """ cols = '*' if len(columns) > 0: cols = " ,".join(columns) sql = """SELECT top {0} {1} FROM dbo.OCPR""".format(num, cols) params = dict({(k, 'null' if v is None else v) for k, v in contact.items()}) params['cardcode'] = cardCode sql = sql + ' WHERE ' + " AND ".join(["{0} = %({1})s".format(k, k) for k in params.keys()]) self.cursorAdaptor.sqlSrvCursor.execute(sql, params) contacts = [] for row in self.cursorAdaptor.sqlSrvCursor: contact = {} for k, v in row.items(): value = '' if type(v) is datetime.datetime: value = v.strftime("%Y-%m-%d %H:%M:%S") elif v is not None: value = str(v) contact[k] = value contacts.append(contact) return contacts
Example #6
Source File: i18n.py From jbox with MIT License | 6 votes |
def _get_translations(): """Returns the correct gettext translations. Copy from flask-babel with some modifications. """ ctx = _request_ctx_stack.top if ctx is None: return None # babel should be in extensions for get_locale if 'babel' not in ctx.app.extensions: return None translations = getattr(ctx, 'wtforms_translations', None) if translations is None: dirname = messages_path() translations = support.Translations.load( dirname, [get_locale()], domain='wtforms' ) ctx.wtforms_translations = translations return translations
Example #7
Source File: i18n.py From RSSNewsGAE with Apache License 2.0 | 6 votes |
def _get_translations(): """Returns the correct gettext translations. Copy from flask-babel with some modifications. """ ctx = _request_ctx_stack.top if ctx is None: return None # babel should be in extensions for get_locale if 'babel' not in ctx.app.extensions: return None translations = getattr(ctx, 'wtforms_translations', None) if translations is None: dirname = messages_path() translations = support.Translations.load( dirname, [get_locale()], domain='wtforms' ) ctx.wtforms_translations = translations return translations
Example #8
Source File: __init__.py From flask-jwt with MIT License | 6 votes |
def _jwt_required(realm): """Does the actual work of verifying the JWT data in the current request. This is done automatically for you by `jwt_required()` but you could call it manually. Doing so would be useful in the context of optional JWT access in your APIs. :param realm: an optional realm """ token = _jwt.request_callback() if token is None: raise JWTError('Authorization Required', 'Request does not contain an access token', headers={'WWW-Authenticate': 'JWT realm="%s"' % realm}) try: payload = _jwt.jwt_decode_callback(token) except jwt.InvalidTokenError as e: raise JWTError('Invalid token', str(e)) _request_ctx_stack.top.current_identity = identity = _jwt.identity_callback(payload) if identity is None: raise JWTError('Invalid JWT', 'User does not exist')
Example #9
Source File: __init__.py From Flask-Fixtures with MIT License | 5 votes |
def pop_ctx(): """Removes the test context(s) from the current stack(s) """ if getattr(_request_ctx_stack.top, 'fixtures_request_context', False): _request_ctx_stack.pop() if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False): _app_ctx_stack.pop()
Example #10
Source File: flask_elasticsearch.py From Flask-Elasticsearch with MIT License | 5 votes |
def __getattr__(self, item): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'elasticsearch'): if isinstance(ctx.app.config.get('ELASTICSEARCH_HOST'), str): hosts = [ctx.app.config.get('ELASTICSEARCH_HOST')] elif isinstance(ctx.app.config.get('ELASTICSEARCH_HOST'), list): hosts = ctx.app.config.get('ELASTICSEARCH_HOST') ctx.elasticsearch = Elasticsearch(hosts=hosts, http_auth=ctx.app.config.get('ELASTICSEARCH_HTTP_AUTH'), **self.elasticsearch_options) return getattr(ctx.elasticsearch, item)
Example #11
Source File: auth_context.py From quay with Apache License 2.0 | 5 votes |
def set_authenticated_context(auth_context): """ Sets the auth context for the current request context to that given. """ ctx = _request_ctx_stack.top ctx.authenticated_context = auth_context return auth_context
Example #12
Source File: auth_context.py From quay with Apache License 2.0 | 5 votes |
def get_authenticated_context(): """ Returns the auth context for the current request context, if any. """ return getattr(_request_ctx_stack.top, "authenticated_context", None)
Example #13
Source File: testing.py From annotated-py-projects with MIT License | 5 votes |
def open(self, *args, **kwargs): if self.context_preserved: _request_ctx_stack.pop() self.context_preserved = False kwargs.setdefault('environ_overrides', {}) \ ['flask._preserve_context'] = self.preserve_context old = _request_ctx_stack.top try: return Client.open(self, *args, **kwargs) finally: self.context_preserved = _request_ctx_stack.top is not old
Example #14
Source File: testing.py From PhonePi_SampleServer with MIT License | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #15
Source File: testing.py From cloud-playground with Apache License 2.0 | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #16
Source File: testing.py From syntheticmass with Apache License 2.0 | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #17
Source File: testing.py From arithmancer with Apache License 2.0 | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #18
Source File: testing.py From appengine-try-python-flask with Apache License 2.0 | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #19
Source File: __init__.py From bearded-avenger with Mozilla Public License 2.0 | 5 votes |
def before_request(): """ Grab the API token from headers :return: 401 if no token is present """ method = request.form.get('_method', '').upper() if method: request.environ['REQUEST_METHOD'] = method ctx = _request_ctx_stack.top ctx.url_adapter.default_method = method assert request.method == method if request.path == '/u/logout': return if request.path == '/u/login': return if request.path == '/favicon.ico': return if '/u' in request.path: if request.remote_addr not in HTTPD_UI_HOSTS: return 'unauthorized, must connect from {}'.format(','.join(HTTPD_UI_HOSTS)), 401 # make sure SECRET_KEY is set properly if 'token' not in session: return render_template('login.html', code=401) else: return if request.endpoint not in ['/', 'help', 'confidence', 'health']: t = pull_token() if not t or t == 'None': return '', 401
Example #20
Source File: flask_cassandra.py From flask-cassandra with BSD 3-Clause "New" or "Revised" License | 5 votes |
def connection(self): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'cassandra_cluster'): ctx.cassandra_cluster = self.connect() return ctx.cassandra_cluster
Example #21
Source File: testing.py From scylla with Apache License 2.0 | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #22
Source File: flask_gopher.py From flask-gopher with GNU General Public License v3.0 | 5 votes |
def _parse_directory(self, folder, abs_folder): """ Construct a gopher menu that represents all of the files in a directory. """ folder = Path(folder) lines = [] # Add a link to the parent directory if we're not at the top level if folder.parent != folder: if folder.parent != folder.parent.parent: options = {self.url_token: folder.parent} else: options = {} lines.append(menu.dir('..', url_for(self.view_name, **options))) for file in sorted(Path(abs_folder).iterdir()): relative_file = folder / file.name menu_type = self._guess_menu_type(file) item_text = file.name if file.is_dir(): item_text += '/' if self.show_timestamp: last_modified = datetime.fromtimestamp(file.stat().st_mtime) timestamp = last_modified.strftime(self.timestamp_fmt) item_text = item_text.ljust(self.width - len(timestamp)) + timestamp options = {self.url_token: relative_file} lines.append(menu_type(item_text, url_for(self.view_name, **options))) return '\n'.join(lines)
Example #23
Source File: flask_gopher.py From flask-gopher with GNU General Public License v3.0 | 5 votes |
def menu(self): """ The current active instance of the GopherMenu class. This variable is instantiated on the request context so that it can be initialized with the same host/port that the request's url_adapter is using. """ ctx = request_ctx_stack.top if ctx is not None: if not hasattr(ctx, 'gopher_menu'): host = request.environ['SERVER_NAME'] port = request.environ['SERVER_PORT'] ctx.gopher_menu = self.menu_class(host, port) return ctx.gopher_menu
Example #24
Source File: testing.py From Building-Recommendation-Systems-with-Python with MIT License | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #25
Source File: testing.py From Flask-P2P with MIT License | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()
Example #26
Source File: flask_sapb1.py From Flask-SAPB1 with MIT License | 5 votes |
def getShipments(self, num=100, columns=[], params={}, itemColumns=[]): """Retrieve shipments(deliveries) from SAP B1. """ cols = '*' if 'DocEntry' not in columns: columns.append('DocEntry') if len(columns) > 0: cols = " ,".join(columns) ops = {key: '=' if 'op' not in params[key].keys() else params[key]['op'] for key in params.keys()} sql = """SELECT top {0} {1} FROM dbo.ODLN""".format(num, cols) if len(params) > 0: sql = sql + ' WHERE ' + " AND ".join(["{0} {1} %({2})s".format(k, ops[k], k) for k in params.keys()]) self.cursorAdaptor.sqlSrvCursor.execute(sql, {key: params[key]['value'] for key in params.keys()}) shipments = [] for row in self.cursorAdaptor.sqlSrvCursor: shipment = {} for k, v in row.items(): value = '' if type(v) is datetime.datetime: value = v.strftime("%Y-%m-%d %H:%M:%S") elif v is not None: value = str(v) shipment[k] = value shipments.append(shipment) for shipment in shipments: shipmentId = shipment['DocEntry'] shipment['items'] = self._getShipmentItems(shipmentId, itemColumns) return shipments
Example #27
Source File: flask_sapb1.py From Flask-SAPB1 with MIT License | 5 votes |
def cursorAdaptor(self): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'msSQLCursorAdaptor'): ctx.msSQLCursorAdaptor = self.connect(type="CURSOR") return ctx.msSQLCursorAdaptor
Example #28
Source File: flask_sapb1.py From Flask-SAPB1 with MIT License | 5 votes |
def comAdaptor(self): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'sapb1COMAdaptor'): ctx.sapb1COMAdaptor = self.connect(type="COM") return ctx.sapb1COMAdaptor
Example #29
Source File: flask_sapb1.py From Flask-SAPB1 with MIT License | 5 votes |
def teardown(self, exception): ctx = stack.top if hasattr(ctx, 'sapb1COMAdaptor'): ctx.sapb1COMAdaptor.disconnect() if hasattr(ctx, 'msSQLCursorAdaptor'): ctx.msSQLCursorAdaptor.disconnect()
Example #30
Source File: testing.py From Financial-Portfolio-Flask with MIT License | 5 votes |
def __exit__(self, exc_type, exc_value, tb): self.preserve_context = False # on exit we want to clean up earlier. Normally the request context # stays preserved until the next request in the same thread comes # in. See RequestGlobals.push() for the general behavior. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop()