因为刚刚学完Django基础,看了几页Flask的官方文档,感觉比Django简单,所以flask的学习笔记可能不会很详细,只会记录一些与Django不一样的东西或者我自己觉得值得记录的东西。

路由

  • 与django不一样的是,flask的路由直接用一个装饰器就解决了,比django更直观也更方便去查找每个路由对应的方法。
  • 构建动态构建URL的方法也和django,使用尖括号<>作为关键字参数传递,然后在下面的方法中接收传过来的参数
  • url尾端是否使用斜杠
    Flask的URL规则基于Werkzeug的路由模块
    如果尾端有斜杠时,如果访问没有斜杠的url时会自动重定向到有斜杠的url上(这种是一个规范的url)
    如果尾端没有斜杠,这样可以保持url的唯一,避免搜索引擎重复索引
  • url_for(),感觉有点和Django中的反向解析的类似,用来动态构建url,第一个参数是方法名后面可以跟若干个参数表示url中传的参数 例如:
@app.route('/')
def hello_world():
    print(url_for('hello_world', par='123', par1='456'))
    return 'Hello World!'

输出结果为:/?par=123&par1=456

HTTP 方法

  • 最常见的包括POST,GET等,可在装饰器中methods参数来处理不同的 HTTP 方法:例如@app.route('/', methods=['GET', 'POST'])

重定向

  • 使用 redirect() 函数可以重定向,例如:
@app.route('/')
def index():
    return redirect(url_for('login'))

错误页面

  • 使用 errorhandler() 装饰器可以定制出错页面:
@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

然后新建一个page_not_found.html编写你的404错误页面

  • Flask类具有带有错误代码的abort()函数。
    例如Flask.abort(401)表示 用于未身份验证的

模板

  • 渲染模板使用 render_template() 方法可以渲染模板,与Django不同的是,这个只有两个参数,第一个是要渲染的html模板,第二个参数是要传递到html中的参数
  • Jinja2 模板引擎,和django模板引擎的语法差不多,但Jinja2号称比django快很多。
  • Markup 类。自动转义默认开启,使用Markup()或者在模板中使用 |safe 过滤器将其标记为安全的
  • 静态文件,存放在应用的 /static 中。在html中使用url_for()引入静态文件:
<script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>

cookie和session

app.secret_key = os.urandom(16)   # 加密session的秘钥


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/login', methods=['POST', 'GET'])  # 登录界面
def login():
    if request.method == 'POST':
        user = request.form.get('user')
        resp = make_response(redirect(url_for('mine')))
        # resp.set_cookie('user',user)   # 设置cookie
        session['user'] = user   # 设置session
        return resp
    else:
        return render_template('login.html')


@app.route('/mine')
def mine():
    # user = request.cookies.get('user')   # 获取cookie
    user = session.get('user')  # 获取session
    return render_template('mine.html', user=user)


@app.route('/logout')
def logout():
    resp = make_response(render_template('login.html'))
    # resp.delete_cookie('user')   # 删除cookie
    session.pop('user')  # 删除session
    return resp

login.html:

<h1>
    登录界面
</h1>
<hr>
<form action="{{ url_for('login') }}" method="post">
    <h3>用户名:</h3>
    <input type="text" placeholder="请输入用户名" name="user">
    <button>提交</button>
</form>
<hr>
<a href="{{ url_for('mine') }}">进入用户中心</a>
最后修改:2021 年 03 月 26 日
如果觉得我的文章对你有用,请随意赞赏