在Python AppEngine上从Android上传并读取文件

0 投票
1 回答
894 浏览
提问于 2025-04-17 08:10

我想把一个csv文件从安卓设备发送到Python的AppEngine上。我正在使用Blobstore API,发送文件时用到了MultipartEntityHttpPostHttpGet这些工具。

根据Blobstore API的要求,你需要调用一个方法create_upload_url('/upload')来生成一个上传文件的链接,然后用这个链接作为上传文件的动作。你可以在这里找到更多信息。

我在做什么呢?我调用一个方法来创建这个链接,并把它返回给我的安卓应用。然后我就用这个链接来上传文件。

生成的链接格式是这样的:

myapp.appspot.com/_ah/upload/一堆数字和字母/

基本上就是这样:

安卓代码

 HttpClient httpClient = new DefaultHttpClient();
 HttpGet httpGet = new HttpGet(mContext.getString("myapp.appspot.com/get_blobstore_url");

 HttpResponse urlResponse = httpClient.execute(httpGet);

 result = EntityUtils.toString(urlResponse.getEntity());

 Uri fileUri = Uri.parse("file:///sdcard/dir/myfile.csv"); // Gets the Uri of the file in the sdcard
 File file = new File(new URI(fileUri.toString())); // Extracts the file from the Uri

 FileBody fileBody = new FileBody(file, "multipart/form-data");

 MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
 entity.addPart("file", fileBody);

 HttpPost httpPost = new HttpPost(result);

 httpPost.setEntity(entity);

 HttpResponse response = httpClient.execute(httpPost);
 response.getStatusLine();

AppEngine代码

# Returns only the URL in which the file will be uploaded, so this URL may be used in client for upload the file
class GetBlobstoreUrl(webapp.RequestHandler):
    def get(self):
        logging.info('here')
        upload_url = blobstore.create_upload_url('/upload')
        logging.info("url blob %s", upload_url)
        self.response.out.write(upload_url)

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        logging.info('inside upload handler')
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        return blob_info.key()

def main():
    application = webapp.WSGIApplication([('/upload', UploadHandler), ('/get_blobstore_url', GetBlobstoreUrl)], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()

问题1

当我把文件发送到AppEngine返回的链接时,这会自动调用服务器上的UploadHandler方法吗?因为这个方法里的日志信息没有显示出来,而且文件确实被插入了,我在用生成的链接上传文件时收到的响应是404错误,为什么会出现这个错误,如果文件已经被上传了呢?

问题2

在我上传文件后,如何在服务器上解析这个csv文件,并把文件里的所有数据插入到数据存储中呢?

谢谢。

1 个回答

0

当我把文件发送到AppEngine返回的那个网址时,这会自动调用服务器的方法UploadHandler吗?

没错。

当我把文件发送到AppEngine返回的那个网址时,这会自动调用服务器的方法UploadHandler吗?

给我们看看你的服务器日志 - 你在哪个网址遇到404错误?上传处理程序有没有给你任何日志信息?

我上传文件后,怎么在服务器上解析这个csv文件,并把文件里的所有数据插入到数据存储中呢?

可以使用BlobReader API,然后把打开的文件传给Python的csv模块。

撰写回答