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()

你可能感兴趣的:(MySQL,python,数据库,sql)