Flask 基本知识点

1路由
为了便于记忆URL,现代Web框架通过了路由技术提到复杂的URL,特别是那些非首页导航进入的页面。
示例代码:
@app.route('/')
def hello_world():
    return 'Hello World'
2、使用变量
要给URL添加变量部分,可以把这些特殊的字段标记为<variable_name>,这个部分将会作为命名参数传递到函数里。
如果这些特殊的字段是数值,可以用 <converter:variable_name>指定一个转换器。转换器有下面几种:
int:接受整数。
float:接受浮点数。
URL添加变量还可以一个斜杠(/)结尾,他被作为目录分隔符。


 使用Jinja2模板
1.没有使用模板
@app.route('/book/')
def show_book_info():
    s = '''
    <html>
        <body>
            <h3>书名:《Python从小白到大牛》</h3>
            <h3>作者:关东升</h3>
        </body>
    </html>

2.使用模板
Jinja2模板库使用 render_template()函数。
代码文件hello.py:
@app.route('/book/')
def show_book_info():
    return render_template('book.html', book_name = 'Python从小白到大牛', author='关东升' '')
 
模板文件book.html:
<html>
    <body>
        <h3>书名:《{{ book_name }}》</h3>
        <h3>作者:{{  author }}</h3>
    </body>
</html>

 

3、Jinga2模板引擎中表达式
{{ ... }} 输出表达式结果。
Jinga2变量过滤器:
{{ 变量 | 过滤器 }}
capitalize:首字母大写。
lower:小写。
upper:大写
title:所有单词首字母大写。
trim:去除前后空格。
striptags:去除html标签。
safe:字符串不转义。
 
4、Jinga2模板引擎中语句
{% ... %} 使用语句。语法结构:
{% 语句 %} 
...
{% end语句  %} 
例如:
判断结构:
{% if 条件表达式 %} 
...
{% endif %} 
循环结构:
{% for item in 序列 %} 
...
{% endfor %} 
 
5、模板继承
 定义基础模板base.html:
<div id="content">
    {% block body %}
    {% endblock %}
</div>
继承基础模板login.html:
{% extends "base.html" %}
...
{% block body %}
  <table width="40%" border="0">
   ...
  </table>
{% endblock %} 
 访问静态文件:

Web应用有一些静态文件,如:图片文件、CSS文件和Javascript文件等。
使用Jinja模板时静态文件放到当前py文件同级的static文件夹中。
获得这些静态文件URL路径,可以使用url_for()函数。
示例:
 url_for('static', filename = 'css/book.css')
 
在模板文件中使用 url_for()函数:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename = 'css/book.css') }}">
<img src="{{ url_for('static', filename = 'images/book_img2.jpg') }}" width="20px" height="20px">


 Request 请求对象

HTTP协议有请求和应答过程,客户端提交的数据被封装在请求对象中。Flask提供了请求对象Request,Request的属性:
Form:是一个表单对象,它是字典类型数据,包含了客户端提交表单数据,数据的键是客户端控件名,数据的值是客户端控件的值。
args:是客户端提交参数,参数是跟在URL的?后面的内容,127.0.0.1:5000/login?userid=tony&userpwd=12345
Cookies:是客户端Cookies对象,它是字典类型数据。
files:与上传文件相关数据。
method:获得当前请求方法。
 
使用Request对象示例:
hello.py文件: 
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        my_form = request.form
        print(my_form['userid'])
        print(my_form['userpwd'])
        return render_template('result.html', result=my_form)
    else:
        args_info = request.args
        print(args_info['userid'])
        print(args_info['userpwd'])
        return render_template('result.html', result=args_info)
 
login.html文件:
<form action = "/login" method = "POST">
  <table width="40%" border="0">
    <tbody>
      <tr>
        <td>用户ID:</td>
        <td><input name="userid" type="text"/></td>
      </tr>
      <tr>
        <td>密码:</td>
        <td><input name="userpwd" type="password"/></td>
      </tr>
      <tr align="center">
        <td colspan="2">
          <input type="submit" value="确定">
          <input type="reset" value="取消">
        </td>
      </tr>
    </tbody>
  </table>
</form>

 Response 对象

HTTP协议有请求和应答过程,服务器端返回的数据被封装在应答对象中。 HTTP协议应答包含了返回给客户端的字符串、状态码(默认是200)。
Flask可以使用 make_response函数获得Response应答对象。
视图函数返回字符串:
@app.route('/hello')
def hello():
    return '<h1>Helo World.</h1>'
 
视图函数也可以返回Response应答对象:
@app.route('/hello')
def hello():
    response = make_response('<h1>Hello World.</h1>')
    return response
 
返回Response应答对象有很多优点:可以设置应答状态码、设置Cookie、设置应答头信息。
@app.route('/hello')
def hello():
    response = make_response('<h1>Hello World.</h1>', 200)
    response.headers['Content-Type'] = 'text/html'
    return response
    
使用模板:
response = make_response(render_template('login.html'))
 
 Cookie 对象

Cookies是存储在客户端计算机上的数据,不同的浏览器有自己的存储目录,使用Cookies的目的是记住和跟踪与客户使用相关的数据。
1、设置Cookies,使用Response的set_cookie函数:
@app.route('/setcookie')
def set_cookie():
    response = make_response('<h1>设置Cookie</h1>')
    response.set_cookie('userid', 'tony')
    return response
还可以设置Cookies的过期时间: 
timeoutdate = datetime.today() + timedelta(days=10)
response.set_cookie('userid', 'tony', expires=timeoutdate)
 
2、获取Cookies,使用Request的cookies属性返回Cookies对象,再通过Cookies键获得:
@app.route('/getcookie')
def get_cookie():
    name = request.cookies.get('userid')
    print(name)
    s = '<h1>Cookie中userid:{0}</h1>'.format(name)
    return s
Session 对象

Session(会话)与Cookies不同,Session是存储在服务器端内存,服务器为每一个客户端分配一个Session ID,当浏览器关闭或Session操作超时,Session就会失效。Session往往用来存储用户的登录信息。Session数据结构与Cookies一样都是字典结构。
 
 1、设置Session:
from flask import Flask, render_template, request, session
app = Flask(__name__)
app.secret_key = '任何不容易被猜到的字符串'
...
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['userid'] = request.form['userid']
    return render_template('result.html')
 
2、获取Session:
<h3>存储在Session中的userid数据:{{ session['userid'] }}</h3>
 
3、删除Session,使用session.pop()方法:
@app.route('/logout')
def logout():
    session.pop('userid', None)
    return render_template('result.html')
 
 重定向

 


有时需要将用户重新定位到其他网址,可以使用redirect函数,redirect函数返回一个应答对象,定义如下:
redirect(location, statuscode=302, response=None)
location:重定位地址。url_for('success'),success是一个视图函数的名字,不是路由url。
statuscode:设置状态码。
response:应答对象。
状态码参考:https://baike.baidu.com/item/HTTP%E7%8A%B6%E6%80%81%E7%A0%81/5053660?fr=aladdin
 
return redirect(url_for('success'))
...
@app.route('/success')
def success():
    return '<h3>登录成功。</h3>'
 
return redirect(url_for('index'))
...
@app.route('/')
def index():
    return render_template('login.html')
 
 
放弃请求使用函数abort(statuscode),statuscode是HTTP错误状态码。
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        my_form = request.form
        if my_form['userid'] == 'Tony' and my_form['userpwd'] == '123':
            return redirect(url_for('success'))
        else:
            abort(401)  # 401 Unauthorized(未授权)
    else:
        return redirect(url_for('index'))

13 显示消息

Web应用程序需要把信息输出到页面。
1、设置要页面要显示的信息
Flask提供了flash函数设置要页面要显示的信息,flash函数的定义如下:
flash(message, category='message')
message:输出的文本消息。
category:消息类别,取值 'error'、'info'和'warning'。
注意: flash函数是将消息放到Session中的,因此需要设置app.secret_key = '任何不容易被猜到的字符串'。
 14 文件上传

1、上传文件客户端网页表单
 
<form action="/upload" method="POST" 
      enctype="multipart/form-data">
  <input type="file" name="myfile"><br><br>
  <input type="submit" name="开始上传">
</form>
上传表单3个要点:
表单method="POST"。
表单enctype="multipart/form-data",当上传的内容是非文本,如图片等时,需要将form的enctype="multipart/form-data",enctype是编码类型。
使用HTML上传控件,<input type="file" name="myfile">。
 
2、服务器端
使用request.files[]获得客户端上传的文件对象。
from werkzeug.utils import secure_filename
...
@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['myfile']
        f.save(secure_filename(f.filename))
    return '上传文件成功。'
f.filename获得上传文件名。secure_filename函数获得安全文件名,防止客户端伪造文件。
 
3、设置服务器上传文件夹
app.config['UPLOAD_FOLDER'] = 'd:/uploads'
app.config是Flask应用配置对象。

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['myfile']
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return redirect(url_for('uploaded_file',
                            filename=filename)) # 重定位上传文件


@app.route('/uploaded/<filename>')
def uploaded_file(filename):      
         return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)
send_from_directory函数可以以安全方式访问上传文件。 
 
4、限制上传文件大小
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024  # 小于1M
 

2、页面中显示消息
页面中显示消息可以通过get_flashed_messages函数,get_flashed_messages函数定义如下:
get_flashed_messages(with_categories=False, category_filter=[])
with_categories:设置是否采用类别,默认是False,
category_filter:设置消息类别过滤器,with_categories为True才需要。
该函数返回的信息列表,如果with_categories为False返回的列表元素是字符串;如果with_categories为True返回的列表元素是二元组(消息类别,消息)。
 
示例1:
hello.py文件:
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        my_form = request.form
        if my_form['userid'] == 'Tony' and my_form['userpwd'] == '123':
            flash('登录成功。')
            return redirect(url_for('success'))
        else:
            flash('登录失败。')

    return render_template('login.html')
base.html文件:
<!-- 显示信息 -->
{% with messages = get_flashed_messages() %}
 {% if messages %}
    <ul>
       {% for message in messages %}
       <li>{{ message }}</li>
       {% endfor %}
    </ul>
 {% endif %}
{% endwith %}

with定义一个代码块:
{% with %}
...
{% endwith %}
 
示例2:
hello.py文件:
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        my_form = request.form
        if my_form['userid'] == 'Tony' and my_form['userpwd'] == '123':
            flash('登录成功。', 'info')
            return redirect(url_for('success'))
        else:
            flash('登录失败。', 'error')

    return render_template('login.html')
 
 
base.html文件:
<!-- 显示信息 -->
{% with messages = get_flashed_messages(True, ['error', 'info']) %}
 {% if messages %}
    <ul>
       {% for message in messages %}
           {% if message[0] == 'info' %}
                <li class="success">{{ message[1] }}</li>
           {% else %}
                <li class="error">{{ message[1] }}</li>
           {% endif %}
       {% endfor %}
    </ul>
 {% endif %}
{% endwith %}

参考资料:https://www.cnblogs.com/tqtl911/p/9686998.html

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值