首页 > 解决方案 > 如何在 python 中模拟烧瓶请求来测试我的程序?

问题描述

我在 python 中编写了一个函数,它将接收一个 flask.request。我想知道如何通过向它发送虚假请求来测试此功能。有没有办法在本地做到这一点?

我的功能:

def main(request: flask.Request):
    if request.method == 'GET':
        try:
            request_json = request.get_json()
        except:
            return '', 400
        else:
            stuff = do_stuff(request_json)
            return stuff, 200

标签: pythonflask

解决方案


我用它在我的本地测试你的问题

import flask


app = flask.Flask(__name__)

@app.route("/<request>")
def main(request: flask.Request):
    if flask.request.method == 'GET':
        try:
            request_json = request.get_json()
        except:
            return '', 400
        else:
            stuff = do_stuff(request_json)
        return stuff, 200

if __name__ == "__main__":
    app.run(debug=True)

然后卷曲

curl -i http://localhost:5000/testing

并会给出类似的输出

HTTP/1.0 400 BAD REQUEST
Content-Type: text/html; charset=utf-8
Content-Length: 0
Server: Werkzeug/2.0.1 Python/3.9.6
Date: Tue, 26 Oct 2021 16:57:19 GMT

这是预期的输出吗?


推荐阅读