flask学习(四)

1.消息闪现

消息闪现会在请求结束时记录信息,并(且仅在)下一请求中访问信息。
flash()函数会闪现一条消息
get_flashed_messages()函数操作消息本身,在模版中也可以使用。

实例

from flask import Flask,url_for,flash,render_template,redirect,request

app=Flask(__name__)
app.secret_key="some_secret"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login',methods=['GET','POST'])
def login():
    error=None
    if request.method=='POST':
        if request.form['username']!='admin' or \
            request.form['password']!='secret':
            error='Invalid credentials'
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html',error=error)

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

layout.html

<!DOCTYPE html>
<title>My Application</title>
{% with messages=get_flashed_messages() %}
    {% if messages %}
        <ul class=flashes>
            {% for message in messages %}
                <li>{{message}}</li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}
{% block body %}
{% endblock %}

index.html

{% extends "layout.html" %}
{% block body %}
    <h1>Overview</h1>
    <p>Do you want to <a href="{{ url_for('login')}}">log in?</p>
{% endblock %}

login.html

{% extends "layout.html" %}
{% block body %}
    <h1>Login</h1>
    {% if error %}
        <p class=error><strong>Error:</strong>{{error}}</p>
    {% endif %}
    <form action="" method=post>
        <dl>
            <dt>Username:
            <dd><input type=text name=username value={{request.form.username}}></dd>
            <dt>Password:
            <dd><input type=password name=password>
        </dl>
        <p><input type="submit" value="Login"></p>
    </form>
{% endblock %}

2.日志记录

例子:

app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')

3.静态文件

静态文件主要包含CSS,Javascript,图片,字体等静态资源文件。
url_for()生成静态文件路径
url_for('static',filename='style.css')生成的路径就是“/static/style.css”
定制静态文件的真实路径
app=Flask(__name__,static_folder='/tmp')

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,473评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,955评论 18 399
  • 这个男孩25岁,很勉强的眯眼笑,不是纯粹的开心而且他身上穿的那么少,却带那么厚的大帽子,极不搭配,别扭。像我自己的...
    只皇皇阅读 2,593评论 0 0
  • 顾海住院后,最终脱离了生命危险。当他睁开眼的时候,第一眼看见的是顾洋。顾海蹭一下坐了起来,拽着顾洋的衣领,“因子人...
    芥墨阅读 4,729评论 1 0
  • 贫穷会导致判断力下降吗? 当人类最基本的需要未能满足的时候,他所有的注意力都会集中在那些狭窄的需求上面,没有办法考...
    反过来跑阅读 2,490评论 0 1