Python flask.current_app.debug() Examples
The following are 30
code examples of flask.current_app.debug().
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.current_app
, or try the search function
.
Example #1
Source File: error.py From Flask-Large-Application-Example with MIT License | 7 votes |
def broad_exception_handler(e: Exception): # TODO 에러를 세분화해서 잡는 것을 추천합니다. if isinstance(e, HTTPException): message = e.description code = e.code elif isinstance(e, ValidationError): message = json.loads(e.json()) code = HTTPStatus.BAD_REQUEST else: message = "" code = HTTPStatus.INTERNAL_SERVER_ERROR if current_app.debug: import traceback traceback.print_exc() return jsonify({"error": message}), code
Example #2
Source File: extension.py From flask-react-spa with MIT License | 6 votes |
def output_json(data, code, headers=None): """Replaces Flask-RESTful's default output_json function, using Flask.json's dumps method instead of the stock Python json.dumps. Mainly this means we end up using the current app's configured json_encoder class. """ settings = current_app.config.get('RESTFUL_JSON', {}) # If we're in debug mode, and the indent is not set, we set it to a # reasonable value here. if current_app.debug: settings.setdefault('indent', 4) # always end the json dumps with a new line # see https://github.com/mitsuhiko/flask/pull/1262 dumped = dumps(data, **settings) + '\n' response = make_response(dumped, code) response.headers.extend(headers or {}) return response
Example #3
Source File: routes.py From fastlane with MIT License | 6 votes |
def routes(): # pragma: no cover """Print available functions.""" if not current_app.debug: abort(404) func_list = [] for rule in current_app.url_map.iter_rules(): endpoint = rule.rule methods = ", ".join(list(rule.methods)) doc = current_app.view_functions[rule.endpoint].__doc__ route = { "endpoint": endpoint, "methods": methods } if doc: route["doc"] = doc func_list.append(route) func_list = sorted(func_list, key=lambda k: k['endpoint']) return jsonify(func_list)
Example #4
Source File: __init__.py From syntheticmass with Apache License 2.0 | 6 votes |
def delete_memoized_verhash(self, f, *args): """ Delete the version hash associated with the function. ..warning:: Performing this operation could leave keys behind that have been created with this version hash. It is up to the application to make sure that all keys that may have been created with this version hash at least have timeouts so they will not sit orphaned in the cache backend. """ if not callable(f): raise DeprecationWarning("Deleting messages by relative name is no longer" " reliable, please use a function reference") try: self._memoize_version(f, delete=True) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.")
Example #5
Source File: api.py From build-relengapi with Mozilla Public License 2.0 | 6 votes |
def handle_exception(self, exc_type, exc_value, exc_tb): if isinstance(exc_value, HTTPException): resp = jsonify(error={ 'code': exc_value.code, 'name': exc_value.name, 'description': exc_value.description, }, request_id=g.request_id) resp.status_code = exc_value.code else: current_app.log_exception((exc_type, exc_value, exc_tb)) error = { 'code': 500, 'name': 'Internal Server Error', 'description': 'Enable debug mode for more information', } if current_app.debug: error['traceback'] = traceback.format_exc().split('\n') error['name'] = exc_type.__name__ error['description'] = str(exc_value) resp = jsonify(error=error, request_id=g.request_id) resp.status_code = 500 return resp
Example #6
Source File: decorators.py From commandment with MIT License | 6 votes |
def parse_plist_input_data(f): """Parses plist data as HTTP input from request. The unserialized data is attached to the global **g** object as **g.plist_data**. :status 400: If invalid plist data was supplied in the request. """ @wraps(f) def decorator(*args, **kwargs): try: if current_app.debug: current_app.logger.debug(request.data) g.plist_data = plistlib.loads(request.data) except: current_app.logger.info('could not parse property list input data') abort(400, 'invalid input data') return f(*args, **kwargs) return decorator
Example #7
Source File: app_json.py From commandment with MIT License | 6 votes |
def download_key(rsa_private_key_id: int): """Download an RSA private key in PEM or DER format :reqheader Accept: application/x-pem-file :reqheader Accept: application/pkcs8 :resheader Content-Type: application/x-pem-file :resheader Content-Type: application/pkcs8 :statuscode 200: OK :statuscode 404: Not found :statuscode 400: Can't produce requested encoding """ if not current_app.debug: abort(500, 'Not supported in this mode') c = db.session.query(RSAPrivateKey).filter(RSAPrivateKey.id == rsa_private_key_id).one() bio = io.BytesIO(c.pem_data) return send_file(bio, 'application/x-pem-file', True, 'rsa_private_key.pem')
Example #8
Source File: server.py From zeus with Apache License 2.0 | 6 votes |
def worker(channel, queue, tenant, repo_ids=None, build_ids=None): allowed_repo_ids = frozenset(tenant.access.keys()) while await channel.wait_message(): msg = await channel.get_json() data = msg.get("data") if data["repository"]["id"] not in allowed_repo_ids: continue if build_ids and data["id"] not in build_ids: continue if repo_ids and data["repository"]["id"] not in repo_ids: continue evt = Event(msg.get("id"), msg.get("event"), data) with sentry_sdk.Hub.current.start_span( op="pubsub.receive", description=msg.get("id") ): await queue.put(evt) current_app.logger.debug("pubsub.event.received qsize=%s", queue.qsize())
Example #9
Source File: application.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def insecure_transport(self): """Creates a context to enable the oauthlib environment variable in order to debug with insecure transport. """ origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT') if current_app.debug or current_app.testing: try: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' yield finally: if origin: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin else: os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None) else: if origin: warnings.warn( 'OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ ' 'but the app is not running in debug mode or testing mode.' ' It may put you in danger of the Man-in-the-middle attack' ' while using OAuth 2.', RuntimeWarning) yield
Example #10
Source File: ssl.py From zeus with Apache License 2.0 | 6 votes |
def redirect_to_ssl(self): """ Redirect incoming requests to HTTPS. """ criteria = [ request.is_secure, current_app.debug, current_app.testing, request.headers.get("X-Forwarded-Proto", "http") == "https", ] if ( request.headers.get("User-Agent", "") .lower() .startswith(self.exclude_user_agents) ): return if not any(criteria): if request.url.startswith("http://"): url = request.url.replace("http://", "https://", 1) r = redirect(url, code=301) return r
Example #11
Source File: server.py From zeus with Apache License 2.0 | 6 votes |
def worker(db_pool, queue: asyncio.Queue): """ Async worker to perform tasks like persisting revisions to the database. """ while True: event, payload = await queue.get() try: if event == "revision": key = (payload["repo_id"], payload["revision"].sha) if key in _revision_cache: continue async with db_pool.acquire() as conn: await save_revision(conn, payload["repo_id"], payload["revision"]) _revision_cache[key] = 1 if event == "cleanup": repo_id = payload["repo_id"] async with db_pool.acquire() as conn: await cleanup(conn, repo_id) except Exception: current_app.logger.error( "worker.event-error event=%s", event, exc_info=True ) current_app.logger.debug("worker.event event=%s qsize=%s", event, queue.qsize())
Example #12
Source File: core.py From flask-ask with Apache License 2.0 | 5 votes |
def _alexa_request(self, verify=True): raw_body = flask_request.data alexa_request_payload = json.loads(raw_body) if verify: cert_url = flask_request.headers['Signaturecertchainurl'] signature = flask_request.headers['Signature'] # load certificate - this verifies a the certificate url and format under the hood cert = verifier.load_certificate(cert_url) # verify signature verifier.verify_signature(cert, signature, raw_body) # verify timestamp raw_timestamp = alexa_request_payload.get('request', {}).get('timestamp') timestamp = self._parse_timestamp(raw_timestamp) if not current_app.debug or self.ask_verify_timestamp_debug: verifier.verify_timestamp(timestamp) # verify application id try: application_id = alexa_request_payload['session']['application']['applicationId'] except KeyError: application_id = alexa_request_payload['context'][ 'System']['application']['applicationId'] if self.ask_application_id is not None: verifier.verify_application_id(application_id, self.ask_application_id) return alexa_request_payload
Example #13
Source File: flask_api.py From terracotta with MIT License | 5 votes |
def convert_exceptions(fun: Callable) -> Callable: """Converts internal exceptions to appropriate HTTP responses""" @functools.wraps(fun) def inner(*args: Any, **kwargs: Any) -> Any: try: return fun(*args, **kwargs) except exceptions.TileOutOfBoundsError: # send empty image from terracotta import get_settings, image settings = get_settings() return send_file(image.empty_image(settings.DEFAULT_TILE_SIZE), mimetype='image/png') except exceptions.DatasetNotFoundError as exc: # wrong path -> 404 if current_app.debug: raise return abort(404, str(exc)) except (exceptions.InvalidArgumentsError, exceptions.InvalidKeyError, marshmallow.ValidationError) as exc: # wrong query arguments -> 400 if current_app.debug: raise return abort(400, str(exc)) return inner
Example #14
Source File: core.py From flask-ask with Apache License 2.0 | 5 votes |
def dbgdump(obj, default=None, cls=None): if current_app.config.get('ASK_PRETTY_DEBUG_LOGS', False): indent = 2 else: indent = None msg = json.dumps(obj, indent=indent, default=default, cls=cls) logger.debug(msg)
Example #15
Source File: userauth.py From confidant with Apache License 2.0 | 5 votes |
def log_out_callback(self, clear_session_on_errors=True): """ Callback for SAML logout requests. Request must have a SAMLResponse GET parameter. On failure, renders error JSON. On success, redirects to /goodbye. """ logger.debug('Processing SAML logout response') auth = self._saml_auth() errors = [] auth.process_slo() errors = auth.get_errors() if errors: if clear_session_on_errors: self.clear_session() return self._render_saml_errors_json(auth) logger.info('SAML SLO request was successful') self.clear_session() return self.redirect_to_goodbye()
Example #16
Source File: auth.py From flask-restaction with MIT License | 5 votes |
def decode_token(self, token): """Decode Authorization token, return None if token invalid""" key = current_app.secret_key if key is None: if current_app.debug: current_app.logger.debug("app.secret_key not set") return None try: return jwt.decode( token, key, algorithms=[self.config["algorithm"]], options={'require_exp': True} ) except jwt.InvalidTokenError: return None
Example #17
Source File: forms.py From nrelabs-curriculum with Apache License 2.0 | 5 votes |
def _get_wrap(self, node, classes='form-group'): # add required class, which strictly speaking isn't bootstrap, but # a common enough customization if node.flags.required: classes += ' required' div = tags.div(_class=classes) if current_app.debug: div.add(tags.comment(' Field: {} ({}) '.format( node.name, node.__class__.__name__))) return div
Example #18
Source File: renderers.py From flask-nav with MIT License | 5 votes |
def visit_object(self, node): """Fallback rendering for objects. If the current application is in debug-mode (``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment -->`` will be rendered, indicating which class is missing a visitation function. Outside of debug-mode, returns an empty string. """ if current_app.debug: return tags.comment('no implementation in {} to render {}'.format( self.__class__.__name__, node.__class__.__name__, )) return ''
Example #19
Source File: api.py From doorman with MIT License | 5 votes |
def logger(node=None): ''' ''' data = request.get_json() log_type = data['log_type'] log_level = current_app.config['DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL'] if current_app.debug: current_app.logger.debug(json.dumps(data, indent=2)) if log_type == 'status': log_tee.handle_status(data, host_identifier=node.host_identifier) status_logs = [] for item in data.get('data', []): if int(item['severity']) < log_level: continue status_logs.append(StatusLog(node_id=node.id, **item)) else: db.session.add(node) db.session.bulk_save_objects(status_logs) db.session.commit() elif log_type == 'result': db.session.add(node) db.session.bulk_save_objects(process_result(data, node)) db.session.commit() log_tee.handle_result(data, host_identifier=node.host_identifier) analyze_result.delay(data, node.to_dict()) else: current_app.logger.error("%s - Unknown log_type %r", request.remote_addr, log_type ) current_app.logger.info(json.dumps(data)) # still need to write last_checkin, last_ip db.session.add(node) db.session.commit() return jsonify(node_invalid=False)
Example #20
Source File: userauth.py From confidant with Apache License 2.0 | 5 votes |
def _saml_req_dict_from_request(self, flask_request=None): """ Given a Flask Request object, return a dict of request information in the format that python-saml expects it for Auth objects. :param flask_request: A request object to pull data from. :type flask_request: flask.Request :returns: python-saml settings data :rtype: dict """ if flask_request is None: flask_request = flask.request url_data = urlparse(flask_request.url) if flask_request.scheme == 'https': https = 'on' elif current_app.debug and settings.SAML_FAKE_HTTPS: https = 'on' else: https = 'off' return { 'https': https, 'http_host': flask_request.host, 'server_port': url_data.port, 'script_name': flask_request.path, 'get_data': flask_request.args.copy(), 'post_data': flask_request.form.copy(), }
Example #21
Source File: server.py From zeus with Apache License 2.0 | 5 votes |
def build_server(loop, host, port): app = Application(loop=loop, logger=current_app.logger, debug=current_app.debug) app.router.add_route("GET", "/", stream) app.router.add_route("GET", "/healthz", health_check) return await loop.create_server(app.make_handler(), host, port)
Example #22
Source File: server.py From zeus with Apache License 2.0 | 5 votes |
def ping(loop, resp, client_guid): # periodically send ping to the browser. Any message that # starts with ":" colon ignored by a browser and could be used # as ping message. while True: await asyncio.sleep(15, loop=loop) current_app.logger.debug("pubsub.ping guid=%s", client_guid) with sentry_sdk.Hub.current.start_span(op="pubsub.ping"): resp.write(b": ping\r\n\r\n")
Example #23
Source File: versioned_static.py From evesrp with BSD 2-Clause "Simplified" License | 5 votes |
def send_static_file(self, filename): # Short-circuit if not adding file hashes if not self.config['SRP_STATIC_FILE_HASH']: return super(VersionedStaticFlask, self).send_static_file(filename) try: return super(VersionedStaticFlask, self).send_static_file(filename) except NotFound as e: current_app.logger.debug(u"Checking for version-hashed file: {}". format(filename)) # Map file names are derived from the source file's name, so ignore # the '.map' at the end. if filename.endswith('.map'): hashed_filename = filename[:-4] else: hashed_filename = filename # Extract the file hash from the name filename_match = re.match(r'(.+)\.([0-9a-fA-F]{8})(\.\w+)$', hashed_filename) if filename_match is None: current_app.logger.warning(u"Hash was unable to be found.") raise e requested_hash = filename_match.group(2) real_filename = filename_match.group(1) + filename_match.group(3) if filename != hashed_filename: real_filename += '.map' return super(VersionedStaticFlask, self).send_static_file( real_filename)
Example #24
Source File: versioned_static.py From evesrp with BSD 2-Clause "Simplified" License | 5 votes |
def get_file_hash(filename): if not hasattr(g, 'static_hashes'): g.static_hashes = {} # Check the cache if not in debug mode if not current_app.debug: try: return g.static_hashes[filename] except KeyError: pass hasher = hashlib.md5() with open(safe_join(current_app.static_folder, filename), 'rb') as f: hasher.update(f.read()) filehash = hasher.hexdigest()[:8] g.static_hashes[filename] = filehash return filehash
Example #25
Source File: __init__.py From flask-restplus-server-example with MIT License | 5 votes |
def serve_swaggerui_assets(path): """ Swagger-UI assets serving route. """ if not current_app.debug: import warnings warnings.warn( "/swaggerui/ is recommended to be served by public-facing server (e.g. NGINX)" ) from flask import send_from_directory return send_from_directory('../static/', path)
Example #26
Source File: forms.py From jbox with MIT License | 5 votes |
def _get_wrap(self, node, classes='form-group'): # add required class, which strictly speaking isn't bootstrap, but # a common enough customization if node.flags.required: classes += ' required' div = tags.div(_class=classes) if current_app.debug: div.add(tags.comment(' Field: {} ({}) '.format( node.name, node.__class__.__name__))) return div
Example #27
Source File: api.py From doorman with MIT License | 4 votes |
def distributed_write(node=None): ''' ''' data = request.get_json() if current_app.debug: current_app.logger.debug(json.dumps(data, indent=2)) queries = data.get('queries', {}) statuses = data.get('statuses', {}) for guid, results in queries.items(): task = DistributedQueryTask.query.filter( DistributedQueryTask.guid == guid, DistributedQueryTask.status == DistributedQueryTask.PENDING, DistributedQueryTask.node == node, ).first() if not task: current_app.logger.error( "%s - Got result for distributed query not in PENDING " "state: %s: %s", request.remote_addr, guid, json.dumps(data) ) continue # non-zero status indicates sqlite errors if not statuses.get(guid, 0): status = DistributedQueryTask.COMPLETE else: current_app.logger.error( "%s - Got non-zero status code (%d) on distributed query %s", request.remote_addr, statuses.get(guid), guid ) status = DistributedQueryTask.FAILED for columns in results: result = DistributedQueryResult( columns, distributed_query=task.distributed_query, distributed_query_task=task ) db.session.add(result) else: task.status = status db.session.add(task) else: # need to write last_checkin, last_ip on node db.session.add(node) db.session.commit() return jsonify(node_invalid=False)
Example #28
Source File: rebar.py From flask-rebar with MIT License | 4 votes |
def _init_error_handling(self, app): @app.errorhandler(errors.HttpJsonError) def handle_http_error(error): return self._create_json_error_response( message=error.error_message, http_status_code=error.http_status_code, additional_data=error.additional_data, ) @app.errorhandler(400) @app.errorhandler(404) @app.errorhandler(405) def handle_werkzeug_http_error(error): return self._create_json_error_response( message=error.description, http_status_code=error.code ) @app.errorhandler(MOVED_PERMANENTLY_ERROR) @app.errorhandler(PERMANENT_REDIRECT_ERROR) def handle_request_redirect_error(error): return self._create_json_error_response( message=error.name, http_status_code=error.code, additional_data={"new_url": error.new_url}, headers={"Location": error.new_url}, ) def run_unhandled_exception_handlers(exception): exc_info = sys.exc_info() current_app.log_exception(exc_info=exc_info) for func in self.uncaught_exception_handlers: func(exception) @app.errorhandler(Exception) def handle_generic_error(error): run_unhandled_exception_handlers(error) if current_app.debug: raise error else: return self._create_json_error_response( message=messages.internal_server_error, http_status_code=500 ) @app.teardown_request def teardown(exception): if isinstance(exception, SystemExit): try: run_unhandled_exception_handlers(exception) except Exception: # make sure the exception handlers dont prevent teardown pass
Example #29
Source File: flask_api.py From terracotta with MIT License | 4 votes |
def create_app(debug: bool = False, profile: bool = False) -> Flask: """Returns a Flask app""" from terracotta import get_settings import terracotta.server.datasets import terracotta.server.keys import terracotta.server.colormap import terracotta.server.metadata import terracotta.server.rgb import terracotta.server.singleband import terracotta.server.compute new_app = Flask('terracotta.server') new_app.debug = debug # extensions might modify the global blueprints, so copy before use new_tile_api = copy.deepcopy(TILE_API) new_metadata_api = copy.deepcopy(METADATA_API) # suppress implicit sort of JSON responses new_app.config['JSON_SORT_KEYS'] = False # CORS settings = get_settings() CORS(new_tile_api, origins=settings.ALLOWED_ORIGINS_TILES) CORS(new_metadata_api, origins=settings.ALLOWED_ORIGINS_METADATA) new_app.register_blueprint(new_tile_api, url_prefix='') new_app.register_blueprint(new_metadata_api, url_prefix='') # register routes on API spec with new_app.test_request_context(): SPEC.path(view=terracotta.server.datasets.get_datasets) SPEC.path(view=terracotta.server.keys.get_keys) SPEC.path(view=terracotta.server.colormap.get_colormap) SPEC.path(view=terracotta.server.metadata.get_metadata) SPEC.path(view=terracotta.server.rgb.get_rgb) SPEC.path(view=terracotta.server.rgb.get_rgb_preview) SPEC.path(view=terracotta.server.singleband.get_singleband) SPEC.path(view=terracotta.server.singleband.get_singleband_preview) SPEC.path(view=terracotta.server.compute.get_compute) SPEC.path(view=terracotta.server.compute.get_compute_preview) import terracotta.server.spec new_app.register_blueprint(SPEC_API, url_prefix='') if profile: from werkzeug.contrib.profiler import ProfilerMiddleware # use setattr to work around mypy false-positive (python/mypy#2427) setattr( new_app, 'wsgi_app', ProfilerMiddleware(new_app.wsgi_app, restrictions=[30]) ) return new_app
Example #30
Source File: core.py From flask-ask with Apache License 2.0 | 4 votes |
def init_app(self, app, path='templates.yaml'): """Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: Turn on application ID verification by setting this variable to an application ID or a list of allowed application IDs. By default, application ID verification is disabled and a warning is logged. This variable should be set in production to ensure requests are being sent by the applications you specify. Default: None `ASK_VERIFY_REQUESTS`: Enables or disables Alexa request verification, which ensures requests sent to your skill are from Amazon's Alexa service. This setting should not be disabled in production. It is useful for mocking JSON requests in automated tests. Default: True `ASK_VERIFY_TIMESTAMP_DEBUG`: Turn on request timestamp verification while debugging by setting this to True. Timestamp verification helps mitigate against replay attacks. It relies on the system clock being synchronized with an NTP server. This setting should not be enabled in production. Default: False `ASK_PRETTY_DEBUG_LOGS`: Add tabs and linebreaks to the Alexa request and response printed to the debug log. This improves readability when printing to the console, but breaks formatting when logging to CloudWatch. Default: False """ if self._route is None: raise TypeError("route is a required argument when app is not None") self.app = app app.ask = self app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST']) app.jinja_loader = ChoiceLoader([app.jinja_loader, YamlLoader(app, path)])