google-app-engine 上传下载 用户文件

2023-10-28

http://blog.notdot.net/2009/9/Handling-file-uploads-in-App-Engine

http://hi.baidu.com/zjm1126/item/31d65e31962da022b3c0c56e

一篇:

import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


class MyModel(db.Model):
data = db.BlobProperty(required=True)
mimetype = db.StringProperty(required=True)

class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_args=None):
if not template_args:
template_args = {}
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.render(path, template_args))

class upload(BaseRequestHandler):
def get(self):
self.render_template('index.html',)
def post(self):
file = self.request.POST['file']
obj = MyModel(data=file.value, mimetype=file.type)
obj.put()
o=file
#self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o)))
#return
file_url = "http://%s/download/%d/%s" % (self.request.host, obj.key().id(), file.filename)
self.response.out.write("Your uploaded file is now available at <a href='%s'>%s</a>" % (file_url,file_url,))

class download(BaseRequestHandler):
def get(self,id,filename):
#id=self.request.get('id')
entity = MyModel.get_by_id(int(id))
self.response.headers['Content-Type'] = entity.mimetype
self.response.out.write(entity.data)



application = webapp.WSGIApplication(
[
('/?', upload),
('/download/(\d+)/(.*)',download),
],
debug=True
)
def main():
run_wsgi_app(application)

if __name__ == "__main__":
main()



the html is:


<form enctype="multipart/form-data" action="/" method="post">
<input type="file" name="file" />
<input type="submit" />
</form>

另一篇英文:

This is the ninth in a series of 'Cookbook' posts describing usefulstrategies and functionality for writing better App Engine applications.

One issue that comes up frequently on the App Engine groups is how tohandle file uploads from users. Part of the confusion arises from thefact that App Engine apps cannot write to the local filesystem.Fortunately, the Datastore comes to the rescue: We can easily write anapp that accepts file uploads and stores them in the datastore, thenserves them back to users.

To start, we need an HTML form users can upload files through:

<html>
<head>
  <title>File Upload</title>
</head>
<body>
  <form method="post" action="/">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
  </form>
</body>
</html>

We'll also need a datastore model we can store the uploaded file in:

class DatastoreFile(db.Model):
  data = db.BlobProperty(required=True)
  mimetype = db.StringProperty(required=True)

And finally, a Request Handler that can handle the uploads:

class UploadHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write(template.render("upload.html", {}))

  def post(self):
    file = self.request.POST['file']
    entity = DatastoreFile(data=file.value, mimetype=file.type)
    entity.put()
    file_url = "http://%s/%d/%s" % (self.request.host, entity.key().id(), file.name)
    self.response.out.write("Your uploaded file is now available at %s" % (file_url,))

Note that we access the uploaded file using self.request.POST ratherthan self.request.get(); using self.request.get("file") would only giveus the actual data of the uploaded file, whilstself.request.POST["file"] returns a cgi.FieldStorage object, whichgives us access to the file data, filename, and mimetype. We take careto store the mimetype in addition to the original file data so we canmake sure we serve it back up with the correct mimetype.

Serving the uploaded file from the datastore is, of course, also easy:

class DownloadHandler(webapp.RequestHandler):
  def get(self, id, filename):
    entity = DatastoreFile.get_by_id(int(id))
    self.response.headers['Content-Type'] = entity.mimetype
    self.response.out.write(entity.data)

Our handler here takes a filename in addition to the ID; the filenameis purely for convenience, to make the URLs we provide more friendly.All we care about is the ID, which we use to find the file object inthe datastore.

Finally, here's the webapp to glue all this together:

application = webapp.WSGIApplication([
    ('/', UploadHandler),
    ('/(\d+)/(.*)', DownloadHandler),
])

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

Next, we'll be taking a break from the cookbook series, and workingthrough the steps of building a blogging system on App Engine.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

google-app-engine 上传下载 用户文件 的相关文章

  • 爷青回

    B站主页 https space bilibili com 1707990930 欢迎 点赞 收藏 评论 如有错误请指正 Python Java领域博主 你们的支持是我最大的动力 大家好 我是爱丽 今天我们来制作一个相信每一位小伙伴都玩过的

