美文网首页
Python pgyer 包上传功能

Python pgyer 包上传功能

作者: _海角_ | 来源:发表于2022-03-22 16:05 被阅读0次

由于python 在日常工作中担任辅助工具功能,所以不是很熟悉用法。
本文主要记录在实现该功能中出现的问题以及解决过程。

import requests
import json
import os

headers = {'cache-control': 'no-cache','Content-type': 'multipart/form-data'}
files={'file': open('apk_path.apk', 'rb')}

pgyerData ={'_api_key':(None,'pgyer_api_key'),
            'file':(None,'@{}'.format(files)),
            }
upLoadResponse = requests.request("POST", 'https://www.pgyer.com/apiv2/app/upload', data=pgyerData,files=files)

if upLoadResponse.status_code == 200 and upLoadResponse.json()["code"] == 0:
   print("pgyer upload success")
else:
   print("pgyer upload failed")

以上为最初版本,上传过程页面没有任何反应,实属不能忍,遂考虑添加上传进度条
实现细节中有几个地方卡住很长时间
1.进度条功能是copy 这里的实现,感谢
2.multipart/form-data的请求实现
其中2 是由1 引出的

在添加完进度之后,进度条功能是有了,但是上传之后报如下错误

{"code":1001,"message":"_api_key could not be empty"}

经过charles 抓包检查发现包头中缺少multipart 信息

正常情况下的header 信息 添加完进度条之后的header 信息

也即,在添加完进度条功能以后,以下信息缺失

multipart/form-data; boundary=2f71be154d06b88b52c035a1a92f5618 

那么问题就来到了如何添加content-type
经查这里的实现感谢
即缺少了

headers['Content-Type'] = e.content_type

添加之后,一切正常。
以下为源码,包含上传以及展示上传进度功能

import requests
import json
import os
from requests_toolbelt import MultipartEncoder,MultipartEncoderMonitor
from clint.textui.progress import Bar as ProgressBar

def create_callback(encoder):
    encoder_len = encoder.len
    bar = ProgressBar(expected_size=encoder_len, filled_char='=')

    def callback(monitor):
        bar.show(monitor.bytes_read)

    return callback

headers = {'cache-control': 'no-cache'}
files={'file': open('apk_path.apk', 'rb')}

e = MultipartEncoder(
    fields={'_api_key': 'gpyer_api_key',
            'file': ('apk_name.apk', open('apk_path.apk', 'rb'))}
    )
callback = create_callback(e)
m = MultipartEncoderMonitor(e, callback)
headers['Content-Type'] = e.content_type

upLoadResponse = requests.post('https://www.pgyer.com/apiv2/app/upload', data=m,headers=headers)

print('\n');

if upLoadResponse.status_code == 200 and upLoadResponse.json()["code"] == 0:
   print("pgyer upload success")
else:
   print("pgyer upload failed")

相关文章

网友评论

      本文标题:Python pgyer 包上传功能

      本文链接:https://www.haomeiwen.com/subject/uopfjrtx.html