flask
安装flask
pip install flask
使用flask
from flask import Flask, request
import sys
import os
sys.path.append('.')
app = Flask(__name__)
import PredictDogCat
model = PredictDogCat.init('/workspace/Projects/DogAndcat/models/dogcat_20200813.h5')
import time
import random
import string
import threading
import json
lock = threading.Lock()
def generate_random_str(randomlength=16):
# string.digits=0123456789
# string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
random_str = ''.join(str_list)
return random_str
@app.route("/cv/dogcat/v1/recognize",methods=['POST'])
def check():
text=""
rz=""
stus={'code':0,'info':''}
if request.method == 'POST':
f = request.files['imagefile']
basepath = '/'
upload_path = os.path.join(basepath, 'data', generate_random_str(24)+".jpg")
f.save(upload_path)
time0=time.time()
print(upload_path)
lock.acquire()
result = ''
try:
result = PredictDogCat.predict(model, upload_path)
except Exception as e:
print("Unexpected Error: {}".format(e))
stus['info']=''.format(e)
stus['code']=1
lock.release()
time1 = time.time()
# print result
print("cost time: ",time1 - time0)
stus['info'] = result
rz = json.dumps(stus)
return rz
if __name__ == "__main__":
app.run(host='0.0.0.0', port=2688)
curl访问验证
curl -F "imagefile=@/home/lxj/Data/mnt-docker/Projects/DogAndcat/dog.jpg" http://127.0.0.1:2688/cv/dogcat/v1/recognize
{"code": 0, "info": "dog"}
注意:上传图片文件一定要加上@
Flask实现下载
send_file方式
flask.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False, last_modified=None)
注意:Please never pass filenames to this function from user sources;
you should use send_from_directory() instead.
例如:download.py
@app.route("/api/v1/download/<path:filepath>")
def DownloadFile (filepath = None):
if filepath is None:
print('path is null')
try:
print(filepath)
return send_file(filepath, as_attachment=True)
except Exception as e:
print(e)
注意:filepath对应的路径为相对路径,相对于download.py所在目录
send_from_directory方式
flask.send_from_directory(directory, filename, **options)例如:
@app.route('/api/v1/download/<path:filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename, as_attachment=True)
curl下载文件验证
对download.py服务的验证如下:
curl -O http://ip:10000/api/v1/download/./results/denghui/HvR5ThUWxFLdMgnjslRlvTNh/test_HvR5ThUWxFLdMgnjslRlvTNh.mp4
文件路径为:./results/denghui/HvR5ThUWxFLdMgnjslRlvTNh/test_HvR5ThUWxFLdMgnjslRlvTNh.mp4
Flask动态url
Flask中动态url设置采用<datatype:name>
,其中支持的类型有:
例如:
/api/v1/download/<path:filepath>
参考
https://flask.palletsprojects.com/en/0.12.x/api/#flask.send_file
https://flask.palletsprojects.com/en/0.12.x/api/#url-route-registrations
https://www.cnblogs.com/hujiapeng/p/8470099.html