python3.7+flask+web学习笔记4

Flask视图技术

  • app.route和add_url_rule的简介

  • 标准视图使用

  • 基本方法的类视图基本使用

  • 装饰器的基本使用

1.app.route和add_url_rule的简介

1.1app.route的使用

例子里面就有  

@app.route('/') 

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

可以通过url_for('hello_world') 反转到给定的url命名

@app.route('/',endpoint='index')

def hello_world():

  return 'hello world'

扫描二维码关注公众号,回复: 8739819 查看本文章

1.2add_url_rule使用

通过add_url_rule来绑定视图函数和URL

例如:

app.add_url_rule('/test/',endpoint='my_test', view_func=my_test)  endpoint 不是必须填写

app.add_url_rule('/test/', view_func=my_test)  endpoint 不是必须填写

第三笔记稍微修改一下:增加

def my_test():
    return '这个是测试函数 my_test'

app.add_url_rule("/test/my_test/",endpoint='my_test',view_func=my_test)

说明:my_test被"/test/my_test/绑定

进行构建一个虚拟请求;

app.add_url_rule("/test/my_test/",endpoint='my_test',view_func=my_test)

with app.test_request_context():
    print(url_for('my_test'))

结果为:

/test/my_test/

2.标准视图使用

必须继承 flask.views.View
必须实现 dispatch_request
必须使用 app.add_url_rule来做url与视图映射

有点意思的代码:

#encoding:utf-8

from flask import Flask,render_template,views

app = Flask(__name__)

import datetime
import random
app = Flask(__name__)

def getTime():

    now = datetime.datetime.now()


    otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
    return otherStyleTime


class Vip(views.View):
    def __init__(self):
        super().__init__()
        self.context = {

            'vip':'这个是会员平台'
        }

class Index(Vip):
    def dispatch_request(self):
        title = "我的首页的例子"
        auther = "风清扬"
        myTime = getTime()
        randl = random.randint(0, 1)
        return render_template('index.html',**self.context,**locals())

class Login(Vip):
    def dispatch_request(self):
        return render_template('/login/login.html',**self.context)

class Reg(Vip):
    def dispatch_request(self):
        return render_template('/reg/reg.html',**self.context)


app.add_url_rule(rule="/",endpoint='index',view_func=Index.as_view('index'))
app.add_url_rule(rule="/login/",endpoint='login',view_func=Login.as_view('login'))
app.add_url_rule(rule="/reg/",endpoint='reg',view_func=Reg.as_view('reg'))



if __name__ == '__main__':

    app.run(debug=True)

显示如下:

3.基本方法的类使用视图

主要是继承flask.views.MethodView 里面有http的get和post方法,最最最常用的方法

4.装饰器的基本使用

装饰器本质是参数是函数,返回也是函数

带参数的可变参数

def func(*args,**kwargs):

发布了134 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/keny88888/article/details/103580254