Python之Flask框架

Python之Flask框架

1. 项目结构

  • DemandSys
    • blueprints
    • config
    • models
    • static
    • templates
    • app.py

blueprints – “蓝图”文件夹下存放各个功能模块的实现文件,每一个功能“蓝图”都需要在 app.py 文件中进行注册

config – 存放各种配置文件。需要注意的是,启动项目时的位置在app.py同级,所以打开配置文件时,路径填写如下:

1
with open("./config/dbconf.json", mode="r", encoding="utf-8") as f

models – 存放各种模型(类)文件

static – 存放所有的js、css文件

templates – 存放所有的页面

2. 开发思路

2.1 关于蓝图的使用

Auth.py文件中

1
2
3
4
5
6
7
8
# 第一个auth_bp是在url_for中调用使用的,第二个auth_bp是在网页地址栏中呈现的
# action="{{ url_for("auth_bp.login") }}" 此处的login指的是方法名
# http://127.0.0.1:5000/auth_bp/login 此处的login指的是route后面填写的名称
auth_bp = Blueprint("auth_bp", __name__, url_prefix="/auth_bp")

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
。。。

app.py文件中

1
2
# 注册认证类模块蓝图,包括登录、注册功能
app.register_blueprint(auth_bp)

2.2 全局变量

1
2
3
4
from flask import current_app

# 直接在current_app中创建一个全局变量,并且对其赋值即可
current_app.curUser = curUser

2.3 页面跳转的通用方法

1
2
3
4
5
# 针对iframe方式来跳转
# 根据传递的参数不同,跳转到对应的页面
@app.route('/iframe/<name>', methods=['GET'])
def iframeRouter(name):
return render_template(name, curUser=current_app.curUser, curDomainRole=current_app.curDomainRole)

这个方法有一个问题是,它是整个项目的路由,会拦截前端页面中所有的

onclick
1
2
3
4
5
6
7
8
9
10
11

例子: 点击编辑按钮的时候要传递用户id,后台获取用户id对应的所有的用户信息后,跳转到编辑页面,并初始化文本框信息。在加了路由之后,a标签的点击跳转事件就不会跳到后台对应的方法,而是被 `iframeRouter` 方法拦截,会报错。折中的解决方法就是点击按钮之后,跳转到js方法,通过ajax将用户信息保存到全局变量,返回成功后,打开编辑页面,写一个 `window.onload` 方法,获取到全局变量,返回成功后,初始化文本框

#### 2.4 redirect 和 render_template

- redirect:方法之间的调用
- render_template:跳转到对应的页面,并可以在后面添加传递的参数

#### 2.5 flask 获取前端传过来的数据

首先需要在方法名上添加注解,比如

@auth_bp.route(‘/login’, methods=[‘POST’])

1
2
3
4
5
6

之后通过`request.form["xxx"]`即可获取到对应的值

### 3. 异常

#### 3.1 启动异常

[Errno 48] Address already in use
解决端口占用:
sudo lsof -i:5000
kill -9 端口号