Flask入门

发布时间 2023-11-11 20:28:36作者: PiggThird

总结

1 三板斧:
	-return 字符串								HttpResponse
	-return render_template('index.html')	  render
	-return redirect('/login')				  redirect
2 路由写法(路径,支持的请求方式,别名)
@app.route('/login',methods=['GET','POST'],endpoint='别名')
3 模板语言渲染
	-同dtl,但是比dtl强大,支持加括号执行,字典支持中括号取值和get取值
4 分组(django中的有名分组)
    @app.route('/detail/<int:nid>',methods=['GET'])
    def detail(nid):
5 反向解析
	-url_for('别名')
    
6 获取前端传递过来的数据
	# get 请求
		request.query_string
  	# post请求
      user = request.form.get('user')
      pwd = request.form.get('pwd')

配置文件

方式一

app.config['DEBUG'] = True
PS: 由于Config对象本质上是字典,所以还可以使用		app.config.update(...)

方式二

#通过py文件配置
app.config.from_pyfile("python文件名称")
如:
settings.py
DEBUG = True

方式三(最好用的)

app.config.from_object('settings.TestingConfig')  想要用哪个配置改名字即可
app.config.from_object('settings.DevelopmentConfig')

# 创建一个新的py文件在里边写
class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True

路由系统

1 基本使用			    转换器
@app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')
# 把nid要传进去 /detail/1
def detail(nid):
    user = session.get('user_info')
    if not user:
        return redirect('/login')

    info = USERS.get(nid)
    return render_template('detail.html',info=info)

转换器

DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

路由的本质

1 本质就是:app.add_url_rule()
2 endpoint(别名):如果不写默认是函数名,endpoint不能重名

app.add_url_rule参数

@app.route和app.add_url_rule参数:
rule, URL规则
view_func, 视图函数名称
defaults = None, 默认值, 当URL中无参数,函数需要参数时,使用defaults = {'k': 'v'}
为函数提供参数
endpoint = None, 名称,用于反向生成URL,即: url_for('名称')
methods = None, 允许的请求方式,如:["GET", "POST"]
#对URL最后的 / 符号是否严格要求,默认严格,False,就是不严格
strict_slashes = None
    '''
        @app.route('/index', strict_slashes=False)
        #访问http://www.xx.com/index/ 或http://www.xx.com/index均可
        @app.route('/index', strict_slashes=True)
        #仅访问http://www.xx.com/index
    '''
#重定向到指定地址
redirect_to = None, 
    '''
        @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
    '''

CBV(但是大部分flask还是用FBV)

from flask import Flask,request,render_template,redirect
from flask import views

app=Flask(__name__)


# class IndexView(views.View):
#     methods = ['GET']
#     # decorators = [auth, ]
#     def dispatch_request(self):
#         print('Index')
#         return 'Index!'

# 自定义装饰器
def auth(func):
    def inner(*args, **kwargs):
        print('before')
        result = func(*args, **kwargs)
        print('after')
        return result

    return inner


class IndexView(views.MethodView):
    methods = ['GET']  # 指定运行的请求方法
    # 登录认证装饰器加在哪?
    decorators = [auth, ]  #加多个就是从上往下的效果
    def get(self):
        print('xxxxx')
        return "我是get请求"
    def post(self):
       return '我是post请求'

# 路由如何注册?
# IndexView.as_view('index'),必须传name
app.add_url_rule('/index',view_func=IndexView.as_view('index'))

if __name__ == '__main__':
    app.run()
    
# 总结
    用的比较少
    继承views.MethodView,只需要写get,post,delete方法
    如果加装饰器decorators = [auth, ]
    允许的请求方法methods = ['GET']