需求:
后端不断产生新的图片数据,发送给前端,前端然后显示。
方案:
1.后端可以生成一个图片URL地址,然后返回给前端【采用】
2.或者返回base64
疑问:
将图片文件夹放在nginx里面就会生成图片的URL地址吗????
如何将图片的URL地址保存到数据库呢???
怎么和数据库对应上呢???
步骤:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!