How does Python upload files?

scene description

In work, it is often necessary to upload some files to the server for convenient use and management, such as uploading files to Tencent Cloud's Object Storage (COS). So how to use Python to implement file upload?

Option One

import requests


class Upload:
    def __init__(self):
        """
        基础配置
        """
        # 请求头
        self.headers = {
    
    
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
        }
        # 上传链接
        self.upload_url = 'https://api.test.cn/upload'  # POST方法

    def upload(self):
        """
        上传文件
        """
        data = {
    
    
            'bucketName': 'test',
            'objectName': '测试附件.xlsx',
            'fileDownloadName': '测试附件.xlsx',
        }
        files = {
    
    
            'file': open('测试文件.xls', 'rb')
        }
        res = requests.post(url=self.upload_url, headers=self.headers, data=data, files=files)
        print(res.json())


if __name__ == '__main__':
    upload = Upload()
    upload.upload()

Option II

import os
import sys

import pymysql
import requests
import you_get


class Upload:
    def __init__(self):
        """
        基础配置
        """
        # 请求头
        self.headers = {
    
    
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
        }
        # 上传链接
        self.upload_url = 'https://api.test.cn/upload'  # POST方法

    def update_data(self):
        """
        更新数据,补全数据库中视频对应的oss链接
        """
        connection = pymysql.connect(
            host='host',
            user='user',
            password='password',
            database='db',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )
        with connection:
            with connection.cursor() as cursor:
                # 获取所有数据
                cursor.execute('select id, video_title, video_url, video_oss  from video_bilibili;')
                for item in cursor.fetchall():
                    if not item.get('video_oss'):
                        print('*' * 60)
                        # 下载视频
                        print(item.get('video_title'))
                        self.download(item.get('video_url'), item.get('video_title'))
                        # 上传视频
                        if video_oss := self.upload(item.get('video_title')):
                            # 编辑SQL语句
                            sql = f"update video_bilibili set video_oss='{video_oss}' where id={item.get('id')};"
                            # 执行SQL语句,更新数据
                            try:
                                cursor.execute(sql)
                                connection.commit()
                            except Exception as e:
                                print(e)
                                print(item)

    def download(self, url, filename):
        """
        下载视频
        """
        sys.argv = ['you-get', '-O', filename, url]
        you_get.main()

    def upload(self, title):
        """
        上传文件
        """
        files = [
            ('files', (
                f'{title}.mp4',  # 文件名称
                open(f'{title}.mp4', 'rb'),  # 读取文件
                'application/octet-stream'
            ))
        ]
        # 上传文件
        response = requests.post(url=self.upload_url, headers=self.headers, files=files)
        if response.json().get('code') == 200:
            video_oss = response.json().get('data')[0].get('urlPath')
            # 删除已下载的数据
            for file in os.listdir():
                if os.path.splitext(file)[1] == '.mp4' or os.path.splitext(file)[1] == '.xml':
                    os.remove(file)
            # 返回oss链接
            return video_oss


if __name__ == '__main__':
    upload = Upload()
    # upload.upload('上传测试文件')
    upload.update_data()

Description: This process uses requests to simulate the process of uploading files using form-data in Postman. Process: first use you-get to download the video according to the third-party
video link stored in the database , and then use the upload method to upload the video to oss, then the oss link will be obtained, and finally the obtained oss ​​link will be updated to the corresponding in the database. Note: The specific operation depends on the actual situation, here only provides ideas.

reference link

Guess you like

Origin blog.csdn.net/qq_34562959/article/details/121557700