入门(十)Flask框架

1、简介

常见的Python Web框架:

  • Flask:是一个使用 Python 编写的轻量级Web框架,快速开发Web应用
  • Django:全能型Web框架,重量级,功能强大

(1)安装

  • pip install flask
    (2)使用
from flask import Flask

# 创建一个app,
app = Flask(__name__)


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


@app.route('/list')
def list_book():
    return str([1, 2, 3])
    
    
if __name__ == '__main__':
    app.run(port='8000', debug=True)

开启debug后,会监测文件更改,并且给出更详细的报错信息

2、获取参数

(1)、get请求参数

from flask import Flask, request


app = Flask(__name__)


@app.route('/test_get')
def test_get():
    a = request.args.get('a', default=1)
    b = request.args.get('b', default=2)
    print(a, b)
    return 'get'


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

(2)、post请求参数

from flask import Flask, request


app = Flask(__name__)


@app.route('/test_get')
def test_get():
    a = request.args.get('a', default=1)
    b = request.args.get('b', default=2)
    print(a, b)
    return """
    
姓名: 密码:
""" @app.route('/test_post', methods=['POST', 'GET']) def test_post(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] return username else: return '登录失败' if __name__ == '__main__': app.run(debug=True)

(3)、rest动态路由

from flask import Flask, request


app = Flask(__name__)


@app.route('/test_rest/')
def test_rest(username):
    return username
    

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

rest参数类型限定,@app.route('/test_rest/')

(4)、文件上传

from flask import Flask, request
import time
import random

app = Flask(__name__)


@app.route('/getload')
def get_load():
    return '''
    
file:
''' @app.route('/upload',methods=['post']) def upload(): file = request.files['file'] save_path = (time.strftime('%Y{0}%m{1}%d{2}%H%M%S')).format('年', '月', '日') + str(random.randint(1,100)) + file.filename file.save(save_path) return 'success' if __name__ == '__main__': app.run(debug=True)

(5)、JinJa2语法
变量传递

@app.route('/test_template')
def test_template():
    return render_template('demo.html', username='zhangsan', age=18)

页面语法
变量引用


{{username}}

分支语法


{% if username: %}
{{username}}
{% else %}
姓名为空
{% endif %}

循环语法


    {% for user in age %}
  • {{user.name}}
  • {% endfor %}

全局处理异常

@app.errorhandler(404)
def error_hander(e):
    print(e)
    return render_template('404.html')

(6)、利用蓝图模块化路由

  • 定义user模块

from flask import Blueprint

# 创建蓝图
user_cont = Blueprint('user', __name__)


@user_cont.route('/user')
def prod_list():
    return 'user_list'
  • 定义product模块
from flask import Blueprint

# 创建蓝图
product_controller = Blueprint('product_controller', __name__)


@product_controller.route('/pro')
def prod_list():
    return 'prod_list'

注册路由

from flask import Flask, request, redirect, jsonify, render_template
from mymodule.user_controller import user_cont
from mymodule.product_controller import product_controller


app = Flask(__name__)
app.register_blueprint(user_cont)
app.register_blueprint(product_controller)

你可能感兴趣的:(入门(十)Flask框架)