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)
相关推荐
千里码aicood11 小时前
Flask-基于图神经网络的谣言检测研究
人工智能·神经网络·flask
烂蜻蜓18 小时前
Flask入门教程(三十一):实用函数与类API——全局工具函数速查
后端·python·flask
千里码aicood19 小时前
flask-基于注意力机制的异常流量检测与自动防御系统
后端·python·flask
2601_9622838820 小时前
Python 开发框架:Django、Flask和FastAPI
python·django·flask·fastapi·web开发
Looooking21 小时前
Python 之 Flask 的全局变量 g
后端·python·flask
Dream-Y.ocean2 天前
基于具身交互智能数字人,我用Flask搭了一个AI教学平台:课代表AI全流程实战
人工智能·flask·交互
零域码客2 天前
一文掌握 jQuery + Flask 全栈核心知识点(前端交互 + 后端接口 + 前后端联调)
前端·python·ajax·flask·jquery·前后端联调·web全栈
minhuan2 天前
基于Playwright数据采集,大模型对接Flask+SQLite,平滑升级向量库与分布式微服务26.5
人工智能·flask·大模型应用·大模型业务集成·微服务架构演进
千里码aicood3 天前
flask基于opencv绘图机器人的系统设定(opencv)
opencv·机器人·flask
应用市场3 天前
GPT vs Claude 深度对比(2026年9月):从模型特性到编程实战,开发者该怎么选
python·gpt·flask