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

Sourcery Starbot ⭐ refactored ahmadfikrimasyhur/flask-admin #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
18 changes: 13 additions & 5 deletions examples/auth-flask-login/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,11 @@ class MyAdminIndexView(admin.AdminIndexView):

@expose('/')
def index(self):
if not login.current_user.is_authenticated:
return redirect(url_for('.login_view'))
return super(MyAdminIndexView, self).index()
return (
super(MyAdminIndexView, self).index()
if login.current_user.is_authenticated
else redirect(url_for('.login_view'))
)
Comment on lines -111 to +115
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function MyAdminIndexView.index refactored with the following changes:


@expose('/login/', methods=('GET', 'POST'))
def login_view(self):
Expand Down Expand Up @@ -201,8 +203,14 @@ def build_sample_db():
user.first_name = first_names[i]
user.last_name = last_names[i]
user.login = user.first_name.lower()
user.email = user.login + "@example.com"
user.password = generate_password_hash(''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10)))
user.email = f"{user.login}@example.com"
user.password = generate_password_hash(
''.join(
random.choice(string.ascii_lowercase + string.digits)
for _ in range(10)
)
)

Comment on lines -204 to +213
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_sample_db refactored with the following changes:

db.session.add(user)

db.session.commit()
Expand Down
8 changes: 6 additions & 2 deletions examples/auth/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,12 @@ def build_sample_db():
]

for i in range(len(first_names)):
tmp_email = first_names[i].lower() + "." + last_names[i].lower() + "@example.com"
tmp_pass = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10))
tmp_email = f"{first_names[i].lower()}.{last_names[i].lower()}@example.com"
tmp_pass = ''.join(
random.choice(string.ascii_lowercase + string.digits)
for _ in range(10)
)

Comment on lines -141 to +146
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_sample_db refactored with the following changes:

