57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
import json
|
|
import requests
|
|
import time
|
|
import uuid
|
|
import wikipedia
|
|
|
|
class Card():
|
|
def __init__(self, cardId=None, pageId=None, data=None):
|
|
self.cardId = cardId if cardId else uuid.uuid4()
|
|
delay = 2
|
|
while True:
|
|
try:
|
|
self.pageId = pageId if pageId else int(
|
|
wikipedia.page(
|
|
wikipedia.random()
|
|
).pageid
|
|
)
|
|
except wikipedia.exceptions.PageError as e:
|
|
# TODO: why is the random function returning lower-case pages?
|
|
continue
|
|
except wikipedia.exceptions.DisambiguationError as e:
|
|
# TODO pick random disambiuation option
|
|
continue
|
|
except wikipedia.exceptions.WikipediaException as e:
|
|
time.sleep(delay)
|
|
delay = delay**2
|
|
continue
|
|
break
|
|
if data:
|
|
self.load_from_data(data)
|
|
|
|
def validate(self):
|
|
try:
|
|
# TODO: cardId is UUID
|
|
wikipedia.page(pageid=self.pageId)
|
|
except Exception as e:
|
|
raise self.Invalid("Page ID does not match a Wikipedia page.")
|
|
|
|
def load_from_data(self, data):
|
|
self.cardId = uuid.UUID(data['cardId'])
|
|
self.pageId = data['pageId']
|
|
|
|
def as_dict(self):
|
|
return {
|
|
"cardId": str(self.cardId),
|
|
"pageId": self.pageId
|
|
}
|
|
|
|
def __str__(self):
|
|
return json.dumps(self.as_dict(), sort_keys=True)
|
|
|
|
class Invalid(Exception):
|
|
def __init__(self, message, statusCode=406):
|
|
super().__init__(message)
|
|
self.message = message
|
|
self.statusCode = statusCode
|