我正在使用python flask构建我的第一个api,客户端会将图像发布到api。虽然该api非常适合50kb的较小文件,但在上传500kb-2mb的文件时会引发错误。我已经在这里阅读了许多帖子,以及其他博客和github问题,并且我了解到服务器在收到完整文件之前超时会抛出错误。
我遇到的一些选择是:
使用from requests_toolbelt.multipart import encoder
并使用encoder.MultipartEncoder对图像进行编码。
将app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024
添加到server.py中-我这样做了,但这没有帮助。
当前api不使用wsgi或nginx(坦率地说,我不知道如何使用它们或它们的用途,并且当前正在测试我的api的响应),并在调试模式下运行。
我的客户如下:
client.py
import requests
from requests_toolbelt.multipart import encoder
session = requests.Session()
with open('124430597.jpg', 'rb') as f:
files = encoder.MultipartEncoder({
"image_data": ("124430597.jpg", f, "application/octet-stream"),
"composite": "NONE",
})
url = 'http://10.7.104.57:5000/julytest'
headers = {"Prefer": "respond-async", "Content-Type": files.content_type}
resp = session.get(url, headers=headers, data=files)
print(resp.text)
server.py
#!/usr/bin/env python
from PIL import Image
import io
import requests
import numpy as np
import os
from os.path import basename
from flask import Flask, flash, request, redirect, url_for,jsonify, make_response
from werkzeug.utils import secure_filename
from flaskext.mysql import MySQL
from imagesearch.cbir import HSVDescriptor
from imagesearch.cbir import Searcher
import MySQLdb
import datetime
import cv2
UPLOAD_FOLDER = '/home/magesh/imgdb/'
ALLOWED_EXTENSIONS = set(['jpg', 'jpeg'])
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'Abc@123def'
app.config['MYSQL_DATABASE_DB'] = 'tamprint'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024
mysql = MySQL()
mysql.init_app(app)
mysql = MySQL()
mysql.init_app(app)
@app.route('/julytest', methods=['GET', 'POST'])
def get():
print(request.files['image_data'])
img = request.files['image_data']
fil = img.filename
w = 16.5
h = 20.5
l = w-0.25
m = w-0.25
p = h-0.25
q = h-0.25
image = cv2.imread(img.filename)
#rows, cols, channels = image.shape
#print(rows,cols,channels)
cv2.imwrite(fil, image)
cur = mysql.connect().cursor()
#do other stuff
正如我之前说过的,这对于较小的图像非常适用。...但是对于较大的图像,我无法使用OpenCV读取它们,这表明我没有在服务器端收到这些图像。