Flask-微型Python框架

“微”的含义:

“微”并不代表整个应用只能塞在一个 Python 文件内, 当然塞在单一文件内也没有问题。

“微”也不代表 Flask 功能不强。

微框架中的“微”字表示 Flask 的目标是保持核心简单而又可扩展

一个最小的应用,hello.py

视图是一个应用对请求进行响应的函数。

from flask import Flask     #导入类
app = Flask(__name__)       #创建类实例
​
@app.route('/')             #route()装饰器来告诉flask触发函数的url
def hello_world():          #函数名称被用于生成相关联的url
    return 'Hello, World!'

 

启动前需要导出FLASK_APP环境变量:

export FLASK_APP=hello.py

启动方式:1 使用flask命令: flask run

2 使用python 的-m 开关: python -m flask run

默认启动地址是 http://127.0.0.1:5000/,flask run --host=0.0.0.0可以让自己的服务器被公开访问。

转换器

@app.route('/hello')
def hello():
    return 'Hello, World'
    
@app.route('/user/<username>')   #通过把URL的一部分标记为 <variable_name> ,从而在URL中添加变量
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(username)
​
@app.route('/post/<int:post_id>') # 接受正整数
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id
​
@app.route('/path/<path:subpath>')  # 接受可包含斜杠的string
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

 

构造URL

url_for() 函数用于构建指定函数的 URL。它把函数名称作为第一个 参数。它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量将添加到 URL 中作为查询参数。

from flask import Flask, escape, url_for
​
app = Flask(__name__)
​
@app.route('/')
def index():
    return 'index'
​
@app.route('/login')
def login():
    return 'login'
​
@app.route('/user/<username>')
def profile(username):
    return '{}\'s profile'.format(escape(username))
​
with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))            #未知参数next将作为查询参数
    print(url_for('profile', username='John Doe'))

 

/
/login
/login?next=/
/user/John%20Doe

HTTP方法和请求对象

from flask import request
​
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    else:
        return show_the_login_form()

 

操作请求数据

method 属性可以操作当前请求方法, form 属性处理表单数据, args 属性操作url中提交的参数,files 属性来访问上传的文件,cookies 属性访问cookies

from flask import request
​
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)

 

渲染模板

url_for('static', filename='style.css') #静态文件
​
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name) #html文件渲染

 

重定向和错误

from flask import abort, redirect, url_for
​
@app.route('/')
def index():
    return redirect(url_for('login'))
​
@app.route('/login')
def login():
    abort(401)                   #401表示禁止访问
    this_is_never_executed()
​
@app.errorhandler(404)           #errorhandler装饰器定制出错页面
def page_not_found(error):       #404表示页面不存在
    return render_template('page_not_found.html'), 404

 

响应

返回响应对象,视图返回的字符串会被包含在响应体里,而字典会调用 jsonify函数创建响应对象。

消息闪现

flash() 用于闪现一个消息。在模板中,使用 get_flashed_messages() 来操作消息。

 

模块化

随着flask程序越来越复杂,我们需要对程序进行模块化的处理,之前学习过python的模块化管理,于是针对一个简单的flask程序进行模块化处理

简单来说,Blueprint 是一个存储视图方法的容器,这些操作在这个Blueprint 被注册到一个应用之后就可以被调用,Flask 可以通过Blueprint来组织URL以及处理请求。

posted @ 2021-03-09 20:02  小小马进阶笔记  阅读(192)  评论(0编辑  收藏  举报