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


Python exceptions.InternalServerError方法代码示例

本文整理汇总了Python中werkzeug.exceptions.InternalServerError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.InternalServerError方法的具体用法?Python exceptions.InternalServerError怎么用?Python exceptions.InternalServerError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug.exceptions的用法示例。


在下文中一共展示了exceptions.InternalServerError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_responds_with_validate

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def test_responds_with_validate(app, client):  # noqa
    import pytest
    from flask import jsonify
    from werkzeug.exceptions import InternalServerError

    class TestSchema(Schema):
        _id = fields.Integer(required=True)
        name = fields.String(required=True)

    @app.errorhandler(InternalServerError)
    def payload_validation_failure(err):
        return jsonify({"message": "Server attempted to return invalid data"}), 500

    @app.route("/test")
    @responds(schema=TestSchema, validate=True)
    def get():
        obj = {"wrong_field": 42, "name": "Jon Snow"}
        return obj

    with app.test_client() as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert resp.status_code == 500
        assert resp.json == {"message": "Server attempted to return invalid data"} 
开发者ID:apryor6,项目名称:flask_accepts,代码行数:26,代码来源:decorators_test.py

示例2: test_menu_logged_in_error_dont_show_no_user

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def test_menu_logged_in_error_dont_show_no_user(self, mock_user_get):
        """ If the user is logged in, if we show a 500 error, do not show the user menu
            Don't query the database to get a current_user for the template context"""
        @self.app.route('/page_that_returns_500')
        def view500():
            raise InternalServerError('error')

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        user = db_user.get_or_create(1, 'iliekcomputers')
        mock_user_get.return_value = user
        self.temporary_login(user['login_id'])
        resp = self.client.get('/page_that_returns_500')
        data = resp.data.decode('utf-8')
        # item not in user menu
        self.assertNotIn('My Listens', data)
        self.assertNotIn('Sign in', data)
        self.assertIn('Import', data) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:20,代码来源:test_index.py

示例3: submit_listens_to_listenbrainz

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def submit_listens_to_listenbrainz(listenbrainz_user, listens, listen_type=LISTEN_TYPE_IMPORT):
    """ Submit a batch of listens to ListenBrainz

    Args:
        listenbrainz_user (dict): the user whose listens are to be submitted
        listens (list): a list of listens to be submitted
        listen_type: the type of listen (single, import, playing_now)
    """
    username = listenbrainz_user['musicbrainz_id']
    retries = 10
    while retries >= 0:
        try:
            current_app.logger.debug('Submitting %d listens for user %s', len(listens), username)
            insert_payload(listens, listenbrainz_user, listen_type=listen_type)
            current_app.logger.debug('Submitted!')
            break
        except (InternalServerError, ServiceUnavailable) as e:
            retries -= 1
            current_app.logger.error('ISE while trying to import listens for %s: %s', username, str(e))
            if retries == 0:
                raise spotify.SpotifyListenBrainzError('ISE while trying to import listens: %s', str(e)) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:23,代码来源:spotify_read_listens.py

示例4: handle_exception

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def handle_exception(self, e):
        """Default exception handling that kicks in when an exception
        occours that is not catched.  In debug mode the exception will
        be re-raised immediately, otherwise it is logged and the handler
        for a 500 internal server error is used.  If no such handler
        exists, a default 500 internal server error message is displayed.

        .. versionadded: 0.3
        """
        handler = self.error_handlers.get(500)
        if self.debug:
            raise
        self.logger.exception('Exception on %s [%s]' % (
            request.path,
            request.method
        ))
        if handler is None:
            return InternalServerError()
        return handler(e) 
开发者ID:hhstore,项目名称:annotated-py-projects,代码行数:21,代码来源:flask.py

示例5: test_menu_logged_in_error_dont_show_no_user

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def test_menu_logged_in_error_dont_show_no_user(self, mock_user_get):
        """ If the user is logged in, if we show a 500 error, do not show the user menu
            Don't query the database to get a current_user for the template context"""
        @self.app.route('/page_that_returns_500')
        def view500():
            raise InternalServerError('error')

        user = db_user.get_or_create('little_rsh')
        mock_user_get.return_value = user
        self.temporary_login(user['id'])
        resp = self.client.get('/page_that_returns_500')
        data = resp.data.decode('utf-8')
        # item not in user menu
        self.assertNotIn('Your profile', data)
        self.assertIn('Sign in', data)
        mock_user_get.assert_not_called()
        self.assertIsInstance(self.get_context_variable('current_user'), AnonymousUserMixin) 
开发者ID:metabrainz,项目名称:acousticbrainz-server,代码行数:19,代码来源:test_index.py

示例6: __init__

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def __init__(self, import_name: str) -> None:
        shared_web_path = os.path.abspath(os.path.dirname(__file__))
        static_folder = os.path.join(shared_web_path, 'static')
        super().__init__(import_name, static_folder=static_folder)
        super().register_error_handler(DoesNotExistException, self.not_found)
        super().register_error_handler(exceptions.NotFound, self.not_found)
        super().register_error_handler(exceptions.InternalServerError, self.internal_server_error)
        super().route('/unauthorized/')(self.unauthorized)
        super().route('/logout/')(self.logout)
        super().route('/authenticate/')(self.authenticate)
        super().route('/authenticate/callback/')(self.authenticate_callback)
        super().route('/api/gitpull', methods=['POST'])(api.process_github_webhook)
        super().route('/api/commit')(api.commit_id)
        super().route('/robots.txt')(self.robots_txt)
        super().route('/favicon<rest>')(self.favicon)
        self.url_build_error_handlers.append(self.external_url_handler)
        if self.config.get('SERVER_NAME') is None:
            self.config['SERVER_NAME'] = configuration.get_optional_str('flask_server_name')
        self.config['menu'] = []
        self.config['js_url'] = ''
        self.config['css_url'] = ''
        self.config['commit-id'] = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
        self.config['branch'] = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode()
        self.config['SESSION_COOKIE_DOMAIN'] = configuration.get_optional_str('flask_cookie_domain')

        translations = os.path.abspath(os.path.join(shared_web_path, 'translations'))
        self.config['BABEL_TRANSLATION_DIRECTORIES'] = translations
        self.babel = Babel(self)
        localization.init(self.babel)
        self.api_root = Blueprint('api', import_name, url_prefix='/api/')
        self.api = Api(self.api_root, title=f'{import_name} API')
        self.register_blueprint(self.api_root) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:34,代码来源:flask_app.py

