flask部署

一、flask目录结构图

 flask必须包含,static和templates文件夹,分别用于存放静态数据和HTML网页模板。

二、HTML代码

<!DOCTYPE html>
<html lang="zh">
<head >
     <meta http-equiv="Content-Type" content="text/html; charset="UTF-8">
     <title>Title</title>
</head>
<body>
    <h1>upload</h1>
    <!--表单form
    action: 表单提交的位置,可以是网站,也可以是一个请求处理地址。
    method: post,get 提交方式
    get方式提交:我们可以在url中看到提交的信息,高效但不安全
    post方式提交:我们不可以在url中看到提交的信息,比较安全,可以传输大文件
    -->
    <form action="" enctype='multipart/form-data' method="POST">  <!-- form建立一个表单,表单会发送一个request.post的请求 -->
        选择上传的图片: <input type="file" name="file"><br>
        点击提交按钮: <input type="submit" value="submit"><br>
    </form>
    <div>
        <!--表单form
        {{received_img_path}}:用于存储flask中返回的变量值,用{{变量名}}表示
        -->
        <p>原始图片<p><img src="{{received_img_path}}" id="image_1" width="1024" height="512"/>
    </div>
    <div>
        <p>检测结果图片<p><img src="{{drawed_img_path}}" id="image_2" width="1024" height="512"/>
    </div>
</body>
</html>

 三、flask代码

# coding:utf-8
import cv2
from flask import Flask,render_template,request,redirect,url_for
from werkzeug.utils import secure_filename
import os
from tools.predictinfer import ocr_pre
from flask import jsonify
import base64
import numpy as np

# 实例化Flask对象
app = Flask(__name__)
# 文件上传目录
app.config['UPLOAD_FOLDER'] = './receivedimg'
# 支持的文件格式
app.config['ALLOWED_EXTENSIONS'] = {'png','PNG','jpg','JPG','webp','jpeg','JPEG'}  # 集合类型
app.config["JSON_AS_ASCII"] = False
# 设置开启web服务后,如果更新html文件,可以使更新立即生效
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

# 根据图片文件路径获取base64编码后内容
def get_imageBase64String(imageFilePath):
    if not os.path.exists(imageFilePath):
        image_base64_string = ''
    else:
        with open(imageFilePath, 'rb') as file:
            image_bytes = file.read()
        image_base64_bytes = base64.b64encode(image_bytes)
        image_base64_string = image_base64_bytes.decode('utf-8')
    return image_base64_string

# @app.route('/', methods=['GET', 'POST'])   # index只是加载这个HTML网页,一个网页中有多个form,每个form的请求方法可以不同,form的请求方式通过method设定,form链接的函数是通过action设定。
# def index():
#     return render_template('upload.html')
@app.route('/', methods=['GET', 'POST'])    # 定义一个路由,用于接收html页面的表单发出的request请求。
def upload():
    if request.method == 'POST':
        f = request.files['file']          # 'file'必须和HTML页面中的【选择上传的图片: <input type="file" name="file">】的name相同。用于获取客户端上传的内容。
        if allowed_file(f.filename):
            # basepath = os.path.dirname(__file__)  # 当前文件所在路径
            received_img_path = 'static/receivcedimg'  #  注意此处保存的图片必须保存在名为static的文件夹下。
            received_img_path = os.path.join(received_img_path,f.filename)  # secure_filename(f.filename)是保证文件名符合规范,自动去掉中文字符
            f.save(received_img_path)  #将客户端上传的图片保存到服务器,用于后面的模型调用
            print('接收图片文件保存到此路径:%s' % received_img_path)
            result = ocr_pre(received_img_path) # 调用模型预测之后的结果:The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable.
            # 将检测的图片保存在服务器文件夹下,后面展示在页面上需要调用
            drawed_img_path = 'static/drawedimg'  #  注意此处保存的图片必须保存在名为static的文件夹下。
            drawed_img_path = os.path.join(drawed_img_path, 'drawed_' + f.filename)
            drawed_img = result[0]
            cv2.imencode('.jpg', drawed_img)[1].tofile(drawed_img_path)  # OpenCV使用imencode对图片编码,可以保存在中文路径下。
            print(received_img_path,'\n',drawed_img_path)
            return render_template('upload.html',
                                   received_img_path=received_img_path,
                                   drawed_img_path=drawed_img_path
                                   )                              #将需要返回的结果返回给upload.html这个网页
            # return jsonify(imageBase64String = imageBase64String)
        else:
            return '输入图片格式有误,仅支持[png,jpgjpeg,webp,JPEG,jpeg]类型图片'
    else:
        return render_template('upload.html')
    # return render_template('upload.html')   #  render_template函数用于将flask产生的  IP:port 的地址与upload.html网页关联。使用render_template时,必须将upload.html放在templates文件夹下。

@app.route('/testjson', methods=['POST', 'GET'])  # 定义一个路由,这个路由关联的函数是下面的testjson函数,访问的链接是 IP:port/testjson
def testjson():
    #return '返回json'
    return jsonify(name='zhangsan',age=22)

if __name__ == '__main__':
    # 发送请求前先测试下ocr_pre这个函数是否正常运行。
    result = ocr_pre('../test/input/IMG_3648.JPG')
    if result is not None:
        print('模型函数测试正常')
    # 运行flask程序生成ip和port
    app.run(debug=True)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值