需求:

  后端不断产生新的图片数据,发送给前端,前端然后显示。

方案:

  1.后端可以生成一个图片URL地址,然后返回给前端【采用】
  2.或者返回base64

疑问:

  将图片文件夹放在nginx里面就会生成图片的URL地址吗????

  如何将图片的URL地址保存到数据库呢???

  怎么和数据库对应上呢???

  

 

步骤:

 

import os
import time
import pymysql

# 配置MySQL数据库连接信息
db = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    database='mydb',
    charset='utf8mb4'
)

# 配置Nginx服务器中保存图片的目录
image_dir = '/var/www/static/images'

# 定义函数,将新上传的图片信息保存到MySQL数据库中
def save_image_to_db(image_path):
    with db.cursor() as cursor:
        # 生成图片URL地址
        image_url = f'http://localhost/images/{os.path.basename(image_path)}'
        # 将图片URL地址和文件路径保存到MySQL数据库中
        sql = 'INSERT INTO images (url, path) VALUES (%s, %s)'
        cursor.execute(sql, (image_url, image_path))
    db.commit()

# 定义函数,监控指定目录下的文件变化
def watch_dir(dir_path):
    # 获取目录下当前的所有文件
    current_files = set(os.listdir(dir_path))
    while True:
        # 获取目录下当前的所有文件
        current_files = set(os.listdir(dir_path))
        # 暂停一段时间
        time.sleep(1)
        # 获取目录下最新的文件
        new_files = set(os.listdir(dir_path)) - current_files
        # 如果有新文件上传,将其保存到MySQL数据库中
        for file_name in new_files:
            if file_name.endswith('.jpg') or file_name.endswith('.png'):
                file_path = os.path.join(dir_path, file_name)
                save_image_to_db(file_path)

if __name__ == '__main__':
    # 启动监控指定目录的程序
    watch_dir(image_dir)

 

 

from flask import Flask, jsonify
import pymysql

app = Flask(__name__)

# 连接mysql数据库
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    db='example_db',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

# 查询所有图片URL并返回给前端
@app.route('/images')
def get_images():
    with conn.cursor() as cursor:
        cursor.execute('SELECT url FROM images')
        urls = [row['url'] for row in cursor.fetchall()]
    return jsonify(urls)

# 关闭数据库连接
@app.teardown_appcontext
def close_db(error):
    conn.close()

  

posted on 2023-01-25 00:12  黑逍逍  阅读(752)  评论(0编辑  收藏  举报