def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
# CV2
#img_np = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_UNCHANGED) # cv2.IMREAD_COLOR in OpenCV 3.1
img_np = cv2.imread(os.path.join(app.config['UPLOAD_FOLDER'], filename), -1)
cv2.imshow("Image", img_np)
return redirect(url_for('uploaded_file',
filename=filename))
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
python类files()的实例源码
def content_item_resource_upload(id,property):
#print(request.headers['Content-Type'])
#print(request.files)
file = request.files['file']
#print(file.filename)
#print(file.content_type)
#print(file.content_length)
uploadContentType = file.content_type
if file.content_type.startswith("text/") and file.content_type.find("charset=")<0:
uploadContentType = file.content_type+"; charset=UTF-8"
uploadDir = app.config['UPLOAD_STAGING'] if 'UPLOAD_STAGING' in app.config else 'tmp'
os.makedirs(uploadDir,exist_ok=True)
staged = os.path.join(uploadDir, file.filename)
file.save(staged)
status = 500
responseJSON = None
contentType = None
with open(staged,"rb") as data:
status,responseJSON,contentType = model.uploadContentResource(id,property,file.filename,uploadContentType,os.path.getsize(staged),data)
os.unlink(staged)
if status==200 or status==201:
return Response(stream_with_context(responseJSON),status=status,content_type = contentType)
else:
return Response(status=status)
def block(self):
"""
block is a decorator function that wraps around the route and does all the crazy stuff
"""
def decorator(func):
@wraps(func)
def wrapped():
if request.method == 'POST' or request.method == 'PUT':
result = True
result2 = True
if request.form:
result2 = self.collect_urls(request.form.values())
if request.files:
result = self.test_files_against_api(
request.files.values())
elif request.json:
result = self.test_base64_data(request.json.values())
result2 = self.collect_urls(request.json.values())
if not result or not result2:
return jsonify({"response": "seems like the request contains the" \
+ " images that contains NSFW content."}), 403
return func()
return wrapped
return decorator
def predict():
logger.info('/predict, hostname: ' + str(socket.gethostname()))
if 'image' not in request.files:
logger.info('Missing image parameter')
return Response('Missing image parameter', 400)
# Write image to disk
with open('request.png', 'wb') as f:
f.write(request.files['image'].read())
img = cv2.imread('request.png', 0)
img = np.resize(img, (28, 28, 1))
''' Return value will be None if model not running on host '''
prediction = mnist_client.predict(np.array([img]))
logger.info('Prediction of length: ' + str(len(prediction)))
''' Convert the dict to json and return response '''
return jsonify(
prediction=prediction,
prediction_length=len(prediction),
hostname=str(socket.gethostname())
)
mnist_mock_client_example.py 文件源码
项目:tfserving_predict_client
作者: epigramai
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def predict():
logger.info('/predict, hostname: ' + str(socket.gethostname()))
if 'image' not in request.files:
logger.info('Missing image parameter')
return Response('Missing image parameter', 400)
# Write image to disk
with open('request.png', 'wb') as f:
f.write(request.files['image'].read())
img = cv2.imread('request.png', 0)
img = np.resize(img, (28, 28, 1))
prediction = mnist_client.predict(np.array([img]))
logger.info('Prediction of length:' + str(len(prediction)))
''' Convert the dict to json and return response '''
return jsonify(
prediction=prediction,
prediction_length=len(prediction),
hostname=str(socket.gethostname())
)
def pcap_get(task_id):
task = Task.query.get(task_id)
if not task:
return json_error(404, "Task not found")
if task.status == Task.DELETED:
return json_error(404, "Task files has been deleted")
if task.status != Task.FINISHED:
return json_error(420, "Task not finished yet")
pcap_path = os.path.join(settings.reports_directory,
"%s" % task_id, "dump.pcap")
if not os.path.isfile(pcap_path):
return json_error(404, "Pcap file not found")
return send_file(pcap_path)
def memorydumps_list(task_id):
folder_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(task_id), "memory")
if os.path.exists(folder_path):
memory_files = []
memory_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(task_id), "memory")
for subdir, dirs, files in os.walk(memory_path):
for filename in files:
memory_files.append(filename.replace(".dmp", ""))
if len(memory_files) == 0:
return json_error(404, "Memory dump not found")
return jsonify({"dump_files": memory_files})
else:
return json_error(404, "Memory dump not found")
def FUN_upload_image():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
return(redirect(url_for("FUN_root")))
file = request.files['file']
# if user does not select file, browser also submit a empty part without filename
if file.filename == '':
return(redirect(url_for("FUN_root")))
if file and allowed_file(file.filename):
filename = os.path.join("static/img_pool", hashlib.sha256(str(datetime.datetime.now())).hexdigest() + secure_filename(file.filename).lower())
file.save(filename)
prediction_result = mx_predict(filename, local=True)
FUN_resize_img(filename)
return render_template("index.html", img_src = filename, prediction_result = prediction_result)
return(redirect(url_for("FUN_root")))
################################################
# Start the service
################################################
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename, ALLOWED_EXTENSIONS):
filename = secure_filename(file.filename)
file_location = os.path.join(app.config['UPLOAD_FOLDER'], filename)
print "file location", file_location
file.save(file_location)
saved_file = url_for('uploaded_file', filename=filename)
endpoint_name = os.path.splitext(filename)[0]
database = request.form.get("database")
if not database:
print request.form["database"]
raise InvalidUsage("Database name was not provided", 400, '{ "error" : "database was not provided" }')
else:
handle_file(database, file_location, endpoint_name, host)
return redirect('/loxo/' + database + '/collections/' + endpoint_name)
return render_template('upload.html')
def _get_sql(data, files=None):
sql = None
if files is not None and 'datafile' in files:
raw = files['datafile'].read()
try:
sql = raw.decode('utf-8')
except UnicodeDecodeError, err:
logging.error(err)
logging.debug(repr(raw))
sql = (u'-- UnicodeDecodeError: %s\n'
u'-- Please make sure to upload UTF-8 encoded data for now.\n'
u'-- If you want to help improving this part of the application\n'
u'-- please file a bug with some demo data at:\n'
u'-- http://code.google.com/p/python-sqlparse/issues/entry\n'
u'-- Thanks!\n' % err)
if not sql:
sql = data.get('data')
return sql or ''
def upload():
#pprint.pprint(request.files)
# check if the post request has the file part
if 'file' not in request.files:
#print("not file")
return redirect("/")
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
return redirect("/")
filename = secure_filename(file.filename)
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(path)
FLAGS.input_files = path
# inference
result = main(None)
#print(result)
return jsonify(result)
def get(self, instance_id):
if not self.is_exist(instance_id):
abort(404)
if not self.is_allowed(instance_id):
abort(403)
folder_path = thumbnail_utils.get_preview_folder_name(
self.subfolder,
instance_id
)
file_name = thumbnail_utils.get_file_name(instance_id)
# Use legacy folder name if the file cannot be found.
if not os.path.exists(os.path.join(folder_path, file_name)):
folder_path = thumbnail_utils.get_folder_name("preview-files")
return send_from_directory(
directory=folder_path,
filename=file_name
)
def post(self, instance_id):
if not self.is_exist(instance_id):
abort(404)
self.check_permissions(instance_id)
uploaded_file = request.files["file"]
thumbnail_utils.save_file(
self.data_type,
instance_id,
uploaded_file,
size=self.size
)
thumbnail_url_path = \
thumbnail_utils.url_path(
self.data_type,
instance_id
)
return {"thumbnail_path": thumbnail_url_path}, 201
def post(self):
uploaded_file = request.files["file"]
file_name = "%s.csv" % uuid.uuid4()
file_path = os.path.join(app.config["TMP_DIR"], file_name)
uploaded_file.save(file_path)
result = []
try:
self.check_permissions()
self.prepare_import()
with open(file_path) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
result.append(self.import_row(row))
return fields.serialize_models(result), 201
except KeyError as e:
return {"error": "A column is missing: %s" % e}, 400
except permissions.PermissionDenied:
abort(403)
def addTileset(gameID):
'''
Create a tileset
'''
file = request.files['file']
if file.filename == '':
flash('No file selected')
elif not file.filename.endswith('.png'):
flash('Upload failed: file type must be .png')
else:
directory = GamesList.getByID(gameID).getTileDir()
destination = os.path.join(directory, file.filename)
file.save(destination)
return redirect(url_for('GAMES_PATH_BLUEPRINT.editGame',
gameID=gameID))
def addProp(gameID):
'''
Upload a prop image
'''
file = request.files['file']
if file.filename == '':
flash('No file selected')
elif not file.filename.endswith('.png'):
flash('Upload failed: file type must be .png')
else:
directory = GamesList.getByID(gameID).getPropDir()
destination = os.path.join(directory, file.filename)
file.save(destination)
flash('Prop added successfully')
return redirect(url_for('GAMES_PATH_BLUEPRINT.editGame',
gameID=gameID))
def data(command):
def handle_file():
f_name = request.args.get('file_name')
path = app.config['UPLOAD_FOLDER']
if not f_name:
path, f_name = os.path.split(app._cr.csv_file)
return path, f_name
def _set_data_file(path, f_name):
_file = os.path.join(path, f_name)
app._cr.csv_file = _file
app._ar.csv_file = _file
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
if request.method == 'GET':
if command == 'set':
path, f_name = handle_file()
_set_data_file(path, f_name)
return 'data file set to %s\n' % f_name
elif command == 'download':
path, f_name = handle_file()
return send_from_directory(path, f_name, as_attachment=True)
elif command == 'upload':
return render_template('upload_file.html')
elif command == 'list':
files = os.listdir(app.config['UPLOAD_FOLDER'])
files = [f for f in files if allowed_file(f)]
return render_template('file_list.html', file_list=files)
if request.method == 'POST':
file = request.files['data_file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "File Saved!\n"
def ckupload():
#site_info = site_get()
"""CKEditor file upload"""
error = ''
url = ''
callback = request.args.get("CKEditorFuncNum")
if request.method == 'POST' and 'upload' in request.files:
fileobj = request.files['upload']
fname, fext = os.path.splitext(fileobj.filename)
rnd_name = '%s%s' % (gen_rnd_filename(), fext)
filepath = os.path.join(app.static_folder, 'upload', rnd_name)
# ???????????????
dirname = os.path.dirname(filepath)
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
error = 'ERROR_CREATE_DIR'
elif not os.access(dirname, os.W_OK):
error = 'ERROR_DIR_NOT_WRITEABLE'
if not error:
fileobj.save(filepath)
url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
else:
error = 'post error'
#print callback
res = """<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>""" % (callback, url, error)
response = make_response(res)
response.headers["Content-Type"] = "text/html"
return response
def _post_args(self): # pylint: disable=no-self-use
# pylint: disable=maybe-no-member
""" Return action and args after parsing request """
data = request.json if request.json else {}
params = api_utils.change_to_str_in_dict(data)
action = params.get('action', request.form.get('action', ''))
args = params.get('args', {})
try:
args['file'] = request.files['file']
except KeyError:
pass
LOGGER.debug('Input args are: action: %s, args: %s', action, args)
return action, args