Flask

本文介绍了Flask Web框架的基本概念、安装步骤及常用组件,包括如何创建虚拟环境、蓝图管理、URL规则设定等,并探讨了请求处理、响应生成及会话管理的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Flask

Flask是一个Python编写的Web 微框架,让我们可以使用Python语言快速实现一个网站或Web服务。database,templates需要自己去组装。

安装

创建虚拟环境

virtualenv --no-site-packages flaskenv
cd flaskenv
cd Script

启动虚拟环境:

activate

安装flask

pip install flask

运行flask

python xxx.py(启动默认127.0.0.1:5000端口)

运行参数

# debug = True  调试
# port = '8000'  端口
# host = '0.0.0.0'  IP
app.run(debug=True, port='8000', host='0.0.0.0')

修改启动方式

pip install flask-script
# 控制台中输入命令,显然这样的启动方式也是比较麻烦的,可以配置pycharm中的debug的启动
python hello.py runserver -p 端口 -h IP -d

蓝图(Blueprint)管理url,规划url

pip install flask_blueprint
1.初始化:
from flask import Blueprint
stu = Blueprint('stu', __name__)
2.路由注册:
app.register_blueprint(blueprint=stu, url_prefix='/stu')# 蓝图前缀 url_prefix

route规则

Django中传参:
127.0.0.1/index/(\d+)/
127.0.0.1/index/?P<id>(\d+)/
flask中传参
<converter:name>
string: 默认字符串,可以省略

int: 整型

float:浮点型

path: '/'也是当做字符串返回

@blue.route('/getpath/<path:hello,world>')
def hello_path(url_path):

    return 'path: %s' % url_path
# 页面返回
path:hello,world
@blue.route('/getpath/<path:hello/world>')
# 页面返回
path:hello/world

uuid: uuid类型  UUID是128位的全局唯一标识符,通常由32字节的字符串表示
@blue.route('/getuuid')
def gello_get_uuid():
    a = uuid.uuid4()
    return str(a)
# 页面返回
65c7804c-e0b7-4cbe-b866-cd5b152c55a8

request 请求

args--->  GET请求,获取参数

form--->  POST请求,获取参数

files-->  上传的file文件

method--> 请求方式

base_url

path

cookies

response 响应

服务端自己创建,然后返回给客户端,传入自己定义的状态码,make_response(‘页面’,状态码)

@blue.route('/makeresponse')
def make_responses():
    # response = make_response('<h2>whatever</h2>')
    temp = render_template('hello.html')
    response = make_response(temp, 400)  # 传入状态码

    return response, 500  # 也可以在这里传入状态码

@blue.route('/makeabort') # 抛出异常
def make_abort():
    abort(400)
    return '终结'

@blue.errorhandler(400) # 捕捉异常
def get_error(exception):

    return '捕捉异常:%s' % exception    
# /makeabort页面返回
如果没有捕捉异常:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
有捕捉异常:
捕捉异常:400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

session

安装:

pip install flask-session
pip install redis

使用数据库:
SESSION_TYPE类型

redis
mongodb
memcached
sqlchemy

from flask_session import Session
在初始化中配置app
app.config['SECRET_KEY'] = 'secret_key'
# 使用redis存储信息,默认访问redis了, 127.0.0.1:6379
app.config['SESSION_TYPE'] = 'redis'
# 设置访问redis
app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379')
# 定义前缀
app.config['SESSION_KEY_PREFIX'] = 'flask'
# 第一种初始化app
Session(app)

@blue.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        username = session.get('username')
        return render_template('login.html', username=username)
    else:
        username = request.form.get('username')
        session['username'] = username

        return redirect(url_for('app.login'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值