如何定义Google端点API文件下载消息端点

2024-09-30 01:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在googleendpointapi上找到的所有示例(例如tic-tac-toe示例)都显示字符串、整数、枚举等字段。这些示例都没有说明如何使用API指定文档(例如,图像或zip文件)上载或下载。这不可能吗?在

如果这是可能的,谁能分享一个代码片段,说明如何在服务器上定义google端点api以允许文件的下载和上传?例如,是否有一个zip响应将指定一个端点作为响应?如何在响应中包含zip文件?在

一个使用python或php的例子将不胜感激。如果来自endpoints proto datastore团队的任何人正在观看此讨论,请说明目前endpoints是否支持文件下载。如果这根本不可能,我们不愿意浪费时间试图弄清楚。谢谢。在

我们正在寻找一个完整的上传和下载的例子。我们需要在上传期间将上传文件的密钥存储在我们的数据库中,并检索它以供下载。客户端应用程序发送一个令牌,API需要使用该令牌来确定要下载的文件。因此,我们需要将上传过程中生成的blob密钥存储在数据库中。我们的数据库将拥有令牌和blob文件密钥之间的映射。在

class BlobDataFile(models.Model):
   data_code       = models.CharField(max_length=10) # Key used by client app to request file
   blob_key        = models.CharField()

顺便说一句,我们的应用程序是用django1.7编写的,带有mysql(用模型。模型)数据库。我能找到的所有googleappengine上传示例都是为独立的webapp处理程序编写的(不是url.py/views.py解决方案可以在任何地方找到)。因此,构建一个独立的上传程序和编写API代码一样困难。如果你的解决方案url.py/views.py示例上载文件并在BlobDataFile中保存blob\u键,这对我们来说已经足够好了。在


Tags: 文件代码pyapi数据库应用程序示例models
2条回答

如果使用blobstore,请使用get_serving_url函数从客户机的url读取图像,或者使用ResourceContainer中的messages.ByteField并使用base64.b64decode序列化图像

#the returned class
class Img(messages.Message):
     message = messages.BytesField (1)

#The api class
@endpoints.api(name='helloImg', version='v1')
class HelloImgApi(remote.Service):

ID_RESOURCE = endpoints.ResourceContainer(
        message_types.VoidMessage,
        id=messages.StringField(1, variant=messages.Variant.STRING))

@endpoints.method(ID_RESOURCE, Img,
                  path='serveimage/{id}', http_method='GET', #ID is the blobstore key
                  name='greetings.getImage')
def image_get(self, request):
    try:
        blob_reader = blobstore.BlobReader(blob_key)
        value = blob_reader.read()

        return Img(message=value)
    except:
        raise endpoints.NotFoundException('image %s not found.' %
                                          (request.id,))        

APPLICATION = endpoints.api_server([HelloImgApi])

这是响应(以正确的格式保存在客户端中)

^{pr2}$

在客户机中,您可以这样做(在python中实现连续性)

import base64

myFile = open("mock.jpg", "wb")
img = base64.b64decode(value)  #value is the returned string
myFile.write(img)
myFile.close()

您是否尝试将图像转换为base64字符串并将其作为请求的参数发送到客户端?在

因此,您可以在服务器端执行此操作:

#strArg is the Base64 string sent from the client
img = base64.b64decode(strArg)
filename = 'someFileName.jpg' 
with open(filename, 'wb') as f:
    f.write(img)
#then you can save the file to your BlobStore

相关问题 更多 >

    热门问题