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)
相关推荐
moxiaoran57532 天前
Flask学习笔记(一)
后端·python·flask
yzx9910132 天前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame
带娃的IT创业者3 天前
《Python Web部署应知应会》No3:Flask网站的性能优化和实时监测深度实战
前端·python·flask
0_0梅伊阁诗人3 天前
Flask
开发语言·数据库·python·flask
程序员的世界你不懂3 天前
【Flask】实现一个前后端一体的项目-脚手架
后端·python·flask
安岁的笔记本4 天前
Flask/Django 生产部署:Gunicorn vs Nginx,Windows 与 Linux 实战指引
django·flask·gunicorn
Q_Q19632884755 天前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php
Q_Q5110082855 天前
springboot+python+uniapp基于微信小程序的旅游服务系统景点信息展示 路线推荐 在线预约 评论互动系统
spring boot·python·微信小程序·django·flask·uni-app
EvanSun__6 天前
Flask 框架引入
后端·python·flask
神仙别闹6 天前
基于 Python + redis + flask 的在线聊天室
redis·python·flask