user_datastore.create_user(
first_name=first_names[i],
last_name=last_names[i],
Expand Down
2 changes: 1 addition & 1 deletion examples/auth/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

# Create in-memory database
DATABASE_FILE = 'sample_db.sqlite'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_FILE
SQLALCHEMY_DATABASE_URI = f'sqlite:///{DATABASE_FILE}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 6-6 refactored with the following changes:

SQLALCHEMY_ECHO = True

# Flask-Security config
Expand Down
7 changes: 2 additions & 5 deletions examples/babel/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@

@babel.localeselector
def get_locale():
override = request.args.get('lang')

if override:
if override := request.args.get('lang'):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_locale refactored with the following changes:

session['lang'] = override

return session.get('lang', 'en')
Expand Down Expand Up @@ -58,7 +56,7 @@ def __unicode__(self):
# Flask views
@app.route('/')
def index():
tmp = u"""
return u"""
Comment on lines -61 to +59
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function index refactored with the following changes:

<p><a href="/admin/?lang=en">Click me to get to Admin! (English)</a></p>
<p><a href="/admin/?lang=cs">Click me to get to Admin! (Czech)</a></p>
<p><a href="/admin/?lang=de">Click me to get to Admin! (German)</a></p>
Expand All @@ -71,7 +69,6 @@ def index():
<p><a href="/admin/?lang=zh_CN">Click me to get to Admin! (Chinese - Simplified)</a></p>
<p><a href="/admin/?lang=zh_TW">Click me to get to Admin! (Chinese - Traditional)</a></p>
"""
return tmp

if __name__ == '__main__':
# Create admin
Expand Down
4 changes: 2 additions & 2 deletions examples/bootstrap4/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ def build_sample_db():

for i in range(len(first_names)):
user = User()
user.name = first_names[i] + " " + last_names[i]
user.email = first_names[i].lower() + "@example.com"
user.name = f"{first_names[i]} {last_names[i]}"
user.email = f"{first_names[i].lower()}@example.com"
Comment on lines -95 to +96
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_sample_db refactored with the following changes:

db.session.add(user)

sample_text = [
Expand Down
4 changes: 2 additions & 2 deletions examples/custom-layout/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ def build_sample_db():

for i in range(len(first_names)):
user = User()
user.name = first_names[i] + " " + last_names[i]
user.email = first_names[i].lower() + "@example.com"
user.name = f"{first_names[i]} {last_names[i]}"
user.email = f"{first_names[i].lower()}@example.com"
Comment on lines -89 to +90
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_sample_db refactored with the following changes:

db.session.add(user)

sample_text = [
Expand Down
29 changes: 16 additions & 13 deletions examples/forms-files-images/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
# add WYSIWYG class to existing classes
existing_classes = kwargs.pop('class', '') or kwargs.pop('class_', '')
kwargs['class'] = '{} {}'.format(existing_classes, "ckeditor")
kwargs['class'] = f'{existing_classes} ckeditor'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CKTextAreaWidget.__call__ refactored with the following changes:

return super(CKTextAreaWidget, self).__call__(field, **kwargs)


Expand Down Expand Up @@ -144,12 +144,15 @@ class FileView(sqla.ModelView):


class ImageView(sqla.ModelView):
def _list_thumbnail(view, context, model, name):
if not model.path:
return ''

return Markup('<img src="%s">' % url_for('static',
filename=form.thumbgen_filename(model.path)))
def _list_thumbnail(self, context, model, name):
return (
Markup(
'<img src="%s">'
% url_for('static', filename=form.thumbgen_filename(model.path))
)
if model.path
else ''
)
Comment on lines -147 to +155
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ImageView._list_thumbnail refactored with the following changes:


column_formatters = {
'path': _list_thumbnail
Expand Down Expand Up @@ -256,9 +259,9 @@ def build_sample_db():
user = User()
user.first_name = first_names[i]
user.last_name = last_names[i]
user.email = user.first_name.lower() + "@example.com"
tmp = ''.join(random.choice(string.digits) for i in range(10))
user.phone = "(" + tmp[0:3] + ") " + tmp[3:6] + " " + tmp[6::]
user.email = f"{user.first_name.lower()}@example.com"
tmp = ''.join(random.choice(string.digits) for _ in range(10))
user.phone = "(" + tmp[:3] + ") " + tmp[3:6] + " " + tmp[6::]
Comment on lines -259 to +264
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_sample_db refactored with the following changes:

user.city = locations[i][0]
user.country = locations[i][1]
db.session.add(user)
Expand All @@ -267,13 +270,13 @@ def build_sample_db():
for name in images:
image = Image()
image.name = name
image.path = name.lower() + ".jpg"
image.path = f"{name.lower()}.jpg"
db.session.add(image)

for i in [1, 2, 3]:
file = File()
file.name = "Example " + str(i)
file.path = "example_" + str(i) + ".pdf"
file.name = f"Example {str(i)}"
file.path = f"example_{str(i)}.pdf"
db.session.add(file)

sample_text = "<h2>This is a test</h2>" + \
Expand Down
2 changes: 1 addition & 1 deletion examples/peewee/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class UserInfo(BaseModel):
user = peewee.ForeignKeyField(User)

def __unicode__(self):
return '%s - %s' % (self.key, self.value)
return f'{self.key} - {self.value}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function UserInfo.__unicode__ refactored with the following changes:



class Post(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion examples/pymongo/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def get_list(self, *args, **kwargs):
users = db.user.find(query, fields=('name',))

# Contribute user names to the models
users_map = dict((x['_id'], x['name']) for x in users)
users_map = {x['_id']: x['name'] for x in users}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TweetView.get_list refactored with the following changes:


for item in data:
item['user_name'] = users_map.get(item['user_id'])
Expand Down
2 changes: 1 addition & 1 deletion examples/sqla-association_proxy/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __init__(self, keyword=None):
self.keyword = keyword

def __repr__(self):
return 'Keyword(%s)' % repr(self.keyword)
return f'Keyword({repr(self.keyword)})'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Keyword.__repr__ refactored with the following changes:



class UserAdmin(sqla.ModelView):
Expand Down
4 changes: 1 addition & 3 deletions examples/sqla-custom-inline-forms/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,7 @@ def postprocess_form(self, form_class):
return form_class

def on_model_change(self, form, model):
file_data = request.files.get(form.upload.name)

if file_data:
if file_data := request.files.get(form.upload.name):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InlineModelForm.on_model_change refactored with the following changes:

model.path = secure_filename(file_data.filename)
file_data.save(op.join(base_path, model.path))

Expand Down
4 changes: 1 addition & 3 deletions examples/sqla/admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@

@babel.localeselector
def get_locale():
override = request.args.get('lang')

if override:
if override := request.args.get('lang'):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_locale refactored with the following changes:

session['lang'] = override

return session.get('lang', 'en')
Expand Down
2 changes: 1 addition & 1 deletion examples/sqla/admin/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@

# Create in-memory database
DATABASE_FILE = 'sample_db.sqlite'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_FILE
SQLALCHEMY_DATABASE_URI = f'sqlite:///{DATABASE_FILE}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 10-10 refactored with the following changes:

SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
8 changes: 4 additions & 4 deletions examples/sqla/admin/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def build_sample_db():
user.type = random.choice(AVAILABLE_USER_TYPES)[0]
user.first_name = first_names[i]
user.last_name = last_names[i]
user.email = first_names[i].lower() + "@example.com"
user.email = f"{first_names[i].lower()}@example.com"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_sample_db refactored with the following changes:


user.website = "https://www.example.com"
user.ip_address = "127.0.0.1"
Expand Down Expand Up @@ -107,7 +107,7 @@ def build_sample_db():
entry = random.choice(sample_text) # select text at random
post = Post()
post.user = user
post.title = "{}'s opinion on {}".format(user.first_name, entry['title'])
post.title = f"{user.first_name}'s opinion on {entry['title']}"
post.text = entry['content']
post.background_color = random.choice(["#cccccc", "red", "lightblue", "#0f0"])
tmp = int(1000 * random.random()) # random number between 0 and 1000:
Expand All @@ -120,12 +120,12 @@ def build_sample_db():
db.session.add(trunk)
for i in range(5):
branch = Tree()
branch.name = "Branch " + str(i + 1)
branch.name = f"Branch {str(i + 1)}"
branch.parent = trunk
db.session.add(branch)
for j in range(5):
leaf = Tree()
leaf.name = "Leaf " + str(j + 1)
leaf.name = f"Leaf {str(j + 1)}"
leaf.parent = branch
db.session.add(leaf)

Expand Down
9 changes: 6 additions & 3 deletions examples/sqla/admin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# Flask views
@app.route('/')
def index():
tmp = u"""
return u"""
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function index refactored with the following changes:

<p><a href="/admin/?lang=en">Click me to get to Admin! (English)</a></p>
<p><a href="/admin/?lang=cs">Click me to get to Admin! (Czech)</a></p>
<p><a href="/admin/?lang=de">Click me to get to Admin! (German)</a></p>
Expand All @@ -28,7 +28,6 @@ def index():
<p><a href="/admin/?lang=zh_CN">Click me to get to Admin! (Chinese - Simplified)</a></p>
<p><a href="/admin/?lang=zh_TW">Click me to get to Admin! (Chinese - Traditional)</a></p>
"""
return tmp


@app.route('/favicon.ico')
Expand All @@ -50,7 +49,11 @@ def operation(self):

# Customized User model admin
def phone_number_formatter(view, context, model, name):
return Markup("<nobr>{}</nobr>".format(model.phone_number)) if model.phone_number else None
return (
Markup(f"<nobr>{model.phone_number}</nobr>")
if model.phone_number
else None
)
Comment on lines -53 to +56
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function phone_number_formatter refactored with the following changes:



def is_numberic_validator(form, field):
Expand Down
19 changes: 11 additions & 8 deletions examples/sqla/admin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,21 @@ class User(db.Model):
def phone_number(self):
if self.dialling_code and self.local_phone_number:
number = str(self.local_phone_number)
return "+{} ({}) {} {} {}".format(self.dialling_code, number[0], number[1:3], number[3:6], number[6::])
return f"+{self.dialling_code} ({number[0]}) {number[1:3]} {number[3:6]} {number[6::]}"

Comment on lines -57 to +58
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function User.phone_number refactored with the following changes:

return

@phone_number.expression
def phone_number(cls):
return sql.operators.ColumnOperators.concat(cast(cls.dialling_code, db.String), cls.local_phone_number)
def phone_number(self):
return sql.operators.ColumnOperators.concat(
cast(self.dialling_code, db.String), self.local_phone_number
)
Comment on lines -61 to +65
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function User.phone_number refactored with the following changes:


def __str__(self):
return "{}, {}".format(self.last_name, self.first_name)
return f"{self.last_name}, {self.first_name}"
Comment on lines -65 to +68
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function User.__str__ refactored with the following changes:


def __repr__(self):
return "{}: {}".format(self.id, self.__str__())
return f"{self.id}: {self.__str__()}"
Comment on lines -68 to +71
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function User.__repr__ refactored with the following changes:



# Create M2M table
Expand All @@ -90,15 +93,15 @@ class Post(db.Model):
tags = db.relationship('Tag', secondary=post_tags_table)

def __str__(self):
return "{}".format(self.title)
return f"{self.title}"
Comment on lines -93 to +96
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Post.__str__ refactored with the following changes:



class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(64), unique=True)

