flask是Python编写的web微框架,我们可以通过flask快速实现web服务,下面来看看如何利用flask快速实现接口服务
安装
python环境必须有啊!这不是废话吗?!
通过pip来安装flask
pip install flask
show me the code
新建一个py文件
基本配置
# 创建一个flask对象,名字随意但一定要和下面的app对应
app = Flask(__name__)
# 访问根路径
@app.route('/')
def main():
return 'hello flask'
# 执行py文件时,运行flask对象
if __name__ == '__main__':
app.run()
执行py文件后,输出以下内容表示flask运行成功
* Serving Flask app "keepapp" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit
当我们通过浏览器访问http://127.0.0.1:5000/
GET、POST
# methods数组中只存在GET,所以此请求只允许GET方式,path参数和方法的参数也要一致
@app.route('/users/<page>/<count>', methods=['GET'])
def get_user_list(page, count):
return {'page':page,'count':count}
# 如果需要从参数中获取对应的值,需要引入request
from flask import request
@app.route('/users', methods=['GET'])
def get_user_list2(page, count):
page = request.args.get("page")
count = request.args.get("count")
return {'page':page,'count':count}
# 支持GET和POST请求方式
@app.route('/users', methods=['GET','POST'])
def get_user_list2(page, count):
#方式和get一样
page = request.args.get("page")
count = request.args.get("count")
return {'page':page,'count':count}
返回html
from flask import send_file
@app.route('/usermap')
def get_user_map():
#本地需要存在一个html文件
fileName = 'static/keepmap.html'
return send_file(fileName)
值得注意的是,请求结果的返回类型必须是string, tuple, Response instance, WSGI callable
否则会出现以下异常提醒
The view function did not return a valid response.
The return type must be a string, tuple, Response instance, or WSGI callable, but it was a list.