我需要創建GAE使用下列程序:如何保存上傳的文件,然後用GAE返回?
- 用戶上傳一些文件(假設POST,要myapp.appspot.com/upload);
- 我需要保存(數據存儲?)並返回鏈接;
- 根據提供的鏈接,用戶應該可以在5分鐘內下載該文件。
我創建了以下內容:
的app.yaml
application: synoext
version: 1
runtime: python
api_version: 1
handlers:
- url: /upload
script: synoext.py
- url: /file/\w+
script: synoext.py
- url: /cleanup
script: synoext.py
synoext.py
import datetime
import logging
import urlparse
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Files(db.Model):
file = db.BlobProperty()
added = db.DateTimeProperty(auto_now_add=True)
class UploadFile(webapp.RequestHandler):
def post(self):
logging.info('(POST) Uploading new file')
# saving file in the database
file = Files()
file.file = db.Blob(self.request.get("file"))
file.put()
self.response.out.write('http://myapp.appspot.com/' + str(file.key()))
class GetFile(webapp.RequestHandler):
def get(self, key):
file = db.get(key)
if file is not None:
self.response.headers['Content-Type'] = 'application/x-bittorrent'
self.response.out.write(file.file)
else:
self.response.set_status(404)
class Cleanup(webapp.RequestHandler):
def get(self):
'''Automatically run job (cron) to delete old records (maximum 10000)
from Files database (records, which are older than 5 minutes)
'''
fiveMinutesAgoDate = datetime.datetime.now() - datetime.timedelta(minutes=5)
q = db.GqlQuery("SELECT * FROM Files WHERE added < :1", fiveMinutesAgoDate)
results = q.fetch(10000)
db.delete(results)
self.response.out.write('{"result": true}')
application = webapp.WSGIApplication(
[('/upload', UploadFile),
('/file/(\w+)', GetFile),
('/cleanup', Cleanup)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
它是正確的嗎?該方法是否正確?或者,我不應該使用數據存儲?
Upd。奇怪,但下面的代碼
def get(self, key):
file = db.get(key)
if file is not None:
如果使用不正確的密鑰不能正常工作。 這裏有什麼問題?
Cron作業與任何其他離線任務具有相同的10分鐘時間限制 - 10分鐘。不過,用ETA排隊單個任務刪除每個blob將是一個更好的解決方案。 –
@尼克哦,很高興知道,我沒有意識到它的感謝。我一直認爲cron-jobs調用是面向用戶的請求。關於評論的第二部分,你的意思是比使用mapper-api更好? – systempuntoout
Mapreduce適用於批量更新,但在此我們確切知道哪些記錄需要更新。每個記錄排隊一個任務,刪除該記錄,很簡單,應該可以正常工作。 –