Python はどのようにファイルをアップロードするのでしょうか?

シーンの説明

仕事では、ファイルを Tencent Cloud のObject Storage (COS)にアップロードするなど、便利な使用と管理のためにサーバーにいくつかのファイルをアップロードする必要があることがよくありますでは、Python を使用してファイルのアップロードを実装するにはどうすればよいでしょうか?

オプション 1

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

オプション 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()

説明: このプロセスは、リクエストを使用して、Postman のフォームデータを使用してファイルをアップロードするプロセスをシミュレートします。
プロセス: 最初に you-get を使用して、データベースに保存されているサードパーティのビデオ リンクに従ってビデオをダウンロードし、次にアップロード メソッドを使用してビデオを oss にアップロードします。次に、oss リンクが取得され、最後に取得された ossリンクはデータベース内の対応するものに更新されます。
注: 具体的な操作は実際の状況によって異なります。ここではアイデアのみを示します。

参考リンク

おすすめ

転載: blog.csdn.net/qq_34562959/article/details/121557700