1. 准备
- 安装好python环境、使用pip(pip可以配置国内镜像源)安装ddddocr、flask、requests
- 写了两个api,使用网图作为参数的/coder接口,使用本地图片作为参数的upload接口
import requests
from flask import Flask, request, jsonify
import ddddocr
ocr = ddddocr.DdddOcr()
app = Flask(__name__)
@app.route('/coder', methods=['POST'])
def coder():
picpath = request.json.get('picpath') # 假设你通过POST请求发送JSON数据
if picpath is None:
return jsonify({'error': 'picpath not none'}), 400
try:
response = requests.get(picpath)
response.raise_for_status() # 确保请求成功
with open("./testpng.png", "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk) # 写入图片二进制数据
with open('./testpng.png', 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
tempjson = {'code': '0'}
tempjson['code'] = res
return jsonify(tempjson) # 使用 jsonify 来返回 JSON 响应
except requests.exceptions.MissingSchema:
return jsonify({'error': 'File Not Found'}), 400
@app.route('/upload', methods=['POST'])
def upload_file():
# 检查请求方法是否为 POST
if request.method == 'POST':
# 检查是否有文件字段
if 'file' not in request.files:
return jsonify({'error': 'agrs error'}), 400
file = request.files['file']
# 检查文件是否存在
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
# 保存文件到指定目录
file.save('./' + file.filename)
with open('./' + file.filename, 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
tempjson = {'code': '0'}
tempjson['code'] = res
return jsonify(tempjson)
return jsonify({'error': 'Method Not Allowed'}), 405
if __name__ == "__main__":
app.run(host='localhost', port=8080, debug=True)
2. 实际调用