flask 开发Restful API(post和get方式实例)
程序员文章站
2022-05-30 22:40:54
命令行安装flaskpip install flask新建脚本api.pyfrom flask import Flaskfrom flask import requestimport jsonapp = Flask(__name__) @app.route('/') #默认getdef index(): return 's' @app.route('/getData') # url=127.0.0.1:8999/getDatadef getData(): nam....
命令行安装flask
pip install flask
新建脚本api.py
from flask import Flask
from flask import request
import json
app = Flask(__name__)
@app.route('/') #默认get
def index():
return 's'
@app.route('/getData') # url=127.0.0.1:8999/getData
def getData():
name=request.values.get('name')
age=request.values.get('age')
print(name)
print(age)
if name=='test':
return 's'
else:
return 'again'
@app.route('/postData',methods=['get','post']) #可以写多个方法
def postData():
if request.method=='POST': #大写
name=request.form['name']
if name=='test':
return 's'
else:
return 'again'
else:
return 'gggg'
@app.route('/postJson',methods=['get','post'])
def postJson():
if request.method== 'POST': #大写
data=request.get_data()
json_data=json.loads(data.decode('utf-8'))
print(json_data)
name=json_data.get("name")
age=json_data.get("age")
print("name=%s,age=%s" %(name,age))
if name=='test':
return 's'
else:
return 'again'
else:
return 'gggg'
if __name__ == '__main__':
app.run(port=8999,debug=True) #host默认0.0.0.0 port默认5000
Postman调用测试
结果打印
本文地址:https://blog.csdn.net/yeluo_vinager/article/details/107160882