Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blackened all code #95

Merged
merged 14 commits into from
Aug 20, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ imgee/static/test_uploads
*.bak
instance/production.env.sh
imgee/static/gen
.pytest_cache
46 changes: 46 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/lucasmbrown/mirrors-autoflake
rev: v1.3
hooks:
- id: autoflake
args: ['--in-place', '--remove-all-unused-imports', '--ignore-init-module-imports', '--remove-unused-variable']
- repo: https://github.com/pre-commit/mirrors-isort
rev: v4.3.21
hooks:
- id: isort
additional_dependencies:
- toml
- repo: https://github.com/ambv/black
rev: master
hooks:
- id: black
language_version: python3.6
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.3
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-byte-order-marker
- id: check-case-conflict
- id: check-executables-have-shebangs
- id: check-json
- id: check-merge-conflict
- id: check-xml
- id: fix-encoding-pragma
- id: flake8
additional_dependencies:
- toml
- flake8-assertive
- flake8-blind-except
- flake8-builtins
- flake8-coding
- flake8-comprehensions
- flake8-isort
- flake8-logging-format
- flake8-mutable
- flake8-print
- pep8-naming
19 changes: 12 additions & 7 deletions imgee/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@

import os.path

from flask import Flask, redirect, url_for
from flask_migrate import Migrate
from werkzeug.utils import secure_filename

from flask import Flask, redirect, url_for
from flask_lastuser import Lastuser
from flask_lastuser.sqlalchemy import UserManager
from baseframe import baseframe, assets, Version
from flask_migrate import Migrate

from baseframe import Version, assets, baseframe
import coaster.app

from ._version import __version__

version = Version(__version__)
Expand All @@ -20,9 +22,9 @@

assets['imgee.css'][version] = 'css/app.css'

from . import models, views
from .models import db
from .tasks import TaskRegistry
from . import models, views # NOQA # isort:skip
from .models import db # NOQA # isort:skip
from .tasks import TaskRegistry # NOQA # isort:skip

registry = TaskRegistry()

Expand All @@ -39,7 +41,10 @@
def error403(error):
return redirect(url_for('login'))


if app.config.get('MEDIA_DOMAIN', '').lower().startswith(('http://', 'https://')):
app.config['MEDIA_DOMAIN'] = app.config['MEDIA_DOMAIN'].split(':', 1)[1]

app.upload_folder = os.path.join(app.static_folder, secure_filename(app.config.get('UPLOADED_FILES_DIR')))
app.upload_folder = os.path.join(
app.static_folder, secure_filename(app.config.get('UPLOADED_FILES_DIR'))
)
7 changes: 6 additions & 1 deletion imgee/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
__all__ = ['__version__', '__version_info__']

__version__ = '0.2.0'
__version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')])
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace('-', '.', 1).split('.')
]
)
28 changes: 19 additions & 9 deletions imgee/forms.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
# -*- coding: utf-8 -*-

from coaster.utils import make_name
from baseframe.forms import Form
from wtforms.validators import Required, ValidationError, Length
from wtforms import (FileField, TextField, HiddenField, SelectField)
from wtforms import FileField, HiddenField, SelectField, TextField
from wtforms.validators import Length, Required, ValidationError

from baseframe.forms import Form
from coaster.utils import make_name
from imgee import app

from .models import Label
from .utils import is_file_allowed


def valid_file(form, field):
if not is_file_allowed(field.data.stream, field.data.mimetype, field.data.filename):
raise ValidationError("Sorry, unknown image format. Please try uploading another file.")
raise ValidationError(
"Sorry, unknown image format. Please try uploading another file."
)


class UploadImageForm(Form):
file = FileField("File", validators=[Required(), valid_file])
file_obj = FileField("File", validators=[Required(), valid_file])
iambibhas marked this conversation as resolved.
Show resolved Hide resolved


