使用“工厂模式 + 蓝图(Blueprint)”来组织项目结构

This commit is contained in:
huangge1199 2025-06-25 13:37:37 +08:00
parent 0b19e2572d
commit 777ad04397
11 changed files with 45 additions and 37 deletions

View File

@ -1,3 +1,20 @@
# ai-study-python # ai-study-python
python版本的ai学习 python版本的ai学习
<pre lang="md">
├── app/ # 应用主目录
│ ├── __init__.py # Flask app 创建工厂,注册蓝图等
│ ├── api/ # 存放所有 API 接口模块
│ │ ├── __init__.py
│ │ ├── user.py # 示例:用户模块接口
│ ├── models/ # 数据模型如用SQLAlchemy
│ │ └── __init__.py
│ └── services/ # 业务逻辑层(可选)
│ └── __init__.py
├── static/ # 前端静态文件(如果需要本地托管)
├── config.py # 配置文件
├── run.py # 程序入口,启动 Flask 应用
├── requirements.txt # Python 依赖
└── README.md
</pre>

22
app.py
View File

@ -1,22 +0,0 @@
from flask import Flask
from flasgger import Swagger
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
swagger = Swagger(app)
@app.route('/')
def hello_world():
"""
一个hello world 的测试
---
responses:
200:
description: 返回值
"""
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True, port=18080)

View File

@ -1,13 +1,14 @@
from flask import Flask from flask import Flask
from flask_cors import CORS
from flasgger import Swagger from flasgger import Swagger
from flask_cors import CORS
def create_app(): def create_app():
app = Flask(__name__) app = Flask(__name__)
CORS(app) CORS(app)
swagger = Swagger(app) Swagger(app)
from .routes import bp as main_bp # 注册蓝图
app.register_blueprint(main_bp) from .api import user
app.register_blueprint(user.bp)
return app return app

0
app/api/__init__.py Normal file
View File

14
app/api/user.py Normal file
View File

@ -0,0 +1,14 @@
from flask import Blueprint, jsonify
bp = Blueprint('user', __name__, url_prefix='/api/user')
@bp.route('/hello')
def hello():
"""
用户模块测试接口
---
responses:
200:
description: Hello from user module
"""
return jsonify(message='Hello from user')

0
app/models/__init__.py Normal file
View File

View File

@ -1,8 +0,0 @@
from flask import Blueprint, jsonify
bp = Blueprint('main', __name__)
@bp.route('/api/hello', methods=['GET'])
def hello():
return jsonify({"message": "Hello from Flask!"})

0
app/services/__init__.py Normal file
View File

0
config.py Normal file
View File

View File

@ -1,3 +1,3 @@
flask flask==3.1.1
flasgger==0.9.7.1
flask-cors flask-cors
flasgger

6
run.py Normal file
View File

@ -0,0 +1,6 @@
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True, port=18080)