flask 是基于python2.7运行的
安装就不提了
1.导入flask扩展
from flask import Flask
2.创建flask应用程序的实例对象
app = Flask(__name__)
3.定义路由及视图函数
#127.0.0.1:5000 ---> hello flask
@app.route('/')
def index():
视图函数需要紧跟着路由,这样就可以绑定
return 'hello falsk'
4.运行
if __name__ =='__main__'
#类似与runserver
app.run()
-------------------------------------------------
调试模式下 离开页面端口自动刷新重启
app.run(debug=True)
'''
app设置参数:
参数都会添加到app.config的一个字典中
'''
# 方式一: 直接像操作字典一样赋值. , 所有的参数名, 底层都是大写的
app.config['DEBUG'] = True
# 方式二: 加载文件
# app.config.from_pyfile('config.py')
# 方式三: 加载对象
# app.config.from_object(Config)
# 方式四: app的属性
# app.debug = True
获取值
# 跟字典一样取值即可获取参数
print app.config.get('ITHEIMA')
# 如果在其他的模块中要向获取, 可以使用current_app来获取
# print current_app.config.get('ITHEIMA')
配置路由请求方式:
@app.route('/', methods=['GET', 'POST'])
def hello_world():
return 'Hello World!'
查看当前请求方式
print app.url_map
同名路由获取
代码从上至下获取,且只获取一个,不存在覆盖问题
路由有参数的话必须传参,否则报错
@app.route('/orders/<int:order_id>') # 路由转换器(指定参数类型)
def get_order_id(order_id):
return 'order_id: %s'% order_id
路由的重定向
from flask import redirect
@app.route('/redirect')
def redirect_demo():
return redirect('http//www.baidu.com')
@app.route('/redirect')
def redirect_demo():
# return redirect('/')
# url_for: 需要传入视图函数名, 会返回改函数对应的路由地址
# print url_for('hello_world')
# return redirect(url_for('hello_world'))
#以上为不传参的方式
#以下为传参的方式 get_ordes_id 为函数名
return redirect(url_for('get_ordes_id', order_id=666))
# 返回JSON-->前后端分离, 就是通过传递JSON数据进行沟通
@app.route('/json')
def do_json():
hello = {"name":"stranger", "say":"hello"}
# json.dumps, 只是返回json样式的字符串
# return json.dumps(hello)
以上只会返回一个json样式的字符串
# jsonify, 处了返回json字符串之外, 同时修改了Content-Type 为application/json
return jsonify(hello)
# 如果要实现和方式二一样的效果, 可以使用如下方式
# return 第一个参数: 返回的数据, 第二个参数: 状态码, 第三个参数: 设置响应头信息
# return json.dumps(hello), 200, {'Content-Type': 'application/json'}