Flask不能捕获400 BadRequest

时间:2019-10-31 08:34:31

标签: python flask flask-restful

我无法在Flask应用中处理 400 BadRequest 。以下是 main.py

from dotenv import find_dotenv, load_dotenv
from werkzeug.exceptions import BadRequest

from app import create_app, db
from app.orm import init_db, drop_db
from app.rest.core import InternalServerError, reply, handle_bad_request_error, BadRequestError

load_dotenv(find_dotenv())

app = create_app()


@app.errorhandler(BadRequest)
def handle_bad_request(ex):
    print(ex)
    return handle_bad_request_error(BadRequestError(ex.description))


@app.errorhandler
def handle_all(ex: Exception):
    print(ex)
    err = InternalServerError(description='')
    return reply(err)


@app.cli.command('initdb')
def init_db_command():
    init_db(db)


@app.cli.command('dropdb')
def drop_db_command():
    drop_db(db)


if __name__ == "__main__":
    # Print API map
    with app.app_context():
        # site_map(app)
        # Initialize DB
        init_db(db)
    # Run
    app.run()

我还尝试编写400而不是BadRequest,并使用@bp.errorahandler@bp.app_errorhandler装饰器在Blueprint中对其进行处理。烧瓶只是我所有尝试的结果。我仍然收到标准错误消息:

{
    "message": {
        "Authorization": "Basic authorization required"
    }
}

这是我的Resource抛出此异常:

class AccessTokenResource(BaseResource):

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('Authorization', required=True, location='headers', help='Basic authorization required')
        basic = parser.parse_args()['Authorization']
        if not basic or not basic.lower().startswith('basic '):
            raise UnauthorizedError('Basic authorization required')
        try:
            credentials = base64.b64decode(basic.split()[1]).decode('utf-8')
            email, password = credentials.split(':')
        except Exception as error:
            print(error)
            raise UnauthorizedError('Basic authorization required')
        user = self.db.get_user_by_email(email)
        if user is None or not user.check_password(password):
            raise InvalidEmailOrPasswordError()
        json = AccessTokenSchema().dump(AccessToken(user, app.config['SECRET_KEY']))
        return json, 200, {
            'Cache-Control': 'no-store',
            'Pragma': 'no-cache'
        }

我注册资源如下:

bp = Blueprint('api', __name__)
api = Api(bp)

def init_app(app: Flask):
    schema.init_app(app)
    init_routes(api)
    app.register_blueprint(bp, url_prefix=app.config['API_ENDPOINT'])

Blueprint(bp)捕获了除400以外的所有异常,因此我将其移出以使用应用程序的装饰器,但仍然无法正常工作。官方文档中的示例也无济于事。

问题出在哪里?我在做什么错了?

0 个答案:

没有答案