Flask框架

 1、导入Flask类
from flask import Flask, abort, redirect, url_for
# 导入路由模块
from werkzeug.routing import BaseConverter




# 2、创建程序实例
# __name__参数的作用是为了确定程序所在的位置
# flask会默认创建静态路由
# 可以传入任意字符串,但是,如果传入python标准模块名,会解释器会从指定模块名的位置找static所在文件,
# 如果传入python标准模块名,可以访问视图函数。
app = Flask(__name__)


# 装饰器路由
# URL允许重复,url存储在列表中,依次往下查找
# 视图函数不允许重复,视图函数重名需要使用functools,可以让被装饰的函数名称不会被改变,实现路由映射绑定视图函数
@app.route('/index',methods=['GET','POST'])
def index():
    return 'hello world2017'




@app.route('/index2',methods=['GET','POST'])
def index2():
    return 'hello world2018'




# 给视图传参:get请求在url中,post请求一般放在请求体,url中也可以传参
# 以<>形式传参,url中的参数
# <>默认的数据类型是str,兼容数值,可以指定数据类型
# 数值类型互不兼容
@app.route('/index3/<int:args>',methods=['GET','POST'])
def index3(args):
    return 'hello world2018%s' % args


# 返回状态码
# return可以返回自定义的不符合http协议的状态码
# 一般用来实现前后端的数据交互:
# return (errno='666',errmsg='用户名或密码错误')
# $.ajax({
#     url:'/',
#     type:'post',
#     data:params,
#     success:function(resp){
#         if (resp.errno=='666'){
#             alert(resp.errmsg)
#     }
# }
# })


# 返回真实的状态码,类似于python中的raise语句
# abort函数,用来实现符合http协议的真实状态码
# @app.route('/')
# def resp_status():
#     abort(404)
#     return 'response status:',666
#
# # errorhandler装饰器用来接收接收符合http协议的状态码,
# # 用来实现自定义的错误页面。
# @app.errorhandler(404)
# def error_handers(e):
#     return '服务器搬家了,您可以访问http://www.baidu.cn %s' %e




# 重定向
# 当网站项目目录或文件发生改变的情况下,需要使用重定向
# 定义活动页面,如果活动页面发生改变,需要多次重写,扩展性不强
@app.route('/redirect')
def redir_handler():
    a = 'http://www.baidu.com'
    return redirect(a)


# 重定向建议使用url_for接收的参数为视图函数名,反向解析!
# 浏览器访问视图,是通过url地址找到视图函数
# url_for从视图函数,找到具体的url
@app.route('/url')
def url_redir():
    return redirect(url_for('redir_handler'))




if __name__ == '__main__':
    # 查看路由映射,
    print(app.url_map)
    # 开启调试模式,当代码发生改变,自动更新,会提示错误信息
    # run方法,可以指定host、port、debug
    app.run(debug=True)

猜你喜欢

转载自blog.csdn.net/qq_41868948/article/details/80355478