flask与curl访问验证

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值