- 在全部网口上创建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 json |
| |
| app = Flask(__name__) |
| |
| app.config['ALLOWED_EXTENSIONS'] = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} |
| |
| |
| 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: |
| |
| filestr = file.read() |
| |
| file_bytes = numpy.frombuffer(filestr, numpy.uint8) |
| |
| img = 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 |
| } |
| pass |
| return json.dumps(result) |
| else: |
| return 'Invalid file format' |
| |
| if __name__ == '__main__': |
| |
| app.run(debug=False, host='0.0.0.0', port=8080) |
如果要保存文件
| filename = os.path.join(PYHSICAL_PATH, file.filename) |
| file.save(filename) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· 【全网最全教程】使用最强DeepSeekR1+联网的火山引擎,没有生成长度限制,DeepSeek本体
2023-02-11 普冉PY32系列(五) 使用JLink RTT代替串口输出日志
2023-02-11 普冉PY32系列(四) PY32F002A/003/030的时钟设置
2020-02-11 LFTP命令笔记