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)
相关推荐
文军的烹饪实验室8 小时前
使用 Flask 构建流式返回服务
后端·python·flask
.Net Core 爱好者1 天前
基于Flask搭建AI应用,本地私有化部署开源大语言模型
人工智能·后端·python·语言模型·自然语言处理·flask
迪小莫学AI1 天前
【11天从零基础入门flask】第 7 章 表单
后端·python·flask
m0_663234011 天前
flask后端开发(8):Flask连接MySQL数据库+ORM增删改查
数据库·mysql·flask
Channing Lewis1 天前
flask如何进行测试
后端·python·flask
xinzheng新政2 天前
Flask
后端·python·flask
K-D小昊3 天前
AWS云设施攻击
安全·flask·云计算·aws
码界筑梦坊3 天前
基于Flask的当当网畅销图书榜单可视化分析系统的设计与实现
后端·python·flask·毕业设计
Channing Lewis3 天前
flask开发的网站,后端服务关闭后,可以找回之前的数据的吗
python·flask