Python使用Flask框架搭建服务

Flask 是一个轻量级的 Python Web 框架,简单易用且灵活。

1.安装Flask

pip install flask

2.最小Flask应用

from flask import Flask
app = Flask(__name__)

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

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

运行后访问 http://127.0.0.1:5000/ 即可看到结果

3.进阶:使用路由及蓝图

使用路由及蓝图可以支持大型项目开发。蓝图(Blueprint)是 Flask 中用于组织大型应用的模块化方式,它允许你将应用分解成可重用的组件。
蓝图的作用:
模块化: 将不同功能拆分成独立模块
可重用性: 可以在多个项目中复用蓝图
延迟路由注册: 避免循环导入问题
URL前缀统一管理: 为同一组路由添加统一前缀

3.1 创建蓝图

在一个单独的文件中(如 auth.py):

# -*- coding: utf-8 -*-

from flask import Blueprint

# 创建蓝图实例
auth_bp = Blueprint(
    'auth',  # 蓝图名称
    __name__,  # 当前模块名
    url_prefix='/auth',  # URL前缀(可选)
    template_folder='templates/auth',  # 蓝图专用模板目录(可选)
    static_folder='static/auth'  # 蓝图专用静态文件目录(可选)
)

@auth_bp.route('/login', methods=['POST'])
def login():
	#对应登录程序
	
    return "登录结果"

@auth_bp.route('/logout', methods=['POST'])
def logout():
	#对应注销程序
	
    return "登出结果"

3.2 注册蓝图

在路由中注册蓝图,统一管理,创建路由文件routes/routes.py

# -*- coding: utf-8 -*-

from app import app
from auth import auth_bp

# app.register_blueprint(auth_bp, url_prefix='/api')
"""注册蓝图"""
app.register_blueprint(auth_bp)

3.3 启动服务

在程序主目录下创建app.py

# -*- coding: utf-8 -*-
from flask import Flask

app = Flask(__name__)

# 注册路由
from routes.routes import *

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

运行app.py,则会启动一个以服务器ip,端口5000的服务。

4. 高级功能

4.1 蓝图资源组织

/myapp
/auth  # 鉴权模块
    __init__.py 
    auth.py     # 鉴权服务
    templates/   # 蓝图专用模板
    static/      # 蓝图专用静态文件
/blog  # 博客模块
    __init__.py
    blog.py
/routes
	__init__.py
	routes.py  # 路由管理
app.py          # 主应用

4.2 蓝图间共享模板

使用 templates 目录结构:

 	/templates
    	/base.html      # 基础模板
   	 	/auth
        	/login.html # 蓝图专用模板
    	/blog
        	/post.html

4.3 蓝图专用静态文件

auth_bp = Blueprint('auth', __name__, static_folder='static/auth')

# 访问方式:/auth/static/filename

4.4 蓝图错误处理器

@auth_bp.errorhandler(404)
def auth_not_found(error):
    return "认证模块的404页面", 404

4.5 蓝图请求钩子

@auth_bp.before_request
def before_auth_request():
    if not is_logged_in():
        return redirect(url_for('auth.login'))

5.实际项目实例

项目结构如下:

myApp          项目名
    - common        公共项目文件目录
    - log           日志文件目录 
    - routes        路由
    - module
	    - module1  模块1 
	    - module2  模块2
	    - module3  模块3
    - static        前端静态文件
        - css       css文件
        - js        js文件
    - templates     前端html文件
    - app.py        主应用
    - Dockerfile    Docker构建文件
    - requirements.txt 依赖申明文件
    - .dockerignore 忽略文件
    - readme.md     说明文件

5.1 登录模块蓝图 /auth/auth.py

# -*- coding: utf-8 -*-

from flask import Blueprint
from flask import request, jsonify

"""创建蓝图"""
auth_bp = Blueprint("auth", __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
	data = request.get_json()
    userName= data.get("username")
    password= data.get("password")
    try:
    	# 查询数据库获取用户信息
        if username and password:
        	token = "token"
        	return jsonify({
	            "message": "success",
	            "result": token
	        })
        else:
       		return jsonify({
	            "message": "success",
	            "result": "用户名或密码不正确"
	        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    

5.2 用户模块蓝图: /user/user.py

# -*- coding: utf-8 -*-
from flask import Blueprint
from flask import request, jsonify

"""创建蓝图"""
user_bp = Blueprint("user", __name__)

# API 接口:业务接口
@user_bp.route('/api/getuserinfo', methods=['POST'])
def getuserinfo():
    """
    :return:
    """
    data = request.get_json()
    userName= data.get("username")

    if not userName:
        return jsonify({"error": "请输入参数"}), 400
    try:
    	# 查询数据库获取用户信息
        userInfo = {"姓名": userName, "年龄": 18, "居住地": "sss"}
        return jsonify({
            "message": "success",
            "result": userInfo 
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

5.3 注册路由,管理蓝图 /routes/routes.py

# -*- coding: utf-8 -*-
"""
注册路由,管理系统所有蓝图
"""

from app import app
from user.user import user_bp
from auth.auth import auth_bp 

"""注册蓝图"""
# app.register_blueprint(user_bp, url_prefix='/api')
app.register_blueprint(user_bp)
app.register_blueprint(auth_bp)

5.4 主应用 /app.py

# -*- coding: utf-8 -*-
"""
主程序入口
"""

from flask import Flask

app = Flask(__name__)

# 注册路由
from routes.routes import *

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值