Skip to content

Commit

Permalink
Fix issues that showed up in flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
gentlecat committed Aug 17, 2017
1 parent a9407dc commit 83d8836
Show file tree
Hide file tree
Showing 45 changed files with 214 additions and 147 deletions.
1 change: 1 addition & 0 deletions critiquebrainz/data/user_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def __init__(self, label, karma, reviews_per_day, votes_per_day):
def is_instance(self, user):
return self.karma(user.karma)


blocked = UserType(
label='Blocked',
karma=lambda x: (x < -20),
Expand Down
20 changes: 10 additions & 10 deletions critiquebrainz/db/avg_rating.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ def update(entity_id, entity_type):
SELECT review_id,
MAX("timestamp") created_at
FROM revision
WHERE review_id in (
SELECT id
WHERE review_id in (
SELECT id
FROM review
WHERE entity_id = :entity_id
AND entity_type = :entity_type)
GROUP BY review_id)
GROUP BY review_id
)
SELECT SUM(rating),
COUNT(rating)
FROM revision
Expand All @@ -38,7 +38,7 @@ def update(entity_id, entity_type):
})
row = result.fetchone()

#Calulate average rating and update it
# Calculate average rating and update it
sum, count = row[0], row[1]
if count == 0:
delete(entity_id, entity_type)
Expand All @@ -48,10 +48,10 @@ def update(entity_id, entity_type):
connection.execute(sqlalchemy.text("""
INSERT INTO avg_rating(entity_id, entity_type, rating, count)
VALUES (:entity_id, :entity_type, :rating, :count)
ON CONFLICT
ON CONFLICT
ON CONSTRAINT avg_rating_pkey
DO UPDATE
SET rating = EXCLUDED.rating,
SET rating = EXCLUDED.rating,
count = EXCLUDED.count
"""), {
"entity_id": entity_id,
Expand All @@ -70,7 +70,7 @@ def delete(entity_id, entity_type):
"""
with db.engine.connect() as connection:
connection.execute(sqlalchemy.text("""
DELETE
DELETE
FROM avg_rating
WHERE entity_id = :entity_id
AND entity_type = :entity_type
Expand Down Expand Up @@ -111,7 +111,7 @@ def get(entity_id, entity_type):

avg_rating = result.fetchone()
if not avg_rating:
raise db_exceptions.NoDataFoundException("""No rating for the entity with ID: {id} and Type: {type}
""".format(id=entity_id, type=entity_type))
raise db_exceptions.NoDataFoundException("""No rating for the entity with ID: {id} and Type: {type}""".
format(id=entity_id, type=entity_type))

return dict(avg_rating)
5 changes: 3 additions & 2 deletions critiquebrainz/db/avg_rating_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import critiquebrainz.db.exceptions as db_exceptions
import critiquebrainz.db.license as db_license


class AvgRatingTestCase(DataTestCase):

def setUp(self):
Expand Down Expand Up @@ -74,12 +75,12 @@ def test_update(self):
text=u"Testing rating update",
rating=None,
)
#Check if avg_rating is updated after change in rating
# Check if avg_rating is updated after change in rating
avg_rating = db_avg_rating.get(review["entity_id"], review["entity_type"])
self.assertEqual(avg_rating["rating"], 100)
self.assertEqual(avg_rating["count"], 1)

#Check if avg_rating is updated after a review with rating is deleted
# Check if avg_rating is updated after a review with rating is deleted
db_review.delete(review["id"])
with self.assertRaises(db_exceptions.NoDataFoundException):
db_avg_rating.get(review["entity_id"], review["entity_type"])
Expand Down
3 changes: 2 additions & 1 deletion critiquebrainz/db/license_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from critiquebrainz.data.testing import DataTestCase
import critiquebrainz.db.license as db_license


class LicenseTestCase(DataTestCase):

def test_license_create(self):
Expand Down Expand Up @@ -32,5 +33,5 @@ def test_list_licenses(self):
self.assertDictEqual({
"id": "test",
"full_name": "Test license",
"info_url":"www.example.com"
"info_url": "www.example.com"
}, licenses[0])
17 changes: 9 additions & 8 deletions critiquebrainz/db/moderation_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
ACTION_HIDE_REVIEW = "hide_review"
ACTION_BLOCK_USER = "block_user"


def create(*, admin_id, review_id=None, user_id=None,
action, reason):
"""Make a record in the moderation log.
Expand All @@ -29,14 +30,14 @@ def create(*, admin_id, review_id=None, user_id=None,
connection.execute(sqlalchemy.text("""
INSERT INTO moderation_log(admin_id, user_id, review_id, action, timestamp, reason)
VALUES (:admin_id, :user_id, :review_id, :action, :timestamp, :reason)
"""), {
"admin_id": admin_id,
"user_id": user_id,
"review_id": review_id,
"action": action,
"timestamp": datetime.now(),
"reason": reason,
})
"""), {
"admin_id": admin_id,
"user_id": user_id,
"review_id": review_id,
"action": action,
"timestamp": datetime.now(),
"reason": reason,
})


