首页 > 解决方案 > 我如何通过 python 为 mirrorace.org 发送 api 请求

问题描述

我想在 mirrorace 中上传文件,但我无法理解他们的 api,他们给出了一个示例 php 代码,但我无法理解。有人可以告诉我如何从 python 发出发布请求这是他们的 api 文档https://mirrorace。 org/api 请有人帮助我,我是 python 新手。

标签: pythonphpapi

解决方案


我第一次听说mirrorace.org,所以我在几分钟内专门为这个问题编写了这个代码,尽管如此,它确实适用于默认镜像:

from requests import Session
import mimetypes
from pathlib import Path

def get_mime(f):
    return mimetypes.guess_type(f)[0]

s = Session()

api_key = "xxx"
api_token = "xxx"
req1_url = "https://mirrorace.com/api/v1/file/upload" # get info needed for req2

data = {"api_key": api_key, "api_token": api_token}
req1 = s.post(req1_url, data=data).json()
if req1['status'] == 'success':
    upload_key = req1['result']['upload_key']
    cTracker = req1['result']['cTracker']
    server_file = req1['result']['server_file']
    max_mirrors = req1['result']['max_mirrors'] # max mirror allowed to upload
    mirrors = list([k for k, v in req1['result']['mirrors'].items() if v])[:int(max_mirrors)] # create a list of enabled mirror id's with cap based on max_mirrors

    if upload_key and cTracker and server_file and mirrors:
        f = "C:/Users/0x/Desktop/A CARNE (letra e vídeo) com SEU JORGE, vídeo MOACIR SILVEIRA (320 kbps).mp3"
        fn = Path(f).name
        print("FILE NAME:", fn)
        mime_type = get_mime(f)
        print("MIME TYPE:", mime_type)

        # file = {"files": open(f,'rb')} # also works
        file = {'files': (fn, open(f,'rb'), mime_type)}
        # file = {'files': ("new_filename.mp3", open(f,'rb'), mime_type)}  # also works
        
        data = {"api_key": api_key, "api_token": api_token, "cTracker": cTracker, "upload_key": upload_key, "mirrors[]": mirrors}
        req2 = s.post(server_file, files=file, data=data).json()
        if req2['status'] == 'success':
            # {'status': 'success', 'result': {'name': 'A CARNE (letra e vídeo) com SEU JORGE, vídeo MOACIR SILVEIRA (320 kbps).mp3', 'size': 11929965, 'slug': '3Jcad', 'url': 'https://mirrorace.org/m/3Jcad', 'info': 'complete'}}
            print(req2['result']['url'])
        else:
            print("Error: ", req2)
    else:
        print("Error data missing: ",  upload_key, cTracker, server_file, mirrors)
else:
    print("Error: ", req1)

要旨


推荐阅读