乐趣区

python-restful实例

test.py

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)

运行如图

test2.py

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))

运行结果如图

退出移动版