欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Python基于 Flask 创建简单Web服务并接收文件

Python基于 Flask 创建简单Web服务并接收文件

2025/2/13 15:37:27 来源:https://blog.csdn.net/michaelchain/article/details/145576450  浏览:    关键词:Python基于 Flask 创建简单Web服务并接收文件
  • 在全部网口上创建web服务, 监听8080端口
  • 关闭debug模式
  • GET时返回HTML界面, 用于提交文件
  • POST到 /upload 时, 从接收的 file 变量中读取文件, 并传递给 opencv 解析为 image 对象
from flask import Flask, request, redirect, url_for
import os
import cv2
import numpy
import jsonapp = Flask(__name__)app.config['ALLOWED_EXTENSIONS'] = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}# Function to check if the file has an allowed extension
def allowed_file(filename):return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']@app.route('/')
def index():return '''<html><body><h1>Service is Ready</h1><p></p><form method="POST" action="/upload" enctype="multipart/form-data">Function: <input type="text" name="func"> File: <input type="file" name="file"> <input type="submit" value="Process"></form></body></html>'''@app.route('/upload', methods=['POST'])
def upload_file():if 'file' not in request.files:return 'No file part'file = request.files['file']if file.filename == '':return 'No selected file'if file and allowed_file(file.filename):result = {}try:#read image file string datafilestr = file.read()#convert string data to numpy arrayfile_bytes = numpy.frombuffer(filestr, numpy.uint8)# convert numpy array to imageimg = cv2.imdecode(file_bytes, cv2.IMREAD_UNCHANGED)height, width = img.shape[:2]result = {"code": 0,"message": "succ","data": {"size": file_bytes.size,"height": height,"width": width}}except:print("Error occurred")result = {"code": 1,"message": "error","data": None}passreturn json.dumps(result)else:return 'Invalid file format'if __name__ == '__main__':# Start the Flask server on port 8080app.run(debug=False, host='0.0.0.0', port=8080)

如果要保存文件

filename = os.path.join(PYHSICAL_PATH, file.filename)
file.save(filename)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com