29

abort()次のようなメソッドを使用して、flask-restful のエラー メッセージをクライアントに簡単に伝達できます。

abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")

これにより、次のjson出力が生成されます

{
  "message": "Fatal error: Pizza the Hutt was found dead earlier today
       in the back seat of his stretched limo. Evidently, the notorious gangster
       became locked in his car and ate himself to death.", 
  "status": 500
}

追加のメンバーを使用して json 出力をカスタマイズする方法はありますか? 例えば:

{
  "sub_code": 42,
  "action": "redirect:#/Outer/Space"
  "message": "You idiots! These are not them! You've captured their stunt doubles!", 
  "status": 500
}
4

7 に答える 7

43

人々は を使いすぎる傾向がありますがabort()、実際には独自のエラーを生成するのは非常に簡単です。カスタム エラーを簡単に生成する関数を作成できます。JSON に一致するものを次に示します。

def make_error(status_code, sub_code, message, action):
    response = jsonify({
        'status': status_code,
        'sub_code': sub_code,
        'message': message,
        'action': action
    })
    response.status_code = status_code
    return response

次に、呼び出す代わりにこれをabort()行います:

@route('/')
def my_view_function():
    # ...
    if need_to_return_error:
        return make_error(500, 42, 'You idiots!...', 'redirect...')
    # ...
于 2014-02-07T23:19:17.097 に答える
26

私は@dappiuにコメントする50の評判を持っていないので、新しい回答を書く必要がありますが、実際には「Flask-RESTfulはエラーを処理するためのよりクリーンな方法を提供することができました」に関連しています

使用方法を理解するのにしばらく時間がかかったのは、非常に悪いドキュメントです。重要なのは、カスタム例外がflask_restful import HTTPExceptionから継承する必要があることです。Python Exception は使用できないことに注意してください。

from flask_restful import HTTPException

class UserAlreadyExistsError(HTTPException):
    pass

custom_errors = {
    'UserAlreadyExistsError': {
        'message': "A user with that username already exists.",
        'status': 409,
    }
}

api = Api(app, errors=custom_errors)

Flask-RESTful チームは、カスタム例外処理を簡単にするために良い仕事をしましたが、ドキュメントがその努力を台無しにしました。

于 2015-09-08T03:59:38.860 に答える
9

@Miguel が示すように、通常は例外を使用しないでください。エラー応答を返すだけです。ただし、例外を発生させる中止メカニズムが本当に必要な場合があります。これは、たとえばフィルター メソッドで役立つ場合があります。Flask.abortはResponseオブジェクトを受け入れることに注意してください(この要点を確認してください):

from flask import abort, make_response, jsonify

response = make_response(jsonify(message="Message goes here"), 400)
abort(response)
于 2017-07-07T10:25:48.103 に答える
5

の妥当性について@Miguelに同意しませんabort()。Flask を使用して HTTP アプリ以外のもの (要求/応答パラダイムを使用) を構築している場合を除き、できるだけ多くのを使用する必要があると思いますHTTPExceptions(werkzeug.exceptionsモジュール)。また、中止メカニズムを使用することも意味します (これは、これらの例外へのショートカットにすぎません)。代わりに、ビューで独自のエラーを明示的に構築して返すことを選択すると、一連の if/else/return で値をチェックする必要があるパターンにつながりますが、これは多くの場合不要です。関数は、リクエスト/レスポンス パイプラインのコンテキストで動作する可能性が高いことに注意してください。決定を下す前にビューに戻る必要はなく、失敗した時点でリクエストを中止して処理を完了します。フレームワークはこのパターンを完全に理解しており、偶発性があります。また、必要に応じて例外をキャッチすることもできます (おそらく、追加のメッセージで補足するか、リクエストを回収する必要があります)。

したがって、@Miguel に似ていますが、意図した中止メカニズムを維持します。

 def json_abort(status_code, data=None):
    response = jsonify(data or {'error': 'There was an error'})
    response.status_code = status_code
    abort(response)

# then in app during a request

def check_unique_username(username):
    if UserModel.by__username(username):
        json_abort(409, {'error': 'The username is taken'})

def fetch_user(user_id): 
    try:
        return UserModel.get(user_id)
    except UserModel.NotFound:
        json_abort(404, {'error': 'User not found'})
于 2018-07-02T23:35:00.953 に答える
4

このカスタム エラー処理を正しく機能さcodeせるには、サブクラスに属性を定義する必要がありました。HttpException

from werkzeug.exceptions import HTTPException
from flask_restful import Api
from flask import Blueprint

api_bp = Blueprint('api',__name__)

class ResourceAlreadyExists(HTTPException):
    code = 400

errors = {
    'ResourceAlreadyExists': {
        'message': "This resource already exists.",
        'status': 409,
    },
}

api = Api(api_bp, errors=errors)

その後、例外を発生させます

raise ResourceAlreadyExists
于 2016-07-12T02:06:41.293 に答える