示例7: internal_server_error

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def internal_server_error(self, e: Exception) -> Union[Tuple[str, int], Response]:
        log_exception(request, e)
        path = request.path
        try:
            repo.create_issue('500 error at {path}\n {e}'.format(path=path, e=e), session.get('mtgo_username', session.get('id', 'logged_out')), self.name, 'PennyDreadfulMTG/perf-reports', exception=e)
        except GithubException:
            logger.error('Github error', e)
        if request.path.startswith('/api/'):
            return return_json(generate_error('INTERNALERROR', 'Internal Error.', exception=e), status=404)
        view = InternalServerError(e)
        return view.page(), 500 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:13,代码来源:flask_app.py

示例8: image

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def image(c: str = '') -> wrappers.Response:
    names = c.split('|')
    try:
        requested_cards = oracle.load_cards(names)
        path = image_fetcher.download_image(requested_cards)
        if path is None:
            raise InternalServerError(f'Failed to get image for {c}')
        return send_file(os.path.abspath(path)) # Send abspath to work around monolith root versus web root.
    except TooFewItemsException as e:
        logger.info(f'Did not find an image for {c}: {e}')
        if len(names) == 1:
            return redirect(f'https://api.scryfall.com/cards/named?exact={c}&format=image', code=303)
        return make_response('', 400) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:15,代码来源:main.py

示例9: handle_exception

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def handle_exception(e):
        log.debug('LDAP server not accessible while trying to login to opds feed')
        return error_http(FailedDependency())

# @app.errorhandler(InvalidRequestError)
#@app.errorhandler(OperationalError)
#def handle_db_exception(e):
#    db.session.rollback()
#    log.error('Database request error: %s',e)
#    return internal_error(InternalServerError(e)) 
开发者ID:janeczku,项目名称:calibre-web,代码行数:12,代码来源:web.py

示例10: test_error_handler_on_unhandled_error

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def test_error_handler_on_unhandled_error(self, app):

        client = app.test_client()

        @app.route('/uncaught')
        def test_uncaught():
            raise Exception('Oops, something really bad happened.')

        Api(app)

        response = client.get('/uncaught')
        assert response.status_code == 500
        assert response.json['code'] == 500
        assert response.json['status'] == InternalServerError().name 
开发者ID:marshmallow-code,项目名称:flask-smorest,代码行数:16,代码来源:test_error_handler.py

示例11: view

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def view(self, endpoint, values, args):
        """
        Werkzeug views mapping method.
        """

        params = dict(values)
        if endpoint in self._args:
            params.update({key: args[key] for key in self._args[endpoint] if key in args})

        try:
            return self._views[endpoint](**params)
        except Exception as error:  # pylint: disable=broad-except
            self._log.exception("Exception thrown while rendering view")
            self._errors.labels(args.get('module', 'default')).inc()
            raise InternalServerError(error) 
开发者ID:prometheus-pve,项目名称:prometheus-pve-exporter,代码行数:17,代码来源:http.py

示例12: proxylogin

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def proxylogin(request):
    if request.remote_user is None:
        raise InternalServerError(
            '/proxylogin is supposed to have "CosignAllowPublicAccess Off"')

    return finish_login(request, request.args['destination'],
        dict(type='cosignproxy', server=request.args['server'])) 
开发者ID:fmfi-svt,项目名称:votr,代码行数:9,代码来源:login.py

示例13: http_errorhandler

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def http_errorhandler(fn):
    def iter_derived_classes(base_class):
        for class_ in base_class.__subclasses__():
            yield class_
            for derived_class in iter_derived_classes(class_):
                yield derived_class

    for http_error in iter_derived_classes(HTTPException):
        if http_error is InternalServerError:
            continue
        bp.app_errorhandler(http_error)(fn)
    return fn 
开发者ID:huskar-org,项目名称:huskar,代码行数:14,代码来源:error.py

示例14: handle_unknown_error

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def handle_unknown_error(error):
    return handle_http_error(InternalServerError()) 
开发者ID:huskar-org,项目名称:huskar,代码行数:4,代码来源:error.py

示例15: test_current_status_ise

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import InternalServerError [as 别名]
def test_current_status_ise(self, mock_rabbitmq_connection_module):
        mock_rabbitmq_connection_module._rabbitmq.get.side_effect = InternalServerError
        r = self.client.get(url_for('index.current_status'))
        self.assert500(r)

        mock_rabbitmq_connection_module._rabbitmq.get.side_effect = ConnectionClosed
        r = self.client.get(url_for('index.current_status'))
        self.assert200(r)

        mock_rabbitmq_connection_module._rabbitmq.get.side_effect = ConnectionClosed
        r = self.client.get(url_for('index.current_status'))
        self.assert200(r) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:14,代码来源:test_index.py


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