Skip to content

Commit

Permalink
Autoformat Python code with black (#324)
Browse files Browse the repository at this point in the history
* Add black to format Python code

* Reformat Python code with black

* Check code formatting during CI with black
  • Loading branch information
RevolutionTech authored Sep 1, 2019
1 parent ea0d76f commit 3c3e4b9
Show file tree
Hide file tree
Showing 105 changed files with 2,980 additions and 1,859 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ before_script:
- cp .env-sample .env

script:
- poetry run black . --check
- poetry run python manage.py migrate
- poetry run python manage.py collectstatic --no-input
- poetry run coverage run ./manage.py test
Expand Down
2 changes: 1 addition & 1 deletion accounts/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class AccountsConfig(AppConfig):

name = 'accounts'
name = "accounts"

def ready(self):
import accounts.signals
32 changes: 20 additions & 12 deletions accounts/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,43 @@

class GoogleOAuth2Login(GoogleOAuth2):

name = 'google-oauth2-login'
auth_operation = 'login'
name = "google-oauth2-login"
auth_operation = "login"

def setting(self, name, default=None):
return self.strategy.setting(name, default=default, backend=super(GoogleOAuth2Login, self))
return self.strategy.setting(
name, default=default, backend=super(GoogleOAuth2Login, self)
)


class GoogleOAuth2Register(GoogleOAuth2):

name = 'google-oauth2-register'
auth_operation = 'register'
name = "google-oauth2-register"
auth_operation = "register"

def setting(self, name, default=None):
return self.strategy.setting(name, default=default, backend=super(GoogleOAuth2Register, self))
return self.strategy.setting(
name, default=default, backend=super(GoogleOAuth2Register, self)
)


class FacebookOAuth2Login(FacebookOAuth2):

name = 'facebook-login'
auth_operation = 'login'
name = "facebook-login"
auth_operation = "login"

def setting(self, name, default=None):
return self.strategy.setting(name, default=default, backend=super(FacebookOAuth2Login, self))
return self.strategy.setting(
name, default=default, backend=super(FacebookOAuth2Login, self)
)


class FacebookOAuth2Register(FacebookOAuth2):

name = 'facebook-register'
auth_operation = 'register'
name = "facebook-register"
auth_operation = "register"

def setting(self, name, default=None):
return self.strategy.setting(name, default=default, backend=super(FacebookOAuth2Register, self))
return self.strategy.setting(
name, default=default, backend=super(FacebookOAuth2Register, self)
)
6 changes: 4 additions & 2 deletions accounts/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ def cache_using_pk(func):

@functools.wraps(func)
def wrapper(instance, *args, **kwargs):
cache_key = '{func_name}-{pk}'.format(func_name=func.__name__, pk=instance.pk)
return cache.get_or_set(cache_key, functools.partial(func, instance, *args, **kwargs))
cache_key = "{func_name}-{pk}".format(func_name=func.__name__, pk=instance.pk)
return cache.get_or_set(
cache_key, functools.partial(func, instance, *args, **kwargs)
)

return wrapper
6 changes: 3 additions & 3 deletions accounts/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@

def keys(request):
return {
'FB_APP_ID': settings.SOCIAL_AUTH_FACEBOOK_KEY,
'GA_TRACKING_CODE': settings.GA_TRACKING_CODE,
'JACO_API_KEY': settings.JACO_API_KEY,
"FB_APP_ID": settings.SOCIAL_AUTH_FACEBOOK_KEY,
"GA_TRACKING_CODE": settings.GA_TRACKING_CODE,
"JACO_API_KEY": settings.JACO_API_KEY,
}


Expand Down
13 changes: 7 additions & 6 deletions accounts/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@
def userfactory_factory(apps, has_password=True):
class UserFactory(factory.DjangoModelFactory):

_PASSWORD = 'abc123'
_PASSWORD = "abc123"

class Meta:
model = apps.get_model(settings.AUTH_USER_MODEL)

username = factory.Faker('user_name')
email = factory.LazyAttribute(lambda user: "{username}@gmail.com".format(username=user.username))
username = factory.Faker("user_name")
email = factory.LazyAttribute(
lambda user: "{username}@gmail.com".format(username=user.username)
)

if has_password:
password = factory.PostGenerationMethodCall('set_password', _PASSWORD)
password = factory.PostGenerationMethodCall("set_password", _PASSWORD)

return UserFactory

Expand All @@ -25,8 +27,7 @@ class Meta:


class UserAvatarFactory(factory.DjangoModelFactory):

class Meta:
model = django_apps.get_model('accounts', 'UserAvatar')
model = django_apps.get_model("accounts", "UserAvatar")

user = factory.SubFactory(UserFactory)
84 changes: 50 additions & 34 deletions accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@


class LoginAccountForm(AuthenticationForm):

def clean_username(self):
username = self.cleaned_data['username']
username = self.cleaned_data["username"]
return username.lower()


Expand All @@ -26,36 +25,40 @@ class RegisterAccountForm(UserCreationForm):
max_length=150,
validators=[
validators.RegexValidator(
r'^[a-z0-9.@+_-]+$',
r"^[a-z0-9.@+_-]+$",
(
'Enter a valid username. This value may contain only lowercase letters, '
'numbers and @/./+/-/_ characters.'
)
),
]
"Enter a valid username. This value may contain only lowercase letters, "
"numbers and @/./+/-/_ characters."
),
)
],
)
email = forms.EmailField(required=True)
subscribe_news = forms.BooleanField(
required=False, initial=True, label='Get exclusive updates before they\'re public'
required=False,
initial=True,
label="Get exclusive updates before they're public",
)

