Created
August 26, 2014 15:54
-
-
Save duythinht/b1429a48c1d7cb548be1 to your computer and use it in GitHub Desktop.
Upload file via flask with appengine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Blueprint | |
from flask import render_template as render | |
from flask import request, Response | |
import cloudstorage as gcs | |
from google.appengine.api import app_identity | |
from os import environ | |
from json import dumps | |
module = Blueprint('API_UPLOAD', __name__) | |
gae_development = environ.get('SERVER_SOFTWARE', 'testing').startswith('Development') | |
@module.route('/', methods=['GET']) | |
def index(): | |
return ''' | |
<!doctype html> | |
<title>Upload new File</title> | |
<h1>Upload new File</h1> | |
<form action="/api/v1/upload/" method=post enctype=multipart/form-data> | |
<p><input type=file name=file> | |
<input type=submit value=Upload> | |
</form> | |
''' | |
@module.route('/', methods=['POST']) | |
def upload(): | |
f = request.files['file'] | |
gcs_file_name = '/%s/%s' % (app_identity.get_default_gcs_bucket_name(), f.filename) | |
# Write file to google cloud storage | |
with gcs.open(gcs_file_name, 'w', content_type=f.content_type, options={b'x-goog-acl': b'public-read'}) as gcs_file: | |
gcs_file.write(f.read()) | |
data = {} | |
# Return cdn url | |
if not gae_development: | |
data['url'] = 'http://storage.googleapis.com' + gcs_file_name | |
else: | |
data['url'] = 'http://localhost:8080/_ah/gcs' + gcs_file_name | |
return Response(dumps({'data': data}), mimetype='application/json') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment