Flask搭建一個API服務器的步驟

一、API列表

 1. 獲取作品列表

① 獲取手工制作作品列表。

請求格式:

http://api.mculover666.cn:9999/twkk/list/hand_made

返回結果:

{
	goods_num: 3,
	goods_item: [
		{
			goods_id: 1,
			goods_name: "goods1",
			goods_img_url: "xxx"
		},
		{
			goods_id: 2,
			goods_name: "goods1",
			goods_img_url: "xxx"
		},
		{
			goods_id: 3,
			goods_name: "goods1",
			goods_img_url: "xxx"
		}
	]
}

② 獲取繪畫作品列表。
請求格式:

http://api.mculover666.cn:9999/twkk/list/drawing

返回結果:

{
	goods_num: 3,
	goods_item: [
		{
			goods_id: 4,
			goods_name: "goods1",
			goods_img_url: "xxx"
		},
		{
			goods_id: 5,
			goods_name: "goods1",
			goods_img_url: "xxx"
		},
		{
			goods_id: 6,
			goods_name: "goods1",
			goods_img_url: "xxx"
		}
	]
}

③ 獲取證書列表
請求格式:

http://api.mculover666.cn:9999/twkk/list/certificate

返回結果:

{
	goods_num: 3,
	goods_item: [
		{
			goods_id: 6,
			goods_name: "goods1",
			goods_img_url: "xxx"
		},
		{
			goods_id: 7,
			goods_name: "goods1",
			goods_img_url: "xxx"
		},
		{
			goods_id: 8,
			goods_name: "goods1",
			goods_img_url: "xxx"
		}
	]
}

二、安裝Flask

打開命令行,創建一份python虛擬環境:

python3 -m venv venv

在當前終端激活虛擬環境:

.\venv\Scripts\Activate.ps1

激活虛擬環境後,安裝Flask:

pip install Flask

查看安裝結果:

pip list

編寫一個HelloWorld測試一下:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Helloworld'

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

Flask參考教程:https://www.w3cschool.cn/flask/

三、代碼實現

# 導入Flask類
from flask import Flask, redirect, url_for, render_template
import json

# 使用當前模塊的名稱構建Flask app
app = Flask(__name__)

# 裝飾器,設置根目錄url調用函數
@app.route('/twkk')
def index():
    version = "v1.0.0"
    return render_template('index.html', app_version=version)

# 管理員url
@app.route('/twkk/admin')
def hello_admin():
    return 'Hello admin'

# 獲取分類列表
@app.route('/twkk/list/<category>', methods=["GET"])
def get_item_list(category):
    #讀取json文件內容
    try:
        if category == 'drawing':
            with open('drawing.json', 'r') as fp:
                json_data = json.load(fp)
                res_data = json.dumps(json_data)
                return res_data
        elif category == 'hand_made':
            with open('hand_made.json', 'r') as fp:
                json_data = json.load(fp)
                res_data = json.dumps(json_data)
                return res_data
        elif category == 'certificate':
            with open('certificate.json', 'r') as fp:
                json_data = json.load(fp)
                res_data = json.dumps(json_data)
                return res_data
    except:
        return ""

# 運行程序
if __name__ == '__main__':
    app.run()

四、API測試

1. 根目錄測試

/twkk

2. 列表拉取測試

curl localhost:5000/twkk/list/hand_made

在這裡插入圖片描述

curl localhost:5000/twkk/list/drawing

curl localhost:5000/twkk/list/certificate

到此這篇關於Flask搭建一個API服務器的步驟的文章就介紹到這瞭,更多相關Flask搭建API服務器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: