English
Atom Login Admin

Seeds of mention

FlaskでBlobをアップロードする方法

lakshmi@cloudysunny14.org
mentioned on Sunday,January 27,2013

一般的にはBlobをアップロードするときには、blobstore_handlersを使うのだが、別の方法もあるのはご存知だろうか。
例えば、Flaskでアプリケーションを作っているときは、以下のように実装する。

  • app.py
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
  return '.' in filename and \
    filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/upload", methods=["POST"])
def upload():
  if request.method == "POST":
    upload_file = request.files["file"]
    image_data = upload_file.read()
    if image_data and allowed_file(upload_file.filename):
      file_name = secure_filename(upload_file.filename)
      blob_io = files.blobstore.create(mime_type=upload_file.content_type, _blobinfo_uploaded_filename=file_name)
      with files.open(blob_io, 'a') as f:
        f.write(image_data)
      files.finalize(blob_io)
      blob_key = files.blobstore.get_blob_key(blob_io)
      image_url = images.get_serving_url(str(blob_key))
      return redirect(url_for("result", upload_url=image_url))
  • Upload form
<form action="{{ url_for("upload") }}" method=post enctype="multipart/form-data">
    {% if upload_url %}<p class=uploaded>Now upload file's url:
    <input type="text" value="{{upload_url}}">(Copy&Paste this.)</p>{% endif %}
    Upload File:<input type="file" name="file"><br>
    <input type="submit" name="submit" value="Upload">
</form>

Comments

Add Comment

Login
This entry was tagged #GAE