Fork me on GitHub

flask简单操作

flask简介

轻量级的web框架, 遵守MVC的设计模式 创建flask工程,工程中只有三个文件: test.py中自带的程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
from flask import Flask
#实例化flask
app = Flask(__name__)

#注册路由
@app.route('/')
#处理函数
def hello_world():
    return 'Hello World!'

#主函数
if __name__ == '__main__':
    app.run()

启动一个简单的flask服务: 在主函数中添加host、port以及debug:

1
2
3
4
5
6
7
8
 #主函数
 if __name__ == '__main__':
    # 启动flask服务
    app.run(
        host="0.0.0.0",
        port=12344,
        debug=True
    )

在命令行中键入指令: python test.py启动服务 注: 这里的test.py为上述三个文件中的.py文件 服务启动后在浏览器中输入:ip地址:端口号即可访问上述函数hello world

通过命令行方式指定host、port以及debug

导入模块: from flask_script import MAnager

实例化manager: manager = Manager(app=app)

最后修改主函数为:

1
2
3
4
 #主函数
 if __name__ == '__main__':
    # 启动flask服务
    manager.run()

启动服务器: python test.py runserver -h 0.0.0.0 -p 12321 -d

  • -h: 后面指定ip
  • -p: 指定端口
  • -d: debug模式

蓝图

功能: 规划url

导入模块: from flask import Blueprint

实例化: blue = Blueprint('名字', __name__)

注册蓝图: app.register_blueprint(blue)

配置路由时,使用: @blue.route('/')

注意:路由配置完毕之后再注册蓝图

附上完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from flask import Flask, Blueprint
from flask_script import Manager

app = Flask(__name__)
manager = Manager(app=app)
blue = Blueprint('test', __name__)
# 配置路由
@blue.route('/')
def hello_world():
    return 'test blue'
# 注册蓝图
app.register_blueprint(blue)

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

页面显示:

route规则

当需要在地址中传入参数时:

<converter:variable_name> converter可省,省略converter似乎默认string(不确定)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
converter:
	string 	接收任何没有斜杠(‘/’)的文件(默认)
	int	接收整型
	float	接收浮点型
	path	接收路径,可接收斜线(’/’)
	uuid	只接受uuid字符串,唯一码,一种生成规则
	any	可以同时指定多种路径,进行限定
	
	any示例
	@blue.route("/my_any/<any(a,b, c, '20'):p>")
	# my_any路径后边只能是括号里的其中一项
	def my_any(p):
    	print(p)
    	return "ok"

反向解析

url_for:

后端使用:

1
2
3
url_for('蓝图名.函数名', 参数1=值1, 参数2=值2......)
例子:
res = = url_for("test.hello_world")

重定向:

1
2
from flask import redirect
redirect(reverse('蓝图名.函数名'))

前端:

1
2
3

用a标签举例:
<a href="">跳转</a>