Flask一分鍾Mock一個API


如果安裝了Python,並且安裝了Flask:

pip install flask

那么就可以在短短一分鍾內Mock出來一個API,而且只需要用到一個文件

徹底告別在線Mock網站無法指定請求方法,Postman配置繁瑣的問題。

建一個文件

隨便在哪創建一個py文件,比如app.py。

寫一段代碼

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

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

跑一條命令

在cmd或shell執行python app.py,服務就起來了:

D:\>python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

測試一下:

D:\>curl http://127.0.0.1:5000/
Hello, World!

GET請求

不帶參數

代碼:

@app.route("/testGet")
def my_get():
    return "This is GET"

測試:

D:\>curl http://127.0.0.1:5000/testGet
This is GET

帶參數

代碼:

@app.route("/testGetParams")
def my_get_params():
    return request.args

測試:

D:\>curl "http://127.0.0.1:5000/testGetParams?a=1&b=2"
{"a":"1","b":"2"}

POST請求

不帶參數

代碼:

@app.route("/testPost", methods=["POST"])
def my_post():
    return "This is POST"

測試:

D:\>curl -X POST "http://127.0.0.1:5000/testPost"
This is POST

帶Json參數

代碼:

@app.route("/testPostJson", methods=["POST"])
def my_post_json():
    return request.json

test.json

{
	"name": "dongfanger",
	"alias": "redsun"
}

測試:

D:\>curl -H "Content-Type: application/json" -d "@test.json" "http://127.0.0.1:5000/testPostJson"
{'name': 'dongfanger', 'alias': 'redsun'}

同時GET和POST

代碼:

@app.route("/testGetPost", methods=["GET", "POST"])
def my_get_post():
    if request.method == "GET":
        return "This is GET"
    if request.method == "POST":
        return "This is POST"

測試:

D:\>curl http://127.0.0.1:5000/testGetPost
This is GET
D:\>curl http://127.0.0.1:5000/testGetPost -X POST
This is POST

請求頭

代碼:

@app.route("/testHeaders")
def my_headers():
    return str(request.headers)

測試:

D:\>curl http://127.0.0.1:5000/testHeaders
Host: 127.0.0.1:5000
User-Agent: curl/7.55.1
Accept: */*

完整代碼解析

from flask import Flask, request

# Flask實例
app = Flask(__name__)


# @app.route添加路由
@app.route("/testGet")
def my_get():
    return "This is GET"


@app.route("/testGetParams")
def my_get_params():
    # flask.request里面封裝了請求數據,可以看需要獲取
    return request.args

# methods指定請求方法
@app.route("/testPost", methods=["POST"])
def my_post():
    return "This is POST"


@app.route("/testPostJson", methods=["POST"])
def my_post_json():
    return request.json

# 可以同時指定GET和POST
@app.route("/testGetPost", methods=["GET", "POST"])
def my_get_post():
    # 判斷請求方法是GET或POST
    if request.method == "GET":
        return "This is GET"
    if request.method == "POST":
        return "This is POST"


@app.route("/testHeaders")
def my_headers():
    return str(request.headers)


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

小結

本文介紹了如何使用Flask在一分鍾內Mock一個API,只需要一個文件,一段代碼,一條命令,即可完成。然后分別介紹了常用的GET請求和POST請求,以及帶不帶參數,獲取請求頭的用法。在測試時用到了curl命令,它的名字是Client URL的意思,在Mac和Windows都可以安裝使用。

參考資料:

https://flask.palletsprojects.com/en/2.0.x/quickstart/

http://www.ruanyifeng.com/blog/2019/09/curl-reference.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM