当前位置: 首页>>代码示例>>Python>>正文


Python current_app.debug方法代码示例

本文整理汇总了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 
开发者ID:JoMingyu,项目名称:Flask-Large-Application-Example,代码行数:23,代码来源:error.py

示例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) 
开发者ID:fastlane-queue,项目名称:fastlane,代码行数:23,代码来源:routes.py

示例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 
开发者ID:cmdmnt,项目名称:commandment,代码行数:23,代码来源:decorators.py

示例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') 
开发者ID:cmdmnt,项目名称:commandment,代码行数:20,代码来源:app_json.py

示例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()) 
开发者ID:getsentry,项目名称:zeus,代码行数:23,代码来源:server.py

示例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 
开发者ID:getsentry,项目名称:zeus,代码行数:25,代码来源:ssl.py

示例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()) 
开发者ID:getsentry,项目名称:zeus,代码行数:26,代码来源:server.py

示例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 
开发者ID:gita,项目名称:BhagavadGita,代码行数:24,代码来源:application.py

示例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 
开发者ID:briancappello,项目名称:flask-react-spa,代码行数:23,代码来源:extension.py

示例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.") 
开发者ID:synthetichealth,项目名称:syntheticmass,代码行数:24,代码来源:__init__.py

示例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 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:25,代码来源:api.py

示例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 
开发者ID:jpush,项目名称:jbox,代码行数:14,代码来源:forms.py

示例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) 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:13,代码来源:__init__.py

示例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 
开发者ID:paxswill,项目名称:evesrp,代码行数:17,代码来源:versioned_static.py

示例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) 
开发者ID:paxswill,项目名称:evesrp,代码行数:29,代码来源:versioned_static.py


注:本文中的flask.current_app.debug方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。