运行环境:python3
post参数:user,pwd
接口功能:将参数转换成字符串相加并返回json
# -*- coding:utf-8 -*-
from flask import Flask, g
from flask_restful import reqparse, Api, Resource
from flask_httpauth import HTTPTokenAuth #pip install Flask-HTTPAuth
# Flask相关变量声明
app = Flask(__name__)
api = Api(app)
# RESTfulAPI的参数解析 -- put / post参数解析
parser_put = reqparse.RequestParser()
parser_put.add_argument("user", type=str, required=True, help="need user data")
parser_put.add_argument("pwd", 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()
# 构建新参数
user = args['user']
pwd = args['pwd']
# 调用方法to_do
info = {"info": to_do(user, pwd)}
# 资源添加成功,返回201
return info, 201
if __name__ == "__main__":
# 设置路由,即路由地址为http://127.0.0.1:8800/users
api.add_resource(TodoList, "/users")
app.run(host='127.0.0.1',port=8800,debug=True)#port 默认5000端口
运行该py文件,将服务启动
* Restarting with stat
* Debugger is active!
* Debugger PIN: 131-285-031
* Running on http://127.0.0.1:8800/ (Press CTRL+C to quit)
为了测试接口是否可以正常调用,我们新建一个py文件,模拟发送参数到这个地址,看是否有返回结果。
# -*- coding:utf-8 -*-
import requests,json
# api路径
url = "http://127.0.0.1:8800/users"
parms = {
'user': 'abc', # 发送给服务器的内容
'pwd': '456'
}
headers = {
'User-agent': 'none/ofyourbusiness',
'Spam': 'Eggs'
}
res = requests.post(url, data=parms, headers=headers) # 发送请求
text = res.text
print(json.loads(text))
运行测试文件,可以看到返回结果:
{'info': 'abc456'}
服务端打印信息
127.0.0.1 - - [01/Sep/2019 17:21:51] "POST /users HTTP/1.1" 201 -
表示接口可以正常调用了!
auth认证
# -*- coding:utf-8 -*-
from flask import Flask
#https://github.com/miguelgrinberg/flask-httpauth
from flask_httpauth import HTTPBasicAuth#pip install Flask-HTTPAuth
app = Flask(__name__)
auth = HTTPBasicAuth()
users = {
"kingly":"hello",
"susan":"bye"
}
@auth.get_password
def get_pwd(username):
if username in users:
return users.get(username)
return None
@app.route('/')
@auth.login_required
def index():
return 'Hello %s!!' % auth.username()
if __name__ == '__main__':
app.run(host='127.0.0.1',port=8800,debug=True)
参考:https://blog.csdn.net/t8116189520/article/details/81874309
https://www.jianshu.com/p/d9fc7c4d4e81