class Meta(UserCreationForm.Meta):
fields = ('username', 'email', 'password1', 'password2',)
fields = ("username", "email", "password1", "password2")

def clean_email(self):
email = self.cleaned_data['email']
email = self.cleaned_data["email"]

# Verify that there are no other users already with this email address
if User.objects.filter(email=email).exists():
raise forms.ValidationError(
"The email address {email} already belongs to an existing user on PerDiem.".format(email=email)
"The email address {email} already belongs to an existing user on PerDiem.".format(
email=email
)
)

return email

def save(self, commit=True):
user = super(RegisterAccountForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
Expand All @@ -67,13 +70,13 @@ class EditNameForm(forms.Form):
max_length=150,
validators=[
validators.RegexValidator(
r'^[a-z0-9.@+_-]+$',
r"^[a-z0-9.@+_-]+$",
(
'Enter a valid username. This value may contain only '
'lowercase letters, numbers and @/./+/-/_ characters.'
)
),
]
"Enter a valid username. This value may contain only "
"lowercase letters, numbers and @/./+/-/_ characters."
),
)
],
)
first_name = forms.CharField(max_length=30, required=False)
last_name = forms.CharField(max_length=30, required=False)
Expand All @@ -84,7 +87,7 @@ def __init__(self, user, *args, **kwargs):
super(EditNameForm, self).__init__(*args, **kwargs)

def clean_username(self):
username = self.cleaned_data['username']
username = self.cleaned_data["username"]
if User.objects.exclude(id=self.user.id).filter(username=username).exists():
raise forms.ValidationError("A user with that username already exists.")
return username
Expand All @@ -96,21 +99,25 @@ class EditAvatarForm(forms.Form):

