Python,App Engine:HTTP多部分POST到Vk.Ads API

时间:2017-12-20 15:05:40

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

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

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

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

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。使用urlfetchposter

发布到API,方法#1
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。使用requests

POST到API,方法#2
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)

2 个答案:

答案 0 :(得分:1)

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

我使用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的进一步操作。

答案 1 :(得分: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