python3实现通过接口上传图片到服务端,并返回图片地址且入库

1.需要python3的环境
2.源码
main.py:

# coding:utf8
# oss上传工具类
import os
import requests
import tool_db
import time

url = "http://127.0.0.1:8080/user/image/uploadImage"

if __name__ == '__main__':
    # 路径
    path = r'C:\image\收入'
    # 排序字段,不用管
    pid_weight = 4000

    # 入库sql
    insert_sql = "INSERT INTO `bill_categ` (`name`, `icon`, `weight`, `state`, `created_at`,`updated_at`,`flow_type`) VALUES (%s, %s, %s, 1, %s, %s, 1);"
    insert_list = []
    # 遍历文件夹读取文件
    filenames = os.listdir(path)
    i = 1
    for filename in filenames:
        if filename.find(".png") < 1:
            # 剔除掉非图片文件
            continue
        # 文件路径
        filepath = path + "\\" + filename
        # 读取分类名称
        category_name = filename.split("@")[0].split(".")[0]
        print(category_name, filepath)

        file_data = {
            'file': (filename, open(filepath, 'rb'), 'application/octet-stream')
        }
        header = {
            "t": "123",
            "u": "123"
        }

        res = requests.request(url=url, headers=header, files=file_data, method="post")
        print(res.text)
        content = res.json()
        icon_url = content["data"]

       time = int(time.mktime(time.localtime(time.time())))
        insert_list.append([
            category_name, icon_url, pid_weight - i, time, time
        ])

        i += 1

    tool_db.update_batch_by_custom_sql(insert_sql, insert_list)

tool_db.py

# -*- coding: utf-8 -*-
# 数据库链接工具类
import pymysql
import time

from dbutils.pooled_db import PooledDB

host = '127.0.0.1'
port = 3306
password = '******'
database = 'user'
user = 'root'
use_unicode = 1
charset = 'utf8'
updated_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


def init_connect():
    # 打开数据库连接
    pool = PooledDB(pymysql, 5, host=host, port=port, user=user, passwd=password, db=database, use_unicode=use_unicode,
                    charset=charset)
    return pool.connection()


# 连接数据库
conn = init_connect()
cursor = conn.cursor()


def get_by_custom_sql(sql):
    cursor.execute(sql)
    rows = cursor.fetchall()
    return rows


def get_by_custom_sql_one(sql):
    cursor.execute(sql)
    row = cursor.fetchone()
    return row


def update_by_custom_sql(sql):
    cursor.execute(sql, )
    conn.commit()


def update_batch_by_custom_sql(sql, update_list):
    cursor.executemany(sql, update_list)
    conn.commit()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

容若只如初见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值