from flask import Flask, g from flask_restful import reqparse, Api, Resource from flask_httpauth import HTTPTokenAuth # Flask相關變量聲明 app = Flask(__name__) api = Api(app) # RESTfulAPI的參數解析 -- put / post參數解析 parser_put = reqparse.RequestParser() parser_put.add_argument("keyword", type=str, required=True, help="need user data") parser_put.add_argument("lv", type=str, required=True, help="need pwd data") # 功能方法部分案例 def to_do(arg1, args2): return str(arg1) + str(args2) # 操做(post / get)資源列表 class TodoList(Resource): def post(self): args = parser_put.parse_args() # 構建新參數 keyword = args['keyword'] lv = args['lv'] # 調用方法to_do info = {"info": to_do(keyword, lv)} # 資源添加成功,返回201 return info, 201 # 設置路由,即路由地址爲http://127.0.0.1:5000/users api.add_resource(TodoList, "/users") if __name__ == "__main__": app.run(debug=True)
運行如圖
json
import requests import json # api路徑 url = "http://127.0.0.1:5000/users" # url = "http://134.175.183.70:5000/users" parms = { 'keyword': 'KFC', # 發送給服務器的內容 'lv': 'high' } headers = { 'User-agent': 'none/ofyourbusiness', 'Spam': 'Eggs' } res = requests.post(url, data=parms, headers=headers) # 發送請求 text = res.text # print(text) print(json.loads(text))
運行結果如圖flask