|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from flask import Flask, abort, redirect, request |
| 16 | +from google.appengine.api import wrap_wsgi_app |
| 17 | +from google.appengine.ext import blobstore, ndb |
| 18 | + |
| 19 | +UPLOAD_FORM = '''\ |
| 20 | +<h2>Upload photo:</h2> |
| 21 | +<form action="%s" method="POST" enctype="multipart/form-data"> |
| 22 | + <input type="file" name="file"><p></p><input type="submit"> |
| 23 | +</form>''' |
| 24 | + |
| 25 | +app = Flask(__name__) |
| 26 | +app.wsgi_app = wrap_wsgi_app(app.wsgi_app) |
| 27 | + |
| 28 | + |
| 29 | +class PhotoUpload(ndb.Model): |
| 30 | + 'PhotoUpload entity for registering a photo' |
| 31 | + blob_key = ndb.BlobKeyProperty() |
| 32 | + |
| 33 | + |
| 34 | +class PhotoUploadHandler(blobstore.BlobstoreUploadHandler): |
| 35 | + 'PhotoUploadHandler handles a photo upload (POST)' |
| 36 | + def post(self): |
| 37 | + uploads = self.get_uploads(request.environ) |
| 38 | + blob_id = uploads[0].key() if uploads else None |
| 39 | + PhotoUpload(blob_key=blob_id).put() |
| 40 | + return redirect('/view_photo/%s' % blob_id) |
| 41 | + |
| 42 | +@app.route('/upload_photo', methods=['POST']) |
| 43 | +def upload_photo(): |
| 44 | + 'call upload handler for upload (POST) request' |
| 45 | + return PhotoUploadHandler().post() |
| 46 | + |
| 47 | + |
| 48 | +class ViewPhotoHandler(blobstore.BlobstoreDownloadHandler): |
| 49 | + 'ViewPhotoHandler handles a photo view/download (GET)' |
| 50 | + def get(self, blob_key): |
| 51 | + if blobstore.get(blob_key): |
| 52 | + headers = self.send_blob(request.environ, blob_key) |
| 53 | + headers['Content-Type'] = None |
| 54 | + return '', headers |
| 55 | + abort(404) |
| 56 | + |
| 57 | +@app.route('/view_photo/<photo_key>') |
| 58 | +def view_photo(photo_key): |
| 59 | + 'call download handler for view (GET) request' |
| 60 | + return ViewPhotoHandler().get(photo_key) |
| 61 | + |
| 62 | + |
| 63 | +@app.route('/') |
| 64 | +def upload_form(): |
| 65 | + 'display photo upload HTML form' |
| 66 | + return UPLOAD_FORM % blobstore.create_upload_url('/upload_photo') |
0 commit comments