如何在Python中使用flask框架搭建web服务?
在 Python 中使用 Flask 框架搭建 Web 服务非常简单,以下是一个详细的步骤指南和示例代码:
1. 安装 Flask
首先需要安装 Flask 库:
bash
pip install flask
2. 基本 Web 服务示例
下面是一个最简单的 Flask Web 服务,包含基本路由和响应:
Flask基本Web服务示例
V1
创建时间:22:24
3. 运行和测试服务
将上述代码保存为
app.py
运行服务:
bash
from flask import Flask, request, jsonify import os import os.path# 导入你已有的读取方法(请替换为实际的模块和方法名) from your_module import read_pdf # 你的PDF读取方法 from your_module import read_word # 你的Word读取方法app = Flask(__name__)# 定义允许读取的文件类型及其对应的处理方式 ALLOWED_FILE_TYPES = {'txt': 'read_text', # 文本文件'csv': 'read_text', # CSV文件'json': 'read_text', # JSON文件'pdf': 'read_pdf', # PDF文件(使用已有方法)'docx': 'read_word' # Word文件(使用已有方法) }def read_text_file(file_path):"""读取文本类文件内容"""try:with open(file_path, 'r', encoding='utf-8') as f:return f.read(10000) # 限制读取前10000字符,防止过大文件except UnicodeDecodeError:# 尝试其他编码with open(file_path, 'r', encoding='gbk') as f:return f.read(10000)except Exception as e:raise Exception(f"读取文本文件失败: {str(e)}")# 定义路由:处理根路径的GET请求 @app.route('/', methods=['GET']) def home():return "<h1>欢迎使用文件读取API</h1><p>使用/api/read-file?file_type=类型&file_path=路径 来读取文件内容</p>"# 读取文件内容的API @app.route('/api/read-file', methods=['GET']) def read_file():"""读取指定类型和路径的文件内容参数:file_type: 文件类型(如txt, pdf, docx等)file_path: 文件的完整路径或相对路径"""# 获取GET参数file_type = request.args.get('file_type')# 验证参数是否齐全if not file_type or not file_path:return jsonify({'status': 'error','message': '请提供file_type和file_path两个参数'}), 400# 验证文件类型是否被允许if file_type.lower() not in ALLOWED_FILE_TYPES:return jsonify({'status': 'error','message': f'不支持的文件类型: {file_type}, 支持的类型: {", ".join(ALLOWED_FILE_TYPES.keys())}'}), 400# 验证文件是否存在if not os.path.exists(file_path):return jsonify({'status': 'error','message': f'文件不存在: {file_path}'}), 404# 验证文件是否为文件(不是目录)if not os.path.isfile(file_path):return jsonify({'status': 'error','message': f'不是有效的文件: {file_path}'}), 400# 验证文件类型是否匹配file_ext = os.path.splitext(file_path)[1].lower().lstrip('.')if file_ext != file_type.lower():return jsonify({'status': 'warning','message': f'文件类型不匹配,实际类型: {file_ext}, 请求类型: {file_type}','data': None}), 200try:# 根据文件类型选择对应的读取方法read_method = {'txt': read_text_file,'csv': read_text_file,'json': read_text_file,'pdf': read_pdf, # 使用已有的PDF读取方法'docx': read_word # 使用已有的Word读取方法}.get(file_type.lower())# 调用对应的读取方法content = read_method(file_path)# 限制内容长度(如果已有方法没有限制的话)if len(content) > 10000:content = content[:10000]content_truncated = Trueelse:content_truncated = False# 获取文件基本信息file_stats = os.stat(file_path)return jsonify({'status': 'success','message': '文件读取成功','data': {'file_path': file_path,'file_type': file_type,'file_size_bytes': file_stats.st_size,'content_preview': content,'content_truncated': content_truncated}}), 200except Exception as e:return jsonify({'status': 'error','message': f'读取文件时发生错误: {str(e)}','data': None}), 500# 启动服务 if __name__ == '__main__':app.run(host='0.0.0.0', port=5000, debug=True)
服务会在
http://localhost:5000
启动测试方式:
- 访问
http://localhost:5000
查看首页 - 访问
http://localhost:5000/user/abc
查看用户页面 - 使用 curl 测试 POST 接口:
bash
curl -X POST http://localhost:5000/api/data \-H "Content-Type: application/json" \-d '{"name": "测试", "value": 123}'
- 访问
4. 核心概念解释
- 路由(Route):通过
@app.route()
装饰器定义,指定 URL 路径和允许的 HTTP 方法 - 请求处理:
request
对象用于获取客户端发送的数据(表单、JSON 等) - 响应:可以返回字符串、HTML 或使用
jsonify()
返回 JSON 格式响应 - 调试模式:
debug=True
启用调试模式,代码修改后自动重启服务
5. 生产环境部署
生产环境中不应使用 Flask 内置服务器,推荐使用 Gunicorn:
bash
# 安装Gunicorn
pip install gunicorn# 启动服务
gunicorn -w 4 -b 0.0.0.0:5000 app:app
通过以上步骤,你可以快速搭建一个功能完善的 Flask Web 服务,并根据需求扩展更多路由和业务逻辑。