Skip to content

Commit

Permalink
upload files to a bucket
Browse files Browse the repository at this point in the history
  • Loading branch information
chee committed Nov 17, 2020
1 parent cbe57b3 commit 1e4f788
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 10 deletions.
8 changes: 5 additions & 3 deletions app/config.py
Expand Up @@ -5,6 +5,8 @@


class Config(object):
SECRET_KEY = os.environ.get('CC0_SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get("CC0_SQLALCHEMY_DATABASE_URI") or f"sqlite:///{os.path.join(basedir, 'app.db')}"
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.environ.get('CC0_SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get("CC0_SQLALCHEMY_DATABASE_URI") or f"sqlite:///{os.path.join(basedir, 'app.db')}"
SQLALCHEMY_TRACK_MODIFICATIONS = False
OBJECT_KEY_ID = os.environ.get('CC0_OBJECT_KEY_ID')
OBJECT_ACCESS_KEY = os.environ.get('CC0_OBJECT_ACCESS_KEY')
27 changes: 21 additions & 6 deletions app/file.py
@@ -1,15 +1,30 @@
import mimetypes
from os.path import join, basename, dirname
from os.path import basename
from .config import Config
from werkzeug.utils import secure_filename
from slugify import slugify
mimetypes.init()
import boto3

storage_endpoint = "https://eu-central-1.linodeobjects.com"
bucket_name = "cc0"
bucket_url = f"{storage_endpoint}/{bucket_name}"
storage = boto3.resource(
's3',
endpoint_url=storage_endpoint,
region_name='eu-central-1',
aws_access_key_id=Config.OBJECT_KEY_ID,
aws_secret_access_key=Config.OBJECT_ACCESS_KEY
)
bucket = storage.Bucket(bucket_name)

def make_public(name):
storage.Object(bucket_name, name).Acl().put(ACL='public-read')

def get_url_for(file, username, collection_slug, piece_slug):
name = f'{username}-{collection_slug}-{piece_slug}-{secure_filename(basename(file.filename))}'
path = join(dirname(__file__), "static", name)
file.save(path)

return f"/static/{name}"
bucket.upload_fileobj(file.stream, name)
make_public(name)
return f"{bucket_url}/{name}"

def get_type_for(file):
return mimetypes.guess_type(file.filename)[0]
2 changes: 1 addition & 1 deletion app/routes.py
Expand Up @@ -186,7 +186,7 @@ def new_piece(username, slug):
form = PieceForm()
if form.validate_on_submit():
piece_slug = slugify(form.name.data)
existing = Piece.query.filter_by(slug=slug).first()
existing = Piece.query.filter_by(slug=piece_slug).first()
if existing is not None:
flash(f"that name would need the path {username}/{slug}/{piece_slug}, which is taken")
return redirect(url_for('new_piece',
Expand Down

0 comments on commit 1e4f788

Please sign in to comment.