def list_logs(*, admin_id=None, limit=None, offset=None):
Expand Down
1 change: 1 addition & 0 deletions critiquebrainz/db/oauth_grant_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import critiquebrainz.db.exceptions as db_exceptions
from critiquebrainz.db.user import User


class OAuthGrantTestCase(DataTestCase):

def setUp(self):
Expand Down
1 change: 1 addition & 0 deletions critiquebrainz/db/oauth_token_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import critiquebrainz.db.exceptions as db_exceptions
from critiquebrainz.db.user import User


class OAuthTokenTestCase(DataTestCase):

def setUp(self):
Expand Down
7 changes: 5 additions & 2 deletions critiquebrainz/db/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
import sqlalchemy
from brainzutils import cache
from critiquebrainz import db
from critiquebrainz.db import exceptions as db_exceptions, revision as db_revision, users as db_users, avg_rating as db_avg_rating
from critiquebrainz.db import (exceptions as db_exceptions,
revision as db_revision,
users as db_users,
avg_rating as db_avg_rating)
from critiquebrainz.db.user import User
import pycountry

Expand Down Expand Up @@ -290,7 +293,7 @@ def create(*, entity_id, entity_type, user_id, is_draft, text=None, rating=None,
INSERT INTO review (id, entity_id, entity_type, user_id, edits, is_draft, is_hidden, license_id, language, source, source_url)
VALUES (:id, :entity_id, :entity_type, :user_id, :edits, :is_draft, :is_hidden, :license_id, :language, :source, :source_url)
RETURNING id;
"""), {
"""), { # noqa: E501
"id": str(uuid.uuid4()),
"entity_id": entity_id,
"entity_type": entity_type,
Expand Down
3 changes: 2 additions & 1 deletion critiquebrainz/db/review_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import critiquebrainz.db.exceptions as db_exceptions
import critiquebrainz.db.license as db_license


class ReviewTestCase(DataTestCase):

def setUp(self):
Expand Down Expand Up @@ -130,7 +131,7 @@ def test_update(self):
license_id=another_license["id"],
language="es",
)
#Checking if contents are updated
# Checking if contents are updated
retrieved_review = db_review.list_reviews()[0][0]
self.assertEqual(retrieved_review["text"], "Testing update")
self.assertEqual(retrieved_review["rating"], None)
Expand Down
5 changes: 3 additions & 2 deletions critiquebrainz/db/revision.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def get_all_votes(review_id):
for row in rows:
revision = row.id
if revision not in votes:
votes[revision] = {'positive':0, 'negative':0}
votes[revision] = {'positive': 0, 'negative': 0}
if row.vote: # True = positive
votes[revision]['positive'] += 1
else: # False = negative
Expand Down Expand Up @@ -148,7 +148,8 @@ def get_revision_number(review_id, revision_id):
})
rev_num = result.fetchone()[0]
if not rev_num:
raise db_exceptions.NoDataFoundException("Can't find the revision with id={} for specified review.".format(revision_id))
raise db_exceptions.NoDataFoundException("Can't find the revision with id={} for specified review.".
format(revision_id))
return rev_num