随机推荐

  • html 默认打开方式,[HTML] 链接默认打开方式标签元素

    HTML 超链接 锚文本 默认打开方式与默认链接URL地址标签元素 一 语法与结构 二 Html base超链接默认打开地址与打开方式标签使用说明 1 Target 值 1 blank 新窗口打开URL链接 2 parent 在本网页刷新全
  • 【算法练习】MVP争夺战

    100分 题目描述 在星球争霸篮球赛对抗赛中 强大的宇宙战队 希望每个人都能拿到MVP MVP的条件是 单场最高分得分获得者 可以并列 所以宇宙战队决定在比赛中 尽可能让更多的队员上场 且让所有有得分的队员得分都相同 然而比赛过程中的每一分
  • Python学习之道-串口编程&TEMI880温箱控制

    Python学习之道 串口编程 TEMI880温箱控制 一 环境准备 安装pyserial库 pyserial库常用函数介绍 参考例程 二 开发实践 1 实践项目 2 协议介绍 2 1 一般的指令格式 2 2 举例 2 3 协议命令 3 串
  • 二,Xposed环境

    2 1 基本环境 环境已经完全搞定 手机 刷机 权限 注意 手机 开发者模式 调试模式 都要开启 真机参考本系列刷机或其它文章 https blog csdn net qq 32667685 article details 12590947
  • Servlet的相关API

    Hello 我是栋zzzz 先祝各位端午节快乐 那么接下来就继续来学习Servlet吧 我给大家整理了一些前置知识 方便更好的理解Servlet HTTP协议 上 HTTP协议 下 Tomcat Servlet 目录 一 HTTPServl
  • 判断单链表是否有环

    bool FixRing Node pHead Node pSlow pHead Node pFast pHead while pFast pFast gt next 如果存在环 不存在p next NULL的情况 pSlow pSlow
  • 相比于前端,为什么移动端程序员没那么抢手了?

    最近经常有一些移动端开发的小伙伴向我们招聘体验师反映 工作好像没有去年那么好找了 这是个案还是一个普遍现象 我们带着这个问题研究了一下 100offer 平台上的拍卖数据 今年互联网就业形势确实没有去年同期好 2015 年 Q1 我们候选人
  • 第1.3章 树莓派环境监控

    1 zabbix 在拜读 树莓派学习指南 基于Linux pdf 树莓派 Raspberry Pi 实战指南 手把手教你掌握100个精彩案例 等人的著作 都提到了一个问题 就是树莓派容易烧坏 于是就想着在使用前 是不是把监控给做好 比如安装
  • 学习源码之SPI机制

    目录 一 什么是SPI 二 SPI的作用 三 如何使用 四 流程图 五 源码学习 1 ServiceLoader load Class class 2 serviceLoader iterator 3 iterator hasNext 4
  • wifi卡慢延迟高_如何解决家里的WiFi卡顿的问题

    作为不同网络之间互相连接的枢纽 路由器系统构成了基于TCP IP 的国际互联网络Internet 的主体脉络 也可以说 路由器构成了Internet的骨架 家里安装有WiFi的用户有没有注意到一个问题 就是在我们使用WiFi的时候 总会时不
  • 利用人工智能开启商业新时代

    ChatGPT是基于人工智能大模型架构的强大语言模型 它具备出色的自然语言处理和生成能力 能够与人类进行智能对话 无论是寻求创业灵感 市场调研 内容创作还是销售辅助 ChatGPT都可以为你提供强有力的支持 接下来 我将为大家详细介绍如何利
  • 第二章 数据迁移之Dolphinscheduler调度DataX从Mysql全量导入Hive

    绪 需求说明 将源系统mysql表数据全量抽取到hive中作为ODS层 不保留历史变化 create table T YYBZB TGH BANKINFO id int 8 bank id int 8 bank name varchar 2
  • 第四届蓝桥杯Java B组 马虎的算式

    马虎的算式 Description 小明是个急性子 上小学的时候经常把老师写在黑板上的题目抄错了 有一次 老师出的题目是 36 x 495 他却给抄成了 396 x 45 但结果却很戏剧性 他的答案竟然是对的 因为 36 x 495 396
  • unity航点寻径

    一 游戏框架 设置了六个路标 角色会在这六个路标之间一次移动 当移动到第六个路标后又会返回第一个路标 继续依次移动 road 道路 由五个立方体组成 sign 路标 由六个胶囊组成 enemy 寻路的角色 二 游戏实现 1 创建一个平面 赋
  • RGB颜色对照表大全

    常用颜色rgb 颜色对照表 一 R G B 值 R G B 值 R G B 值 黑色 0 0 0 000000 黄色 255 255 0 FFFF00 浅灰蓝色 176 224 230 B0E0E6 象牙黑 41 36 33 292421
  • pdf预览

    previewSop url axios get url responseType arraybuffer then res gt var data res data var blob new Blob data type applicat
  • 实现多线程爬取数据并保存到mongodb

    多线程爬取二手房网页并将数据保存到mongodb的代码 import pymongo import threading import time from lxml import etree import requests from queu
  • 什么是3d虚拟数字人?对未来发展有什么影响?

    3d虚拟数字人指的是以数字形式存在的人工智能 也被称为数字智能体 无论是在我们的周围 还是我们自己的体内 他们都能够利用数据和代码来进行模拟 操纵和创造各种不同的人类形态 基本上来说 数字人就是指那些具备大脑 眼睛 手和嘴等特性的数字化机器
  • 【Analyzing and Mitigating Interference in Neural Architecture Search】分析与缓解NAS权重共享方法中的子模型之间的干扰问题

    Analyzing and Mitigating Interference in Neural Architecture Search 论文地址 https proceedings mlr press v162 xu22h html 摘要
  • google-app-engine 上传下载 用户文件

    http blog notdot net 2009 9 Handling file uploads in App Engine http hi baidu com zjm1126 item 31d65e31962da022b3c0c56e