How to intentionally cause a 400 Bad Request in Python/Flask?

后端 未结 4 2327
广开言路
广开言路 2021-02-19 00:18

A consumer of my REST API says that on occasion I am returning a 400 Bad Request - The request sent by the client was syntactically incorrect. error.

相关标签:
4条回答
  • 2021-02-19 00:54

    You can use abort to raise an HTTP error by status code.

    from flask import abort
    @app.route('/badrequest400')
    def bad_request():
        abort(400)
    
    0 讨论(0)
  • 2021-02-19 01:10

    Also, You can use jsonify

    from flask import jsonify
    
    class SomeView(MethodView):
        def post(self, *args, **kwargs):
            if "csv_file" not in request.files:
                return jsonify({'errors': 'No csv_file key in request.files.'}), 400
    
    0 讨论(0)
  • 2021-02-19 01:11

    You can also use abort with custom message error:

    from flask import abort
    abort(400, 'My custom message')
    

    See https://flask-restplus.readthedocs.io/en/stable/errors.html

    0 讨论(0)
  • 2021-02-19 01:20

    you can return the status code as a second parameter of the return, see example below

    @app.route('/my400')
    def my400():
        code = 400
        msg = 'my message'
        return msg, code
    
    0 讨论(0)
提交回复
热议问题