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)
相关推荐
百锦再6 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082856 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_19632884756 天前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask
计算机专业码农一枚6 天前
Python-flask框架基于推荐算法的在线课程推荐系统设计与实现-Pycharm django
python·flask·推荐算法
NGINX开源社区7 天前
使用 Microsoft Entra ID 配置 NGINX Plus 以实现 SAML SSO
后端·python·flask
山岚的运维笔记8 天前
SQL Server笔记 -- 第86章:查询存储
笔记·python·sql·microsoft·sqlserver·flask
先做个垃圾出来………9 天前
Django vs Flask 异步视图性能对比:数据驱动的深度分析
数据库·django·flask
迪巴拉15259 天前
基于Yolov8训练的Flask后端和Uniapp野生菌识别系统
yolo·flask·uni-app
麦麦大数据9 天前
M004_基于Langchain+RAG的银行智能客服系统设计与开发
typescript·langchain·flask·vue3·faiss·rag
夜瞬10 天前
【Flask 框架学习】01:编写第一个 Flask 应用
后端·python·学习·flask