def __str__(self):
return "{}".format(self.name)
return f"{self.name}"
Comment on lines -101 to +104
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Tag.__str__ refactored with the following changes:



class Tree(db.Model):
Expand All @@ -110,4 +113,4 @@ class Tree(db.Model):
parent = db.relationship('Tree', remote_side=[id], backref='children')

def __str__(self):
return "{}".format(self.name)
return f"{self.name}"
Comment on lines -113 to +116
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Tree.__str__ refactored with the following changes:

16 changes: 11 additions & 5 deletions flask_admin/_backwards.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ def get_property(obj, name, old_name, default=None):
Default value
"""
if hasattr(obj, old_name):
warnings.warn('Property %s is obsolete, please use %s instead' %
(old_name, name), stacklevel=2)
warnings.warn(
f'Property {old_name} is obsolete, please use {name} instead',
stacklevel=2,
)

Comment on lines -32 to +36
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_property refactored with the following changes:

return getattr(obj, old_name)

return getattr(obj, name, default)
Expand All @@ -40,7 +43,7 @@ class ObsoleteAttr(object):
def __init__(self, new_name, old_name, default):
self.new_name = new_name
self.old_name = old_name
self.cache = '_cache_' + new_name
self.cache = f'_cache_{new_name}'
Comment on lines -43 to +46
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ObsoleteAttr.__init__ refactored with the following changes:

self.default = default

def __get__(self, obj, objtype=None):
Expand All @@ -53,8 +56,11 @@ def __get__(self, obj, objtype=None):

# Check if there's old attribute
if hasattr(obj, self.old_name):
warnings.warn('Property %s is obsolete, please use %s instead' %
(self.old_name, self.new_name), stacklevel=2)
warnings.warn(
f'Property {self.old_name} is obsolete, please use {self.new_name} instead',
stacklevel=2,
)

Comment on lines -56 to +63
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ObsoleteAttr.__get__ refactored with the following changes:

return getattr(obj, self.old_name)

# Return default otherwise
Expand Down
10 changes: 2 additions & 8 deletions flask_admin/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@
filter_list = lambda f, l: list(filter(f, l))

def as_unicode(s):
if isinstance(s, bytes):
return s.decode('utf-8')

return str(s)
return s.decode('utf-8') if isinstance(s, bytes) else str(s)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function as_unicode refactored with the following changes:


def csv_encode(s):
''' Returns unicode string expected by Python 3's csv module '''
Expand All @@ -50,10 +47,7 @@ def csv_encode(s):
filter_list = filter

def as_unicode(s):
if isinstance(s, str):
return s.decode('utf-8')

return unicode(s)
return s.decode('utf-8') if isinstance(s, str) else unicode(s)
Comment on lines -53 to +50
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function as_unicode refactored with the following changes:


def csv_encode(s):
''' Returns byte string expected by Python 2's csv module '''
Expand Down
Loading