flask 小入门知识点 2018.12.19

今天听得一脸懵逼,主要因为自己英文底子太差了

不耽误时间了,少总结下,开始复习。。。

代码:

# -*- encoding: utf-8 -*-
# 导入重定向模块 , url_for简易寻址跳转,jsonify强转为json格式的数据
from flask import Flask,redirect,url_for,jsonify

#建立一个配置类
class Config(object):
DEBUG = True
JSON_AS_ASCII = False

# 建立FLASK对象
app = Flask(__name__)
# # 解决中文乱码问题,将JSON数据内的中文正常显示
# app.config['JSON_AS_ASCII'] = False
# # 开启debug模式
# app.config['DEBUG'] = True

# #从配置文件中加载配置
# app.config.from_pyfile('config.ini')
#从环境变量中来加载配置
# app.config.from_envvar('app_config')
#从配置对象来加载
app.config.from_object(Config)

# 使用flask路由器,指定网址和控制器 # 给网址增加参数功能使用<变量名>,路由方法和路由器定义的参数同步
@app.route("/")
def index():
return "hello"

@app.route('/<id>/<name>')

def index1(id,name):
return "hello world,你的参数是%s,%s"%(id,name)

# 使用重定向模块来进行跳转
@app.route('/1')
def reurl():
return redirect("http://www.baidu.com")
# 使用url_for方法来实现简易的站内跳转,参数指定路由方法名称
@app.route('/hello/2')
def reurl_in():
return redirect(url_for('index'))

#使用jsonify让网页直接显示JSON数据
@app.route('/json',methods=['POST'])
def re_json():
json_dict = {'id':10,'title':'flask应用','content':'falsk的格式化'}
#使用JSONIFY来将定义的好的数据转换成json格式,并返回前段
return jsonify(json_dict)
#Flask统一对状态码捕获异常,用来进行友好提示
@app.errorhandler(405)
def internal_server_error(e):
return '这个接口不能被GET请求到,只能post'
# 在第一次请求之前调用
@app.before_first_request
def before_first_request():
print("这是第一次请求之前调用的方法")
#在每一次请求之前调用
@app.before_request
def before_request():
print('每一次请求之前,调用这个方法')
#在请求之后调用方法,必须传响应参数,然后将响应内容返回
@app.after_request
def after_request(response):
print('在请求之后调用这个方法')
return response
# 在请求之后,调用服务器出现的错误信息
@app.teardown_request
def teardown_request(e):
print('服务器出现的错误是%s'%str(e))
if __name__ == "__main__":
app.run()


原文地址:https://www.cnblogs.com/xcsg/p/10143982.html