Expand Down
10 changes: 5 additions & 5 deletions critiquebrainz/db/revision_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ class RevisionTestCase(DataTestCase):
def setUp(self):
super(RevisionTestCase, self).setUp()
self.author = User(db_users.get_or_create('Author', new_user_data={
"display_name":'0',
"display_name": '0',
}))
self.user_1 = User(db_users.get_or_create('Tester #1', new_user_data={
"display_name":'1',
"display_name": '1',
}))
self.user_2 = User(db_users.get_or_create('Tester #2', new_user_data={
"display_name":'2',
"display_name": '2',
}))
self.license = db_license.create(
id=u'TEST',
Expand Down Expand Up @@ -87,8 +87,8 @@ def test_get_all_votes(self):
votes = revision.get_all_votes(review_id)
votes_first_revision = votes[first_revision['id']]
self.assertDictEqual(votes_first_revision, {
"positive":1,
"negative":1
"positive": 1,
"negative": 1
})

def test_get_revision_number(self):
Expand Down
14 changes: 7 additions & 7 deletions critiquebrainz/db/spam_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ def create(revision_id, user_id, reason):
connection.execute(sqlalchemy.text("""
INSERT INTO spam_report (user_id, reason, revision_id, reported_at, is_archived)
VALUES (:user_id, :reason, :revision_id, :reported_at, :is_archived)
"""), {
"user_id": str(user_id),
"reason": reason,
"revision_id": revision_id,
"reported_at": datetime.now(),
"is_archived": False,
})
"""), {
"user_id": str(user_id),
"reason": reason,
"revision_id": revision_id,
"reported_at": datetime.now(),
"is_archived": False,
})
return get(user_id, revision_id)


Expand Down
2 changes: 1 addition & 1 deletion critiquebrainz/db/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def stats(self):
reviews_last_7_days=self.reviews_since_count(today - timedelta(days=7)),
reviews_this_month=self.reviews_since_count(date(today.year, today.month, 1)),
votes_today=self.votes_today_count(),
votes_last_7_days=self.votes_since_count(today-timedelta(days=7)),
votes_last_7_days=self.votes_since_count(today - timedelta(days=7)),
votes_this_month=self.votes_since_count(date(today.year, today.month, 1)),
)

Expand Down
26 changes: 13 additions & 13 deletions critiquebrainz/db/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,15 @@ def create(**user_data):
INSERT INTO "user" (id, display_name, email, created, musicbrainz_id, show_gravatar, is_blocked)
VALUES (:id, :display_name, :email, :created, :musicbrainz_id, :show_gravatar, :is_blocked)
RETURNING id
"""), {
"id": str(uuid.uuid4()),
"display_name": display_name,
"email": email,
"created": datetime.now(),
"musicbrainz_id": musicbrainz_username,
"show_gravatar": show_gravatar,
"is_blocked": is_blocked,
})
"""), {
"id": str(uuid.uuid4()),
"display_name": display_name,
"email": email,
"created": datetime.now(),
"musicbrainz_id": musicbrainz_username,
"show_gravatar": show_gravatar,
"is_blocked": is_blocked,
})
new_id = result.fetchone()[0]
return get_by_id(new_id)

Expand Down Expand Up @@ -343,10 +343,10 @@ def has_voted(user_id, review_id):
FROM vote
WHERE revision_id = :revision_id
AND user_id = :user_id
"""), {
"revision_id": last_revision['id'],
"user_id": user_id
})
"""), {
"revision_id": last_revision['id'],
"user_id": user_id
})
count = result.fetchone()[0]
return count > 0

Expand Down
1 change: 1 addition & 0 deletions critiquebrainz/db/users_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import critiquebrainz.db.oauth_token as db_oauth_token
from critiquebrainz.db.user import User


class UserTestCase(DataTestCase):
def setUp(self):
super(UserTestCase, self).setUp()
Expand Down
1 change: 1 addition & 0 deletions critiquebrainz/frontend/external/musicbrainz.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ def browse_releases(artist_id=None, release_group=None, release_types=None, limi
cache.set(key=key, val=releases, time=DEFAULT_CACHE_EXPIRATION)
return releases


def get_artist_by_id(id):
"""Get artist with the MusicBrainz ID.
Expand Down
6 changes: 4 additions & 2 deletions critiquebrainz/frontend/external/musicbrainz_db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
from sqlalchemy.pool import NullPool

engine = None
Session: Optional[Session] = None
DEFAULT_CACHE_EXPIRATION = 12 * 60 * 60 # seconds (12 hours)
Session: Optional[Session] = None # noqa: F811
DEFAULT_CACHE_EXPIRATION = 12 * 60 * 60 # seconds (12 hours)


def init_db_engine(connect_str):
global engine, Session
Expand All @@ -15,6 +16,7 @@ def init_db_engine(connect_str):
sessionmaker(bind=engine)
)


@contextmanager
def mb_session():
session = Session()
Expand Down
4 changes: 1 addition & 3 deletions critiquebrainz/frontend/external/musicbrainz_db/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,4 @@ def fetch_multiple_events(mbids, *, includes=None):
source_entity_ids=event_ids,
includes_data=includes_data,
)

events = {str(mbid): to_dict_events(events[mbid], includes_data[events[mbid].id]) for mbid in mbids}
return events
return {str(mbid): to_dict_events(events[mbid], includes_data[events[mbid].id]) for mbid in mbids}
8 changes: 5 additions & 3 deletions critiquebrainz/frontend/external/musicbrainz_db/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ def get_tags(*, db, entity_model, tag_model, entity_ids):
List of tuples containing the entity_ids and the list of associated tags.
"""
tags = db.query(entity_model.id, func.array_agg(Tag.name)).\
join(tag_model).\
join(Tag).filter(entity_model.id.in_(entity_ids)).\
group_by(entity_model.id).all()
join(tag_model).\
join(Tag).\
filter(entity_model.id.in_(entity_ids)).\
group_by(entity_model.id).\
all()
return tags
4 changes: 2 additions & 2 deletions critiquebrainz/frontend/external/musicbrainz_db/place.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ def fetch_multiple_places(mbids, *, includes=None):
check_includes('place', includes)
with mb_session() as db:
query = db.query(models.Place).\
options(joinedload("area")).\
options(joinedload("type"))
options(joinedload("area")).\
options(joinedload("type"))
places = get_entities_by_gids(
query=query,
entity_type='place',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ def fetch_multiple_release_groups(mbids, *, includes=None):
query = db.query(models.ReleaseGroup).options(joinedload("meta"))

if 'artists' in includes:
query = query.options(joinedload("artist_credit")).\
options(joinedload("artist_credit.artists")).\
options(joinedload("artist_credit.artists.artist"))
query = query.\
options(joinedload("artist_credit")).\
options(joinedload("artist_credit.artists")).\
options(joinedload("artist_credit.artists.artist"))

release_groups = get_entities_by_gids(
query=query,
Expand Down

0 comments on commit 83d8836

Please sign in to comment.