一、安装flask框架
[root@node-2 ~]# pip3 install flask
二、hello world
1.编写代码
#!/usr/bin/python3
from flask import Flask
app = Flask(__name__)
@app.route('/') #定义client访问的url 相当于nginx中的location
def index(): #函数名是自定义函数名。不是固定的
return '<h1>hello</h1>'
@app.route('/test1') #这里又定义了一个路由
def test1():
return '<h1>test1</h1>'
app.run('0.0.0.0',debug=True)
2.启动flask
[root@node-2 pangbing]# ./main.py
* Serving Flask app 'main' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://10.87.10.38:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 729-968-464
3.访问测试
访问: 10.87.10.38:5000
访问 10.87.10.38:5000/test1
三、返回值
返回json字符串
在flask框架中 不能直接返回字典、元组的 所以需要将数据转换为json数据返回。这里使用了flask自带的jsonify方法
from flask import Flask,jsonify
app = Flask(__name__)
data = [
{'name': 'zhangsan','age': 20},
{'name': 'lisi','age': 22}
]
@app.route('/')
def index():
return jsonify(data)