bgg_api/bgg_connection.py

83 lines
3.3 KiB
Python
Raw Normal View History

2024-07-25 19:58:28 +02:00
import requests
import xml.etree.ElementTree as ET
from pydantic import HttpUrl
import requests
2024-07-25 19:58:28 +02:00
from classes.boardgame import BoardGame, BoardGameExpansion
import auth_manager
authenticated_session: requests.Session
2024-07-25 19:58:28 +02:00
def url_to_xml_object(url: HttpUrl) -> ET.Element:
r = authenticated_session.get(url)
2024-07-25 19:58:28 +02:00
root = ET.fromstring(r.content)
return root
#Requires single boardgame XML 'item' from bgg api
def convert_xml_to_boardgame(boardgame_xml: ET.Element) -> BoardGame:
boardgame_type = boardgame_xml.get('type')
match boardgame_type:
case "boardgame":
boardgame = BoardGame(
id = boardgame_xml.get('id'),
name = boardgame_xml.find('name').get('value'),
description = boardgame_xml.find('description').text,
image_url = boardgame_xml.find('image').text,
thumbnail_url = boardgame_xml.find('thumbnail').text,
year_published = int(boardgame_xml.find('yearpublished').get('value')),
min_players = int(boardgame_xml.find('minplayers').get('value')),
max_players = int(boardgame_xml.find('maxplayers').get('value')),
min_playing_time = int(boardgame_xml.find('minplaytime').get('value')),
max_playing_time = int(boardgame_xml.find('maxplaytime').get('value')),
min_age = int(boardgame_xml.find('minage').get('value')),
all_expansion_ids = [0,1,2,3]
)
case "boardgameexpansion":
boardgame = BoardGameExpansion(
id = boardgame_xml.get('id'),
name = boardgame_xml.find('name').get('value'),
description = boardgame_xml.find('description').text,
image_url = boardgame_xml.find('image').text,
thumbnail_url = boardgame_xml.find('thumbnail').text,
year_published = int(boardgame_xml.find('yearpublished').get('value')),
min_players = int(boardgame_xml.find('minplayers').get('value')),
max_players = int(boardgame_xml.find('maxplayers').get('value')),
min_playing_time = int(boardgame_xml.find('minplaytime').get('value')),
max_playing_time = int(boardgame_xml.find('maxplaytime').get('value')),
min_age = int(boardgame_xml.find('minage').get('value')),
all_expansion_ids = [0,1,2,3]
)
return boardgame
def get_boardgame(boardgame_id: int) -> BoardGame:
url : str = "https://boardgamegeek.com/xmlapi2/thing?id={}&stats=true".format(boardgame_id)
boardgame_xml_object : ET.Element = url_to_xml_object(url)
requested_boardgame = convert_xml_to_boardgame(boardgame_xml_object.find('item'))
return requested_boardgame
def load_authenticated_bgg_session(username: str, password: str) -> requests.Session:
global authenticated_session
login_url = "https://boardgamegeek.com/login/api/v1"
post_data = {
"credentials":{
"username": username,
"password": password
}
}
authenticated_session = requests.Session()
login_response = authenticated_session.post(login_url, json=post_data)
assert login_response.status_code == 204
load_authenticated_bgg_session(auth_manager.username, auth_manager.password)