Skip to content

Commit

Permalink
Restyled by yapf
Browse files Browse the repository at this point in the history
  • Loading branch information
restyled-commits committed Sep 23, 2024
1 parent 3dbc27a commit 378eaaf
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 55 deletions.
19 changes: 12 additions & 7 deletions logetscraper/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ def findCardName(cardURL):
soup = BeautifulSoup(response.content, "html.parser")
s = soup.find_all("section", class_="listA")

assert len(s) == 1, f"Unexpected number of sections in finding card name: {len(s)}"
assert len(
s
) == 1, f"Unexpected number of sections in finding card name: {len(s)}"

head = s[0].find_all("h1")

Expand All @@ -100,13 +102,14 @@ def findCardSpotLink(cardURL):
soup = BeautifulSoup(response.content, "html.parser")
s = soup.find_all("section", class_="listA")

assert len(s) == 1, f"Unexpected number of sections in finding card name: {len(s)}"
assert len(
s
) == 1, f"Unexpected number of sections in finding card name: {len(s)}"

spot = s[0].find_all("div", class_="text_footer")

assert (
len(spot) == 1
), f"Unexpected number of a tags in finding card name: {len(spot)}"
assert (len(spot) == 1
), f"Unexpected number of a tags in finding card name: {len(spot)}"

link = spot[0].find_all("a", target="_blank")

Expand Down Expand Up @@ -153,11 +156,13 @@ def main():
assert len(cardIds) == len(
cardImgs
), f"Number of card Ids and card images do not match: {len(cardIds)} vs {len(cardImgs)}"
logger.info(f"Found a total of {len(cardIds)} cards in the card list page.")
logger.info(
f"Found a total of {len(cardIds)} cards in the card list page.")

for cardId, cardImg in zip(cardIds, cardImgs):
if cardId in existingCardIds:
logger.info(f"Card {cardId} already exists in the database. Skipping.")
logger.info(
f"Card {cardId} already exists in the database. Skipping.")
continue

cardURL = logetURLReconstructor(cardId, "card")
Expand Down
16 changes: 8 additions & 8 deletions logettracker/logettracker/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / ".env")


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

Expand All @@ -30,7 +29,6 @@
# SECURITY WARNING: Nginx will handle host checking in the production environment
ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
Expand Down Expand Up @@ -91,26 +89,28 @@
}
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
"NAME":
"django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
"NAME":
"django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
"NAME":
"django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
"NAME":
"django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

Expand Down
3 changes: 1 addition & 2 deletions logettracker/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ def main():
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
"forget to activate a virtual environment?") from exc
execute_from_command_line(sys.argv)


Expand Down
54 changes: 25 additions & 29 deletions logettracker/tracker/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ def collectedCardsDataValidator(jsonData):
:param jsonData:
"""
if (
not isinstance(jsonData, dict)
or not len(jsonData) == 1
or not "collected" in jsonData
or not isinstance(jsonData["collected"], list)
):
if (not isinstance(jsonData, dict) or not len(jsonData) == 1
or not "collected" in jsonData
or not isinstance(jsonData["collected"], list)):
raise ValidationError(
gettext_lazy(
"The collectedCards field must be a dictionary of format {'collected': [cardid1, cardid2, ...]}."
Expand All @@ -39,14 +36,16 @@ def collectedCardsDataValidator(jsonData):
class LoGetUsers(models.Model):
""" """

user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
CardsColleted = models.JSONField(
validators=[collectedCardsDataValidator], default=dict
)
user = models.OneToOneField(User,
on_delete=models.CASCADE,
primary_key=True)
CardsColleted = models.JSONField(validators=[collectedCardsDataValidator],
default=dict)


class URLStartCheckValidator(URLValidator):
""" """

def __init__(self, startString, schemes=None, **kwargs):
self.startString = startString
super().__init__(schemes, **kwargs)
Expand All @@ -55,7 +54,10 @@ def __call__(self, url):
if not url.startswith(self.startString):
raise ValidationError(
gettext_lazy("The URL must start with '%(startString)s'."),
params={"url": url, "startString": self.startString},
params={
"url": url,
"startString": self.startString
},
)
super().__call__(url)

Expand All @@ -64,22 +66,16 @@ class LoGetCards(models.Model):
""" """
Id = models.IntegerField(primary_key=True)
Name = models.CharField(max_length=100)
Img = models.URLField(
validators=[
URLValidator(),
URLStartCheckValidator("https://loget-card.jp/img/cards"),
]
)
SpotmapLink = models.URLField(
validators=[
URLValidator(),
URLStartCheckValidator("https://loget-card.jp/list_map.aspx"),
]
)
LoGetURL = models.URLField(
validators=[
URLValidator(),
URLStartCheckValidator("https://loget-card.jp/list.aspx"),
]
)
Img = models.URLField(validators=[
URLValidator(),
URLStartCheckValidator("https://loget-card.jp/img/cards"),
])
SpotmapLink = models.URLField(validators=[
URLValidator(),
URLStartCheckValidator("https://loget-card.jp/list_map.aspx"),
])
LoGetURL = models.URLField(validators=[
URLValidator(),
URLStartCheckValidator("https://loget-card.jp/list.aspx"),
])
SpotWebsiteLink = models.URLField()
6 changes: 3 additions & 3 deletions logettracker/tracker/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
path("signup/", views.signupView, name="signup"),
path("logout/", views.logoutView, name="logout"),
path("<slug:t>/success/", views.success, name="success"),
path(
"tracker/processcardaction/", views.processCardAction, name="processCardAction"
),
path("tracker/processcardaction/",
views.processCardAction,
name="processCardAction"),
]
16 changes: 10 additions & 6 deletions logettracker/tracker/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ def processCardAction(request):
action = data.get("action")

user = request.user
userCards = LoGetUsers.objects.get(user=user).CardsColleted["collected"]
userCards = LoGetUsers.objects.get(
user=user).CardsColleted["collected"]

if action == "add":
if div_id not in userCards:
Expand All @@ -85,8 +86,7 @@ def processCardAction(request):
userCards.remove(div_id)

LoGetUsers.objects.filter(user=user).update(
CardsColleted={"collected": userCards}
)
CardsColleted={"collected": userCards})

return JsonResponse({"status": "success"})

Expand Down Expand Up @@ -154,7 +154,9 @@ def loginView(request):
login(request, user)
existingUser = LoGetUsers.objects.filter(user=user)
if not existingUser:
LoGetUsers(user=user, CardsColleted={"collected": []}).save()
LoGetUsers(user=user, CardsColleted={
"collected": []
}).save()
return redirect("tracker:tracker")

context["failed"] = True
Expand Down Expand Up @@ -186,7 +188,8 @@ def settings(request):
user = form.save() # Save the new password
# Prevent user from being logged out after password change
update_session_auth_hash(request, user)
messages.success(request, "Your password was successfully updated!")
messages.success(request,
"Your password was successfully updated!")
return redirect("tracker:settings")
else:
messages.error(request, "Please correct the error below.")
Expand All @@ -212,7 +215,8 @@ def exportData(request):
cards,
headers={
"Content-Type": "text/plain",
"Content-Disposition": 'attachment; filename="collectedcards.json"',
"Content-Disposition":
'attachment; filename="collectedcards.json"',
},
)

Expand Down

0 comments on commit 378eaaf

Please sign in to comment.