flask视图及路由

from flask import Flask,redirect,url_for,request
from werkzeug.routing import BaseConverter


#创建一个Flask对象
app = Flask(__name__)


#把url '/index'绑定到视图函数index1
@app.route('/index')
def index1():
    return "this is index1"


@app.route('/index2')
def index2():
    #重定向到/index
    return redirect("/index")


@app.route('/index3')
def index3():
    #url_for:根据函数名反解析url,可跟参数
    return redirect(url_for("index4",id=121))


@app.route('/index4')
def index4():
    #使用request.args可以得到url的参数
    print(request.args.get('id'))
    return "this is index4"


#使用转换器过滤参数 内置的转换器有:int float path string等
@app.route('/index/<int:num>')
def index5(num):
    return "this num is %s" %num


#自定义转换器
class MyConverter(BaseConverter):
    def __init__(self,map,regex):
        super(MyCoverter,self).__init__(map)
        self.regex = regex
    
    #可以用来过滤数据以及转换数据类型等操作
    def to_python(self,value):
        print(value)
        return value


#将自定义的转换器添加到转换器列表中
app.url_map.converters['mc'] = MyConverter


@app.route('/index5/<mc('\d{3}'):num>')
def index5(num):
    return "this num is %s" %num



class Config:
    DEBUG = True

#通过类设置启动参数
app.config.from_object(Config)
#通过文件设置启动参数
app.config.from_pyfile('config.ini')
#通过环境变量设置启动参数
app.config.from_envvar('config')



if __name__ == "__main__":
    app.run()



    
from flask import Flask
#导入flask_script扩展包
from flask_script import Manager


app = Flask(__name__)


class Config:
    DEBUG = True

app.config.from_object(Config)


#使用manager和应用关联起来
manager = Manager(app)


@app.route('/')
def index():
    return "this is index"


@app.route('/index')
def index():
    #抛出404异常
    abrot(404)
    return "this is index"


#使用装饰器 捕获处理异常
@app.errorhanlder(404)
def error_view(e):
    return "服务器开小差了", 404





if __name__ == "__main__":
    #启动时需要加参数 runserver
    manager.run()

猜你喜欢

转载自blog.csdn.net/sdzhr/article/details/81569181
今日推荐