本文整理匯總了Python中flask.current_app.debug方法的典型用法代碼示例。如果您正苦於以下問題:Python current_app.debug方法的具體用法?Python current_app.debug怎麽用?Python current_app.debug使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.current_app
的用法示例。
在下文中一共展示了current_app.debug方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: broad_exception_handler
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例2: routes
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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)
示例3: parse_plist_input_data
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例4: download_key
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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')
示例5: worker
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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())
示例6: redirect_to_ssl
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例7: worker
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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())
示例8: insecure_transport
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例9: output_json
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例10: delete_memoized_verhash
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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.")
示例11: handle_exception
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例12: _get_wrap
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例13: serve_swaggerui_assets
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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)
示例14: get_file_hash
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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
示例15: send_static_file
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import debug [as 別名]
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)