【问题标题】:Python, App Engine: HTTP multipart POST to Vk.Ads APIPython,App Engine:HTTP 多部分 POST 到 Vk.Ads API
【发布时间】:2018-01-06 04:03:02
【问题描述】:

我试图自己解决这个问题几天,搜索示例和文档,还有it wasn't solved on ruSO。所以,我希望能在 enSO 上找到解决方案。

我使用 Python 和 Google App Engine 在 Vk 社交网络上开发了一项自动创建广告的服务。最初,广告图片被加载到我的服务器(第 1 部分),然后它们在某个时间被上传到 Vk 服务器(第 2.1 和 2.2 部分)。似乎图片已正确加载并存储在我的服务器上(我下载了它们并与原始图片进行了比较——每个字节都是相同的)。但我附上 part 1 代码以防万一。

要先将图片上传到 Vk.Ads,我需要 to get a URL — 这很简单,所以跳过它。其次,我需要向此链接发送一个 POST 请求,其中包含字段 file 以及照片的二进制内容 (API documentation)。我为此创建了两种方法(2.1 和 2.2),但它们都返回 errcode: 2,这意味着 corrupted file。在我看来,问题在于请求,但我不排除文件上传/存储在我的服务器上的可能性,或者 API 的一些奇怪工作。我将不胜感激任何答案和 cmets。

1。上传到我的服务器

import webapp2
from google.appengine.ext import ndb

# stores pictures on the server
class Photo(ndb.Model):
    name = ndb.StringProperty()
    img = ndb.BlobProperty()

    @staticmethod
    def get(name):
        retval = Photo.query(Photo.name == name).get()
        return retval

    @staticmethod
    def create(name, blob):
        retval = Photo()
        retval.name = name
        retval.img = blob
        return retval

class PhotosPage(webapp2.RequestHandler):
    def get(self):
        # general content of the page:
        html = '''<form action="/photos" method="post" enctype="multipart/form-data">
            <input type="file" name="flimg"/>
            <input value="new_pic" name="flname"/>
            <input type="submit" value="Upload"/> </form>'''

    def post(self):
        n = str(self.request.get('flname'))
        f = self.request.get('flimg')
        p = Photo.get(n)
        if p:
            p.img = f
        else:
            p = Photo.create(n, f)
        p.put()

2.1。 POST 到 API,方法 #1,使用 urlfetch и poster:

from poster.encode import multipart_encode, MultipartParam
from google.appengine.api import urlfetch

name = 'file'
content = ... # file binary content
where = ... # gotten URL

options = {
    'file': MultipartParam(
        name=name,
        value=content,
        filename=name,
        filetype='image/png',
        filesize=len(content))
}

data, headers = multipart_encode(options)
pocket = "".join(data)

result = urlfetch.fetch(
    url=where,
    payload=pocket,
    method=urlfetch.POST,
    headers=headers)

2.2。 POST 到 API,方法 #2,使用 requests:

import requests

name = 'file'
content = ... # file binary content
where = ... # gotten URL

# I also tried without this dict; is it necessary?
data = {
    'fileName': name,
    'fileSize': len(content),
    'description': 'undefined',
}

result = requests.post(where, files={name: StringIO(content)}, data=data)

另外,对于第二种方法,我提取了我的请求内容:

POST
https://pu.vk.com/c.../upload.php?act=ads_add&mid=...&size=m&rdsn=1&hash_time=...&hash=...&rhash=...&api=1

Content-Length: 15946
Content-Type: multipart/form-data; boundary=b4b260eace4e4a7082a99753b74cf51f

--b4b260eace4e4a7082a99753b74cf51f
Content-Disposition: form-data; name="description"
undefined

--b4b260eace4e4a7082a99753b74cf51f
Content-Disposition: form-data; name="fileSize"
15518

--b4b260eace4e4a7082a99753b74cf51f
Content-Disposition: form-data; name="fileName"
file

--b4b260eace4e4a7082a99753b74cf51f
Content-Disposition: form-data; name="file"; filename="file" 
< File binary content >

--b4b260eace4e4a7082a99753b74cf51f-- 

更新。

感谢 SwiftStudier,我找到了问题的根源:StringIOBytesIO 的行为与文件 open 不同。如果我只使用open 代码运行良好,但它不适用于虚拟文件。怎么解决?

import requests
from io import BytesIO

with open('path.to/file.png', 'rb') as fin:
    content = BytesIO(fin.read())

token = '...'
url = 'https://api.vk.com/method/ads.getUploadURL?access_token=' + token + '&ad_format=2'
upload_url = requests.get(url).json()['response']

post_fields = {
    'access_token': token
}

data_fields = {
    # This works:
    # 'file': open('path.to/file.png', 'rb')

    # But this does not:
    'file': content
}

response = requests.post(upload_url, data=post_fields, files=data_fields)
print(response.text)

【问题讨论】:

  • @snakecharmerb 文档中没有提到...但我稍后会尝试。
  • @snakecharmerb 不幸的是,base64 编码没有变化:(

标签: python image google-app-engine multipartform-data vk


【解决方案1】:

在对不同的 HTTP 请求内容进行了大量实验和调查后,我发现了错误代码和工作代码之间的唯一区别。它只有大约 4 个字节:文件名必须包含扩展名。 Vk API 甚至会忽略 Content-Type: image/png,但在文件名中需要 .png 或类似名称。所以,这不起作用:

requests.post(upload_url, files={
    'file': BytesIO('<binary file content>')
})

但是这个选项可以正常工作:

requests.post(upload_url, files={
    'file': ('file.png', BytesIO('<binary file content>'), 'image/png')
})

就像这个,GAE不支持:

requests.post(upload_url, files={
    'file': open('/path/to/image.png', 'rb')
})

StringIOStringIO 都适用于该任务。如前所述,Content-Type 无所谓,可以只是multipart/form-data

【讨论】:

    【解决方案2】:

    不确定是否有帮助,但无论如何我都会发布它

    我使用requests将图片上传到ads

    import requests
    
    token = '***'
    url = f'https://api.vk.com/method/ads.getUploadURL?access_token={token}&ad_format=1' # I set add_format randomly just to avoid an error of this parameter was missing
    upload_url = requests.get(url).json()['response']
    
    post_fields = {
        'access_token': token
    }
    
    data_fields = {
        'file': open('/path/to/image.png', 'rb')
    }
    
    response = requests.post(upload_url, data=post_fields, files=data_fields)
    print(response.text)
    

    结果看起来像是有效的照片上传,收到的数据可用于广告 API 的进一步操作。

    【讨论】:

    • 感谢您的回复!我已经尝试过你的代码,它确实有效。但是,我不能在 GEA 上使用它,open 在那里不可用。可能问题出在文件内容和StringIOopen 不同...
    • 我找到了解决办法,看我的回答。无论如何,感谢您的努力!
    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2017-06-05
    • 2014-05-13
    • 2017-07-18
    相关资源
    最近更新 更多