2017-04-25 120 views
0

我正在嘗試使用Openload REST API調用upload a file「240p.mp4」。如何使用Openload.co API上傳文件

由於上傳端點都需要文件的SHA-1散列,我得到了它這樣做:

sha1 = hashlib.sha1() 

BLOCKSIZE = 65536 
with open('240p.mp4', 'rb') as afile: 
    buf = afile.read(BLOCKSIZE) 
    while len(buf) > 0: 
     sha1.update(buf) 
     buf = afile.read(BLOCKSIZE) 

sha1_hash = sha1.hexdigest() 

所以我要求的上傳鏈接:

url = "https://api.openload.co/1/file/ul?login={login}&key={key}&sha1={sha1}".format(
    login='YOUR_LOGIN', 
    key='YOUR_API_KEY', 
    sha1=sha1_hash, 
) 

p = { 
    'url': url, 
    'headers': { 
     'User-Agent': self.ua, 
    } 
} 
r = self.r.get(url=p['url'], headers=p['headers']) 
j = r.json() 

upload_link = j['result']['url'] 

他們建議作出CURL但我更喜歡requests guy ^^

curl -F [email protected]/path/to/file.txt https://13abc37.example.com/ul/jAZUhVzeU78 

所以,我試圖用POST請求來複制它:

p = { 
    'url': upload_link, 
    'headers': { 
     'user-agent': self.ua, 
     'Content-Type': 'multipart/form-data; boundary="xxx"', 
    }, 
    'files': { 
     'file1': open('/scripts/wordpress/240p.mp4', "rb"), 
     # I've also tried this (and some others) 
     # 'file1': ('240.mp4', open('/scripts/wordpress/240p.mp4', "rb"), 'video/mp4') 
    } 
} 
r = self.r.post(url=p['url'], headers=p['headers'], files=p['files']) 

但它返回這個錯誤響應:

r.content¬ 
{ 
    "status": 500, 
    "msg": "failed to read: closed" 
} 

從理論上講,狀態500錯誤是從服務器錯誤。但爲什麼我得到這個錯誤?

N1:我明確地設置了boundary="xxx",因爲如果我不這樣做。該響應返回它缺失。所以我設定了它。

N2:文件/scripts/wordpress/240p.mp4的路徑是正確的。權限也是如此。

N3:我知道遠程上傳功能,但我需要從二進制文件上傳(從本地我的意思)

N4:很明顯的,但self.rrequests.session()的分配

+1

使用https://github.com/mohan3d/PyOpenload – Dalvenjia

+0

我要去嘗試。謝謝。如果它有效,我會檢查代碼以知道我的代碼在哪裏失敗... – Jeflopo

回答

0

我想通了它爲什麼不起作用。 該問題已通過讓requests處理content-type標題解決。 變量在多部分字段中的值name是無關緊要的,你可以稱它爲file1file_upload或其他。

這是爲我工作:

filepath = '/scripts/wordpress/240p.mp4' 

sha1 = hashlib.sha1() 

BLOCKSIZE = 65536 
with open(filepath, 'rb') as afile: 
    buf = afile.read(BLOCKSIZE) 
    while len(buf) > 0: 
     sha1.update(buf) 
     buf = afile.read(BLOCKSIZE) 

sha1_hash = sha1.hexdigest() 

url = "https://api.openload.co/1/file/ul?login={login}&key={key}&sha1={sha1}".format(
    login='YOUR_LOGIN', 
    key='YOUR_API_KEY', 
    sha1=sha1_hash, 
) 

p = { 
    'url': url, 
    'headers': { 
     'User-Agent': self.ua, 
    } 
} 
r = self.r.get(url=p['url'], headers=p['headers']) 
j = r.json() 

upload_link = j['result']['url'] 

p = { 
    'url': upload_link, 
    'headers': { 
     'user-agent': self.ua, 
    }, 
    'files': { 
     'file1': open(filepath, 'rb'), 
    } 
} 
r = self.r.post(url=p['url'], headers=p['headers'], files=p['files']) 
相關問題