def __init__(self, user, *args, **kwargs):
super(EditAvatarForm, self).__init__(*args, **kwargs)
self.fields['avatar'] = forms.ChoiceField(
choices=self.get_avatar_choices(user), required=False, widget=forms.RadioSelect
self.fields["avatar"] = forms.ChoiceField(
choices=self.get_avatar_choices(user),
required=False,
widget=forms.RadioSelect,
)

def get_avatar_choices(self, user):
user_avatars = UserAvatar.objects.filter(user=user)
return [('', 'Default',)] + [(avatar.id, avatar.get_provider_display(),) for avatar in user_avatars]
return [("", "Default")] + [
(avatar.id, avatar.get_provider_display()) for avatar in user_avatars
]

def clean_avatar(self):
avatar_id = self.cleaned_data['avatar']
avatar_id = self.cleaned_data["avatar"]
if avatar_id:
return UserAvatar.objects.get(id=avatar_id)

def clean_custom_avatar(self):
custom_avatar = self.cleaned_data['custom_avatar']
custom_avatar = self.cleaned_data["custom_avatar"]
if custom_avatar and custom_avatar._size > settings.MAXIMUM_AVATAR_SIZE:
raise forms.ValidationError("Image file too large (2MB maximum).")
return custom_avatar
Expand All @@ -119,30 +126,39 @@ def clean_custom_avatar(self):
class EmailPreferencesForm(forms.Form):

email = forms.EmailField()
subscription_news = forms.BooleanField(required=False, label='Let me know about new updates and happenings')
subscription_artup = forms.BooleanField(required=False, label='Subscribe to updates from artists you invest in')
subscription_news = forms.BooleanField(
required=False, label="Let me know about new updates and happenings"
)
subscription_artup = forms.BooleanField(
required=False, label="Subscribe to updates from artists you invest in"
)
subscription_all = forms.BooleanField(
required=False, label='Uncheck this box to unsubscribe from all emails from PerDiem'
required=False,
label="Uncheck this box to unsubscribe from all emails from PerDiem",
)

def __init__(self, user, *args, **kwargs):
super(EmailPreferencesForm, self).__init__(*args, **kwargs)
self.user = user

def clean_email(self):
email = self.cleaned_data['email']
email = self.cleaned_data["email"]

# Verify that there are no other users already with this email address
if User.objects.exclude(id=self.user.id).filter(email=email).exists():
raise forms.ValidationError(
"The email address {email} already belongs to an existing user on PerDiem.".format(email=email)
"The email address {email} already belongs to an existing user on PerDiem.".format(
email=email
)
)

return email

def clean(self):
d = self.cleaned_data
if (d['subscription_news'] or d['subscription_artup']) and not d['subscription_all']:
if (d["subscription_news"] or d["subscription_artup"]) and not d[
"subscription_all"
]:
raise forms.ValidationError(
"You cannot subscribe to general updates or artist updates if you are unsubscribed from all emails."
)
Expand All @@ -152,9 +168,9 @@ def clean(self):
class ContactForm(forms.Form):

INQUIRY_CHOICES = (
('Support', 'Support',),
('Feedback', 'Feedback',),
('General Inquiry', 'General Inquiry',),
("Support", "Support"),
("Feedback", "Feedback"),
("General Inquiry", "General Inquiry"),
)

inquiry = forms.ChoiceField(choices=INQUIRY_CHOICES)
Expand Down
9 changes: 4 additions & 5 deletions accounts/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,19 @@


class LoginFormMiddleware(MiddlewareMixin):

def process_request(self, request):
if request.method == 'POST' and 'login-username' in request.POST:
if request.method == "POST" and "login-username" in request.POST:
# Process the request as a login request
# if login-username is in the POST data
form = LoginAccountForm(data=request.POST, prefix='login')
form = LoginAccountForm(data=request.POST, prefix="login")
if form.is_valid():
login(request, form.get_user())

# We have to change the request method here because
# the page the user is currently on might not support POST
request.method = 'GET'
request.method = "GET"
else:
form = LoginAccountForm(request, prefix='login')
form = LoginAccountForm(request, prefix="login")

# Add the login form to the request (accessible in context)
request.login_form = form
28 changes: 20 additions & 8 deletions accounts/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,29 @@ class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]

operations = [
migrations.CreateModel(
name='UserProfile',
name="UserProfile",
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('invest_anonymously', models.BooleanField(default=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("invest_anonymously", models.BooleanField(default=False)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
)
]
4 changes: 2 additions & 2 deletions accounts/migrations/0002_userprofiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0001_initial'),
("accounts", "0001_initial"),
]

def create_initial_userprofiles(apps, schema_editor):
Expand All @@ -18,5 +18,5 @@ def create_initial_userprofiles(apps, schema_editor):
UserProfile.objects.create(user=user)

operations = [
migrations.RunPython(create_initial_userprofiles, migrations.RunPython.noop),
migrations.RunPython(create_initial_userprofiles, migrations.RunPython.noop)
]
Loading

0 comments on commit 3c3e4b9

Please sign in to comment.