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

  • 在全部网口上创建web服务, 监听8080端口
  • 关闭debug模式
  • GET时返回HTML界面, 用于提交文件
  • POST到 /upload 时, 从接收的 file 变量中读取文件, 并传递给 opencv 解析为 image 对象
python 复制代码
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'}

# 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 data
            filestr = file.read()
            #convert string data to numpy array
            file_bytes = numpy.frombuffer(filestr, numpy.uint8)
            # convert numpy array to image
            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__':
    # Start the Flask server on port 8080
    app.run(debug=False, host='0.0.0.0', port=8080)

如果要保存文件

python 复制代码
filename = os.path.join(PYHSICAL_PATH, file.filename)
file.save(filename)
相关推荐
winfredzhang2 天前
从零实现“照片按地理位置显示在矢量地图上”:Flask + SQLite + Leaflet 全栈实战
python·sqlite·flask
龙腾AI白云4 天前
数字孪生、具身智能、世界模型三者交叉
数据库·人工智能·机器学习·flask·pygame
hhb_6185 天前
Flask+SQLite实现用户管理接口
python·sqlite·flask
QQ14220784497 天前
基于 Flask 的「自动任务控制台」设计与踩坑实录
后端·python·flask
深圳市尚想信息技术有限公司7 天前
TM52F1376海速芯HITENX Flash-8位MCU单片机,多通道ADC + 段码显示一体化主控芯片
单片机·嵌入式硬件·mcu·flask·芯片·控制器
高级程序源8 天前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计
高级程序源8 天前
SSM仓储管理系统31582-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·flask·课程设计
高级程序源9 天前
springboot本地生活服务平台33399-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·小程序·flask·课程设计
高级程序源9 天前
django房屋租赁系统28636-计算机课程设计、毕业设计
python·mysql·elasticsearch·小程序·django·flask·课程设计
fanjiu20209 天前
flask接收消息
python·flask