1
1
Fork 0

Image store - organization of image endpoints

dev
Jan Kužílek 5 years ago
parent 0cdd93606f
commit e596ee6ff1

@ -3,6 +3,7 @@ import os
from flask import (Blueprint, abort, current_app, flash, redirect, from flask import (Blueprint, abort, current_app, flash, redirect,
render_template, request, send_from_directory, url_for) render_template, request, send_from_directory, url_for)
from yadc.models import IMAGE_STORE
bp = Blueprint('main', __name__) bp = Blueprint('main', __name__)
@ -11,7 +12,7 @@ def index():
return redirect(url_for('post.posts')) return redirect(url_for('post.posts'))
@bp.route('/i/<path:path>') @bp.route('/i/<path:path>')
def uploaded_img(path, store='img', exten=None): def uploaded_img(path, store=IMAGE_STORE.image, exten=None):
ext = os.path.splitext(path)[1] ext = os.path.splitext(path)[1]
if exten is not None and ext.split('.')[1] != exten: if exten is not None and ext.split('.')[1] != exten:
@ -20,25 +21,25 @@ def uploaded_img(path, store='img', exten=None):
filename = path.split('/')[0].split('.')[0] filename = path.split('/')[0].split('.')[0]
# print(os.path.join(current_app.config.get('POST_UPLOADS'), store, "{}{}".format(filename, ext))) # print(os.path.join(current_app.config.get('POST_UPLOADS'), store, "{}{}".format(filename, ext)))
return send_from_directory( return send_from_directory(
os.path.join(current_app.config.get('POST_UPLOADS'), store), os.path.join(current_app.config.get('POST_UPLOADS'), store.value),
"{}{}".format(filename, ext) f"{filename}{ext}"
) )
@bp.route('/jpeg/<path:path>') @bp.route('/jpeg/<path:path>')
def uploaded_jpeg(*args, **kwargs): def uploaded_jpeg(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='jpeg', exten='jpg') return uploaded_img(*args, **kwargs, store=IMAGE_STORE.jpeg, exten='jpg')
@bp.route('/sample/<path:path>') @bp.route('/sample/<path:path>')
def uploaded_sample(*args, **kwargs): def uploaded_sample(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='sample', exten='jpg') return uploaded_img(*args, **kwargs, store=IMAGE_STORE.sample, exten='jpg')
@bp.route('/bigthumb/<path:path>') @bp.route('/bigthumb/<path:path>')
def uploaded_big_thumb(*args, **kwargs): def uploaded_big_thumb(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='thumb_big', exten='jpg') return uploaded_img(*args, **kwargs, store=IMAGE_STORE.thumb_big, exten='jpg')
@bp.route('/thumb/<path:path>') @bp.route('/thumb/<path:path>')
def uploaded_smol_thumb(*args, **kwargs): def uploaded_smol_thumb(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='thumb', exten='jpg') return uploaded_img(*args, **kwargs, store=IMAGE_STORE.thumb_smol, exten='jpg')
# @bp.route('/threads') # @bp.route('/threads')

@ -9,7 +9,7 @@ from sqlalchemy.orm import aliased
from yadc import db from yadc import db
from yadc.forms import UploadForm, CommentForm, PostForm from yadc.forms import UploadForm, CommentForm, PostForm
from yadc.models import FILETYPE, RATING, POST_STATUS, Post, Tag, Comment, moderator_required from yadc.models import FILETYPE, RATING, POST_STATUS, IMAGE_STORE, Post, Tag, Comment, moderator_required
from yadc.utils import query_replace, flasherrors, session_rating from yadc.utils import query_replace, flasherrors, session_rating
bp = Blueprint('post', __name__) bp = Blueprint('post', __name__)
@ -192,21 +192,21 @@ def posts_api():
source=p.source, source=p.source,
md5=p.md5, md5=p.md5,
file_size=p.filesize, file_size=p.filesize,
file_url=p.url(path=p.file_uri, endpoint='img'), file_url=p.url(path=p.file_uri, endpoint=IMAGE_STORE.image),
preview_url=p.url(path=p.file_uri, endpoint='thumb_big'), preview_url=p.url(path=p.file_uri, endpoint=IMAGE_STORE.thumb_big),
preview_width=0, preview_width=0,
preview_height=0, preview_height=0,
actual_preview_width=0, actual_preview_width=0,
actual_preview_height=0, actual_preview_height=0,
sample_url=p.url(path=p.file_uri, endpoint='sample'), sample_url=p.url(path=p.file_uri, endpoint=IMAGE_STORE.sample),
sample_width=0, sample_width=0,
sample_height=0, sample_height=0,
sample_file_size=0, sample_file_size=0,
jpeg_url=p.url(path=p.file_uri, endpoint='img') if p.filetype.is_jpeg else p.url(path=p.file_uri, endpoint='jpeg'), jpeg_url=p.url(path=p.file_uri, endpoint=(IMAGE_STORE.image if p.filetype.is_jpeg else IMAGE_STORE.jpeg)),
jpeg_width=0, jpeg_width=0,
jpeg_height=0, jpeg_height=0,

