當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。