python实现上传文件夹中图片,并连接数据库update历史数据

最近遇到个需求,上传到移动方的资源3天过期,

但没有提供更新接口,需要全部资源重新上传替换

3天重复一次 ,工作量太大,于是乎开始思考,过期的只是移动方的资源URL,那我上传一遍替换原来的资源URL,那后续步骤就不用操作,减少一大部分工作量

我们先要实现的是一次上传文件夹中图片

import os,sys
import requests

path=r"C:\Users\Lenovo\Desktop\XXXXX"
    # 设置文件夹路径
dirs=os.listdir(path)
# 用于返回指定的文件夹包含的文件或文件夹的名字的列表

for file in dirs:
    # 在文件夹中循环取值file
    url='http://xx.xx.xx.xx:9900/api-xx-center/xx/xx'
# 接口地址

    data={
            'appId':9,
            'type':4,
            'file':'文件'
            }
# 请求参数

    fpath=os.path.join(path,file)  
# 拼接图片地址及文件名     
    files = {"file": open(fpath, "rb")}
# 获取文件
    headers={'AUTH_MERCHANTS_ID': '367',
    'Authorization': 'Bearer 98ccf6b7-ca07-42d3-b5fd-b7bd638fc5b3'} 
# 设置请求头,通常只需要token 
    r=requests.post(url=url,params=data, headers=headers,files=files)
# 调用requests 的post方式上传 可以print看看

确定实现文件上传实现成功后,需要实现连接数据库,取得最新上传的数据 去替换原来的数据

import pymysql


db=pymysql.connect(
        host='xx.xx.xx.xx',
        port=3306,
        user='root',
        passwd='xxxx',
        db='xxxxx'
)
#   以上xx都需要根据真实内容替换
cur=db.cursor()
try:
        cur.execute("SELECT * FROM `xxx` where xx=367 and xx=9 order by id desc")
#   查询最新数据
        a=cur.fetchall()
        b=a[0][4]
        c=a[0][10]
#   获取需要的值
        cur.execute("update xx  set xx='{}' where resource_name='{}'".format(b,c))
        db.commit()
#   更新后提交
except Exception as e:
        print('错误:{}'.format(str(e)))


db.rollback()

以上分布式均实现后,要做的就是整合

import os,sys
import requests
import pymysql

db=pymysql.connect(
        host='xx.xx.xx.xx',
        port=3306,
        user='root',
        passwd='xxx',
        db='xxxx'
)
cur=db.cursor()
path=r"C:\Users\Lenovo\Desktop\xx"
dirs=os.listdir(path)

for file in dirs:
   
       url='http://xx.xx.xx.xx:9900/api-xx-center/xx/xx'
# 接口地址

    data={
            'appId':9,
            'type':4,
            'file':'文件'
            }
    fpath=os.path.join(path,file)       
    files = {"file": open(fpath, "rb")}

 
    headers={'xx': '367',
    'Authorization': 'Bearer 98ccf6b7-ca07-42d3-b5fd-b7bd638fc5b3'}  
    r=requests.post(url=url,params=data, headers=headers,files=files)

    try:
            cur.execute("SELECT * FROM `xx` where xx=367 and app_id=9 order by id desc")
            a=cur.fetchall()
            b=a[0][4]
            c=a[0][10]
            cur.execute("update xxx set xx='{}' where resource_name='{}'".format(b,c))
            db.commit()
    except Exception as e:
            print('错误:{}'.format(str(e)))
            db.rollback()

db.close()

准备好素材上传即可

结果入下 用最新的数据替换原来的所有符合条件的历史数据

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值