通过使用Python中Flask框架实现一个简单的API接口程序,用户可发送JSON格式的请求,服务器响应请求,并以JSON格式将数据返回给用户,此处代码是一个模板可以测试接口时使用。
Flask代码如下所示:
from flask import Flask, render_template, request, redirect
import json
app = Flask(__name__, template_folder="templates")
@app.route('/login', methods=['GET', 'POST'])
def login():
return_dict = {'status': '0', 'key': 'none'}
if request.method == 'GET':
# 判断参数不为0
if len(request.args) != 0:
get_data = request.args.to_dict()
username = get_data.get("username")
password = get_data.get("password")
print("GET => username = {} password = {}".format(username,password))
return json.dumps(return_dict, ensure_ascii=False)
if request.method == "POST":
if len(request.get_data()) != 0:
username = request.values.get("username")
password = request.values.get("password")
print("username = {} => password = {}".format(username,password))
if(username=="lyshark" and password == "123456"):
return_dict["status"] = "1"
return_dict["key"] = "1f3dsgf9834r98ugdf98gjd"
return json.dumps(return_dict, ensure_ascii=False)
return json.dumps(return_dict, ensure_ascii=False)
@app.route('/lat',methods=['GET', 'POST'])
def lat():
return_dict = {'status': '0','x': 'none', 'y':'none'}
if request.method == 'GET':
return json.dumps(return_dict, ensure_ascii=False)
if request.method == "POST":
if len(request.get_data()) != 0:
key = request.values.get("key")
tel = request.values.get("tel")
print("key = {} => tel = {}".format(key,tel))
if(key=="1f3dsgf9834r98ugdf98gjd"):
return_dict["status"] = "1"
return_dict['x'] = '12.5'
return_dict['y'] = '22.4'
return json.dumps(return_dict, ensure_ascii=False)
return json.dumps(return_dict, ensure_ascii=False)
@app.errorhandler(404)
def not_found(error):
return_dict = {'status': '404', 'message': '页面没有找到'}
return json.dumps(return_dict, ensure_ascii=False)
@app.errorhandler(405)
def not_found(error):
return_dict = {'status': '405', 'message': '服务器不提供请求类型'}
return json.dumps(return_dict, ensure_ascii=False)
@app.errorhandler(500)
def not_found(error):
return_dict = {'status': '500', 'message': '传入参数有误,或存在不规范输入'}
return json.dumps(return_dict, ensure_ascii=False)
@app.errorhandler(400)
def not_found(error):
return_dict = {'status': '400', 'message': 'Bad Request'}
return json.dumps(return_dict, ensure_ascii=False)
@app.errorhandler(409)
def not_found(error):
return_dict = {'status': '409', 'message': 'Conflict'}
return json.dumps(return_dict, ensure_ascii=False)
if __name__ == '__main__':
app.run(port=5000,debug=False)
客户测试代码:
import requests
# 模拟登录
def login():
data = {"username": "lyshark", "password": "123456"}
req = requests.post(url="http://127.0.0.1:5000/login", data=data)
print(req.text)
# 模拟取参数
def get_lat():
data = {"key": "1f3dsgf9834r98ugdf98gjd", "tel": "15644587845"}
req = requests.post(url="http://127.0.0.1:5000/lat", data=data)
print(req.text)
if __name__ == '__main__':
login()
get_lat()