@ -68,6 +68,13 @@ class TAG_CATEGORY(enum.Enum):
# visible = 0 # visible = 0
# deleted = 2 # deleted = 2
class IMAGE_STORE(enum.Enum):
image = 'img'
jpeg = 'jpeg'
sample = 'sample'
thumb_big = 'thumb_big'
thumb_smol = 'thumb'
class TimestampMixin(object): class TimestampMixin(object):
created = db.Column(UtcDateTime, nullable=False, server_default=utcnow()) created = db.Column(UtcDateTime, nullable=False, server_default=utcnow())
updated = db.Column(UtcDateTime, nullable=False, onupdate=utcnow(), server_default=utcnow()) updated = db.Column(UtcDateTime, nullable=False, onupdate=utcnow(), server_default=utcnow())
@ -158,10 +165,6 @@ def admin_required(func):
return func(*args, **kwargs) return func(*args, **kwargs)
return dec_view return dec_view
# class UserPreferences(db.Model):
# user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
# user = db.relationship('User', backref=db.backref('profile', uselist=False))
post_tags = db.Table('post_tags', db.metadata, post_tags = db.Table('post_tags', db.metadata,
db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
@ -187,21 +190,14 @@ class Post(TimestampMixin, db.Model):
approver_id = db.Column(db.Integer, db.ForeignKey('user.id')) approver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
approver = db.relationship('User', backref=db.backref('approved_posts', lazy=True), foreign_keys=[approver_id]) approver = db.relationship('User', backref=db.backref('approved_posts', lazy=True), foreign_keys=[approver_id])
#tags = db.relationship('Tag', secondary=post_tags, back_populates='posts')
tags = db.relationship('Tag', secondary=post_tags, backref=db.backref('posts')) tags = db.relationship('Tag', secondary=post_tags, backref=db.backref('posts'))
# parent_id = db.Column(db.Integer, db.ForeignKey('post.id'))
# parent = db.relationship('Post', backref=db.backref('children', lazy=True), foreign_keys=[parent_id])
# def __init__(self, **kwargs): # def __init__(self, **kwargs):
# super().__init__(**kwargs) # super().__init__(**kwargs)
# # self.md5 = hashlib.md5(file.data.getbuffer()).hexdigest()
# # self.filetype = FILETYPE[file.mimetype.split('/')[1]]
# # with Image.open(file.data) as im:
# # self.width, self.height = im.width, im.height
# # self.filesize = file.data.getbuffer().nbytes
# # self.origin_filename = file.filename
# self.generate_image_files() # self.generate_image_files()
@property @property
@ -251,31 +247,31 @@ class Post(TimestampMixin, db.Model):
@property @property
def image_files(self): def image_files(self):
return dict( return dict(
# image=os.path.join(current_app.config.get('POST_UPLOADS'), 'img', "{}.{}".format(self.md5, 'jpg' if self.filetype is FILETYPE.jpeg else 'png')), image=os.path.join(current_app.config.get('POST_UPLOADS'), IMAGE_STORE.image.value, f"{path}.{self.filetype.file_ext}"),
image=os.path.join(current_app.config.get('POST_UPLOADS'), 'img', "{}.{}".format(self.md5, self.filetype.file_ext)), jpeg=(os.path.join(current_app.config.get('POST_UPLOADS'), IMAGE_STORE.jpeg.value, f"{self.md5}.jpg") if not self.filetype.is_jpeg else None),
jpeg=(None if self.filetype.is_jpeg else os.path.join(current_app.config.get('POST_UPLOADS'), 'jpeg', "{}.{}".format(self.md5, 'jpg'))), sample=os.path.join(current_app.config.get('POST_UPLOADS'), IMAGE_STORE.sample.value, f"{self.md5}.jpg"),
sample=os.path.join(current_app.config.get('POST_UPLOADS'), 'sample', "{}.{}".format(self.md5, 'jpg')), thumb_big=os.path.join(current_app.config.get('POST_UPLOADS'), IMAGE_STORE.thumb_big.value, f"{self.md5}.jpg"),
thumb_big=os.path.join(current_app.config.get('POST_UPLOADS'), 'thumb_big', "{}.{}".format(self.md5, 'jpg')), thumb_smol=os.path.join(current_app.config.get('POST_UPLOADS'), IMAGE_STORE.thumb_smol.value, f"{self.md5}.jpg")
thumb_smol=os.path.join(current_app.config.get('POST_UPLOADS'), 'thumb', "{}.{}".format(self.md5, 'jpg'))
) )
def url(self, path, endpoint='img'): def url(self, path, endpoint=IMAGE_STORE.image):
if endpoint == 'img': store = {s.name:s for s in IMAGE_STORE}.get(endpoint, IMAGE_STORE.image) if not isinstance(endpoint, IMAGE_STORE) else endpoint
if store is IMAGE_STORE.image:
return url_for( return url_for(
'main.uploaded_img', 'main.uploaded_img',
path="{}.{}".format(path, self.filetype.file_ext) path=f"{path}.{self.filetype.file_ext}"
) )
elif endpoint == 'jpeg': elif store is IMAGE_STORE.jpeg:
return url_for( return url_for(
'main.uploaded_jpeg' if not self.filetype.is_jpeg else 'main.uploaded_img', 'main.uploaded_jpeg' if not self.filetype.is_jpeg else 'main.uploaded_img',
path="{}.{}".format(path,'jpg') path=f"{path}.jpg"
) )
elif endpoint == 'sample': elif store is IMAGE_STORE.sample:
return url_for('main.uploaded_sample', path="{}.{}".format(path,'jpg')) return url_for('main.uploaded_sample', path=f"{path}.jpg")
elif endpoint == 'thumb_big': elif store is IMAGE_STORE.thumb_big:
return url_for('main.uploaded_big_thumb', path="{}.{}".format(path,'jpg')) return url_for('main.uploaded_big_thumb', path=f"{path}.jpg")
elif endpoint == 'thumb': elif store is IMAGE_STORE.thumb_smol:
return url_for('main.uploaded_smol_thumb', path="{}.{}".format(path,'jpg')) return url_for('main.uploaded_smol_thumb', path=f"{path}.jpg")
@property @property
def file_uri(self): def file_uri(self):
@ -346,6 +342,4 @@ class Comment(TimestampMixin, db.Model):
def can_edit(self): def can_edit(self):
author = current_user == self.user author = current_user == self.user
moderator = current_user.is_moderator moderator = current_user.is_moderator
return author or moderator return author or moderator
# THINK ABOUT LAZY LOADING

@ -9,7 +9,7 @@
{% for post in posts.items %} {% for post in posts.items %}
<figure style="{{ post.flex }}"> <figure style="{{ post.flex }}">
<a href="{{ url_for('post.post_show', id=post.id) }}"> <a href="{{ url_for('post.post_show', id=post.id) }}">
<img src="{{ post.url(path=post.file_uri, endpoint='thumb') }}" srcset="{{ post.url(path=post.file_uri, endpoint='thumb') }} 512w, {{ post.url(path=post.file_uri, endpoint='thumb_big') }} 800w" alt=""> <!--sizes="(min-width: 513px) 1000w" --> <img src="{{ post.url(path=post.file_uri, endpoint='thumb_smol') }}" srcset="{{ post.url(path=post.file_uri, endpoint='thumb_smol') }} 512w, {{ post.url(path=post.file_uri, endpoint='thumb_big') }} 800w" alt=""> <!--sizes="(min-width: 513px) 1000w" -->
</a> </a>
</figure> </figure>
{% endfor %} {% endfor %}

Loading…
Cancel
Save