🛠️ 先备好工具箱
Python环境(3.8以上最佳)
虚拟环境
(给项目隔离开,别搞脏全局环境)
1 2 3
| python -m venv venv source venv/bin/activate venv\Scripts\activate
|
装依赖包
(这些够用一阵子了):
1
| pip install flask gunicorn python-dotenv flask-cors
|
🏗️ 搭个最简单的架子
1. 项目结构(推荐这样整)
1 2 3 4 5 6 7 8
| my_flask_api/ ├── app/ │ ├── __init__.py # 应用初始化 │ ├── routes/ # 放各种接口 │ │ └── api.py # 业务逻辑 │ └── config.py # 配置文件 ├── .env # 敏感信息(别传到GitHub!) └── run.py # 启动入口
|
2. 核心代码(超简版)
**app/__init__.py**(应用初始化)
1 2 3 4 5 6 7 8 9 10 11 12 13
| from flask import Flask from .config import Config def create_app(): app = Flask(__name__) app.config.from_object(Config) from .routes.api import api_bp app.register_blueprint(api_bp) return app
|
**app/config.py**(配置)
1 2 3 4 5
| import os class Config: DEBUG = True SECRET_KEY = os.urandom(24)
|
**app/routes/api.py**(接口逻辑)
1 2 3 4 5 6 7 8 9 10 11
| from flask import Blueprint, jsonify api_bp = Blueprint('api', __name__) @api_bp.route('/') def home(): return jsonify({"msg": "Flask API已启动!🚀"}) @api_bp.route('/api/ping') def ping(): return jsonify({"status": "alive"})
|
**run.py**(启动文件)
1 2 3 4 5 6
| from app import create_app app = create_app() if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
|
🚀 跑起来试试!
启动服务:
打开浏览器访问:
http://localhost:5000
http://localhost:5000/api/ping
看到JSON返回就说明成了!🎉
🔧 升级功能!让API更实用
1. 蓝图(Blueprint)——模块化神器
把接口按功能拆分到不同文件,比如用户模块、订单模块:
app/routes/user.py
1 2 3 4 5 6 7
| from flask import Blueprint, jsonify, request user_bp = Blueprint('user', __name__, url_prefix='/api/user') @user_bp.route('/') def get_users(): return jsonify([{"id": 1, "name": "Alice"}])
|
**app/__init__.py**(注册蓝图)
1 2
| from .routes.user import user_bp app.register_blueprint(user_bp)
|
2. 参数处理(GET/POST)
GET带参数:
1 2 3 4
| @api_bp.route('/api/greet') def greet(): name = request.args.get('name', '小伙伴') return jsonify({"msg": f"你好呀,{name}!"})
|
POST接收JSON:
1 2 3 4 5
| @api_bp.route('/api/data', methods=['POST']) def handle_data(): data = request.get_json() return jsonify({"received": data}), 201
|
3. 错误处理(友好提示)
1 2 3
| @app.errorhandler(404) def page_not_found(e): return jsonify({"error": "404啦,你找的接口不存在哦!"}), 404
|
📦 准备上线?这些要配置!
1. 环境变量(.env文件)
1 2
| FLASK_DEBUG=False FLASK_SECRET_KEY=你的超长密钥(生产环境别用随机!)
|
2. 生产服务器(Gunicorn)
1 2
| pip install gunicorn gunicorn -w 4 -b 0.0.0.0:8000 run:app
|
3. Docker一键部署
Dockerfile:
1 2 3 4 5 6
| FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "run:app"]
|