class DeleteImageForm(Form):
Expand All @@ -41,15 +44,22 @@ def label_doesnt_exist(form, field):
profile_id = form.profile_id.data
label_name = make_name(field.data)
if label_name in reserved_words():
raise ValidationError('"%s" is reserved and cannot be used as a label. Please try another name.' % label_name)
raise ValidationError(
'"%s" is reserved and cannot be used as a label. Please try another name.'
% label_name
)

exists = Label.query.filter_by(profile_id=profile_id, name=label_name).first()
if exists:
raise ValidationError('Label "%s" already exists. Please try another name.' % field.data)
raise ValidationError(
'Label "%s" already exists. Please try another name.' % field.data
)


class CreateLabelForm(Form):
label = TextField('Label', validators=[Required(), Length(max=250), label_doesnt_exist])
label = TextField(
'Label', validators=[Required(), Length(max=250), label_doesnt_exist]
)
profile_id = HiddenField('profile_id')


Expand Down
9 changes: 5 additions & 4 deletions imgee/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-

from flask_sqlalchemy import SQLAlchemy

from imgee import app

db = SQLAlchemy(app)

from imgee.models.user import *
from imgee.models.stored_file import *
from imgee.models.thumbnail import *
from imgee.models.profile import *
from imgee.models.user import * # NOQA # isort:skip
from imgee.models.stored_file import * # NOQA # isort:skip
from imgee.models.thumbnail import * # NOQA # isort:skip
from imgee.models.profile import * # NOQA # isort:skip
14 changes: 10 additions & 4 deletions imgee/models/profile.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
from coaster.sqlalchemy import BaseNameMixin
# -*- coding: utf-8 -*-
from flask_lastuser.sqlalchemy import ProfileMixin

from coaster.sqlalchemy import BaseNameMixin

from . import db


class Profile(ProfileMixin, BaseNameMixin, db.Model):
__tablename__ = 'profile'

userid = db.Column(db.Unicode(22), nullable=False, unique=True)
stored_files = db.relationship('StoredFile',
backref=db.backref('profile'), lazy='dynamic',
cascade='all, delete-orphan')
stored_files = db.relationship(
'StoredFile',
backref=db.backref('profile'),
lazy='dynamic',
cascade='all, delete-orphan',
)

def permissions(self, user, inherited=None):
perms = super(Profile, self).permissions(user, inherited)
Expand Down
53 changes: 31 additions & 22 deletions imgee/models/stored_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
from flask import url_for

from coaster.sqlalchemy import BaseNameMixin, BaseScopedNameMixin

from .. import app
from ..utils import guess_extension, newid
from . import db
from ..utils import newid, guess_extension


