Files
haha/https_server_example.py
2026-01-16 09:54:02 +08:00

203 lines
6.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
微信小程序 HTTPS 后端服务器示例
支持 Flask 和 FastAPI 两种框架
"""
# ==================== Flask 版本 ====================
from flask import Flask, jsonify, request
from flask_cors import CORS
import ssl
import os
app = Flask(__name__)
# 配置 CORS允许微信小程序访问
CORS(app, resources={
r"/api/*": {
"origins": "*", # 生产环境建议指定具体域名
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization"]
}
})
@app.route('/api/test', methods=['GET'])
def test():
"""测试接口"""
return jsonify({
'code': 200,
'message': 'HTTPS 接口测试成功',
'data': {
'timestamp': request.headers.get('X-Request-Time', ''),
'user_agent': request.headers.get('User-Agent', '')
}
})
@app.route('/api/user/login', methods=['POST'])
def login():
"""登录接口示例"""
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
# 这里添加您的登录逻辑
if username and password:
return jsonify({
'code': 200,
'message': '登录成功',
'data': {
'token': 'example_token_12345',
'user_id': 1
}
})
else:
return jsonify({
'code': 400,
'message': '用户名或密码不能为空'
}), 400
@app.route('/api/health', methods=['GET'])
def health():
"""健康检查接口"""
return jsonify({
'status': 'healthy',
'service': 'wechat-miniprogram-api'
})
def run_flask_server():
"""运行 Flask HTTPS 服务器"""
# SSL 证书路径(根据您的实际情况修改)
cert_file = os.getenv('SSL_CERT', '/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
key_file = os.getenv('SSL_KEY', '/etc/letsencrypt/live/yourdomain.com/privkey.pem')
# 检查证书文件是否存在
if not os.path.exists(cert_file) or not os.path.exists(key_file):
print(f"警告:证书文件不存在!")
print(f"证书路径: {cert_file}")
print(f"私钥路径: {key_file}")
print("请先配置 SSL 证书,或使用 Nginx 反向代理")
# 开发环境可以运行 HTTP仅用于测试
app.run(host='0.0.0.0', port=8000, debug=True)
return
# 配置 SSL
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert_file, key_file)
print("启动 Flask HTTPS 服务器...")
print(f"访问地址: https://yourdomain.com/api/test")
app.run(
host='0.0.0.0',
port=443,
ssl_context=context,
debug=False # 生产环境设为 False
)
# ==================== FastAPI 版本 ====================
try:
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
fastapi_app = FastAPI(title="微信小程序 API", version="1.0.0")
# 配置 CORS
fastapi_app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 生产环境建议指定具体域名
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@fastapi_app.get("/api/test")
async def test_api(request: Request):
"""测试接口"""
return {
'code': 200,
'message': 'HTTPS 接口测试成功',
'data': {
'timestamp': request.headers.get('x-request-time', ''),
'user_agent': request.headers.get('user-agent', '')
}
}
@fastapi_app.post("/api/user/login")
async def login_api(data: dict):
"""登录接口示例"""
username = data.get('username', '')
password = data.get('password', '')
if username and password:
return {
'code': 200,
'message': '登录成功',
'data': {
'token': 'example_token_12345',
'user_id': 1
}
}
else:
return JSONResponse(
status_code=400,
content={
'code': 400,
'message': '用户名或密码不能为空'
}
)
@fastapi_app.get("/api/health")
async def health_check():
"""健康检查接口"""
return {
'status': 'healthy',
'service': 'wechat-miniprogram-api'
}
def run_fastapi_server():
"""运行 FastAPI HTTPS 服务器"""
cert_file = os.getenv('SSL_CERT', '/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
key_file = os.getenv('SSL_KEY', '/etc/letsencrypt/live/yourdomain.com/privkey.pem')
if not os.path.exists(cert_file) or not os.path.exists(key_file):
print(f"警告:证书文件不存在!")
print(f"证书路径: {cert_file}")
print(f"私钥路径: {key_file}")
print("请先配置 SSL 证书,或使用 Nginx 反向代理")
# 开发环境可以运行 HTTP仅用于测试
uvicorn.run(fastapi_app, host="0.0.0.0", port=8000)
return
print("启动 FastAPI HTTPS 服务器...")
print(f"访问地址: https://yourdomain.com/api/test")
uvicorn.run(
fastapi_app,
host="0.0.0.0",
port=443,
ssl_keyfile=key_file,
ssl_certfile=cert_file
)
except ImportError:
print("FastAPI 未安装,跳过 FastAPI 示例")
print("安装命令: pip install fastapi uvicorn")
# ==================== 主程序 ====================
if __name__ == '__main__':
import sys
# 选择框架:'flask' 或 'fastapi'
framework = os.getenv('FRAMEWORK', 'flask').lower()
if framework == 'fastapi':
try:
run_fastapi_server()
except NameError:
print("FastAPI 未安装,使用 Flask")
run_flask_server()
else:
run_flask_server()