image_labels = db.Table('image_labels',
image_labels = db.Table(
'image_labels',
db.Column('label_id', db.Integer, db.ForeignKey('label.id'), nullable=False),
db.Column('stored_file_id', db.Integer, db.ForeignKey('stored_file.id'), nullable=False),
db.Column(
'stored_file_id', db.Integer, db.ForeignKey('stored_file.id'), nullable=False
),
)


Expand All @@ -18,9 +21,12 @@ class Label(BaseScopedNameMixin, db.Model):
Labels are used to categorize images for easy discovery.
An image may have zero or more labels.
"""

__tablename__ = 'label'
profile_id = db.Column(None, db.ForeignKey('profile.id'), nullable=False)
profile = db.relationship('Profile', backref=db.backref('labels', cascade='all, delete-orphan'))
profile = db.relationship(
'Profile', backref=db.backref('labels', cascade='all, delete-orphan')
)
parent = db.synonym('profile')

def __repr__(self):
Expand All @@ -34,6 +40,7 @@ class StoredFile(BaseNameMixin, db.Model):
copy is stored locally for thumbnail generation. Files are always
served from S3.
"""

__tablename__ = 'stored_file'
profile_id = db.Column(None, db.ForeignKey('profile.id'), nullable=False)
size = db.Column(db.BigInteger, default=0) # in bytes
Expand All @@ -42,10 +49,14 @@ class StoredFile(BaseNameMixin, db.Model):
mimetype = db.Column(db.Unicode(32), nullable=False)
orig_extn = db.Column(db.Unicode(15), nullable=True)
no_previews = db.Column(db.Boolean, default=False, nullable=False)
thumbnails = db.relationship('Thumbnail', backref='stored_file',
cascade='all, delete-orphan')
labels = db.relationship('Label', secondary='image_labels',
backref=db.backref('stored_files', lazy='dynamic'))
thumbnails = db.relationship(
'Thumbnail', backref='stored_file', cascade='all, delete-orphan'
)
labels = db.relationship(
'Label',
secondary='image_labels',
backref=db.backref('stored_files', lazy='dynamic'),
)

def __init__(self, **kwargs):
super(StoredFile, self).__init__(**kwargs)
Expand All @@ -64,21 +75,19 @@ def filename(self):
return self.name + self.extn

def dict_data(self):
return dict(
title=self.title,
uploaded=self.created_at.isoformat() + 'Z',
filesize=app.jinja_env.filters['filesizeformat'](self.size),
imgsize=u'%s×%s px' % (self.width, self.height),
url=url_for('view_image', profile=self.profile.name, image=self.name),
thumb_url=url_for('get_image', image=self.name, size=app.config.get('THUMBNAIL_SIZE'))
)
return {
'title': self.title,
'uploaded': self.created_at.isoformat() + 'Z',
'filesize': app.jinja_env.filters['filesizeformat'](self.size),
'imgsize': u'%s×%s px' % (self.width, self.height),
'url': url_for('view_image', profile=self.profile.name, image=self.name),
'thumb_url': url_for(
'get_image', image=self.name, size=app.config.get('THUMBNAIL_SIZE')
),
}

def add_labels(self, labels):
status = {
'+': [],
'-': [],
'': []
}
status = {'+': [], '-': [], '': []}

new_labels = set(labels)
old_labels = set(self.labels)
Expand Down
4 changes: 3 additions & 1 deletion imgee/models/thumbnail.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-

from coaster.sqlalchemy import BaseMixin
from . import db

from ..utils import newid
from . import db


class Thumbnail(BaseMixin, db.Model):
Expand All @@ -12,6 +13,7 @@ class Thumbnail(BaseMixin, db.Model):
image types. Unrecognized types are always served as the original
file.
"""

__tablename__ = 'thumbnail'

name = db.Column(db.Unicode(64), nullable=False, unique=True, index=True)
Expand Down
7 changes: 5 additions & 2 deletions imgee/models/user.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-

from flask import url_for
from flask_lastuser.sqlalchemy import UserBase
from werkzeug.utils import cached_property

from flask_lastuser.sqlalchemy import UserBase

from . import db
from .profile import Profile

Expand All @@ -17,7 +19,8 @@ def profile(self):
@cached_property
def profiles(self):
return [self.profile] + Profile.query.filter(
Profile.userid.in_(self.organizations_owned_ids())).order_by(Profile.title).all()
Profile.userid.in_(self.organizations_owned_ids())
).order_by(Profile.title).all()

@cached_property
def profile_url(self):
Expand Down
2 changes: 1 addition & 1 deletion imgee/static/img/imgee.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 8 additions & 8 deletions imgee/static/js/dropzone-amd-module.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,19 +162,19 @@ Emitter.prototype.hasListeners = function(event){
/*
#
# More info at [www.dropzonejs.com](http://www.dropzonejs.com)
#
# Copyright (c) 2012, Matias Meno
#
#
# Copyright (c) 2012, Matias Meno
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Expand Down Expand Up @@ -202,9 +202,9 @@ Emitter.prototype.hasListeners = function(event){

/*
This is a list of all available events you can register on a dropzone object.

You can register an event handler like this:

dropzone.on("dragEnter", function() { });
*/

Expand Down Expand Up @@ -1184,4 +1184,4 @@ Emitter.prototype.hasListeners = function(event){
}).call(this);

return module.exports;
}));
}));
Loading