Skip to content

Commit

Permalink
Merge pull request #198 from SaltieRL/with_session_decorator
Browse files Browse the repository at this point in the history
With session decorator
  • Loading branch information
dtracers authored Oct 26, 2018
2 parents 00b0385 + 08aa003 commit 95b9a02
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 86 deletions.
6 changes: 3 additions & 3 deletions backend/blueprints/players.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
def view_player(id_):
print(id_, request.remote_addr)
if len(id_) != 17 or re.match(regex, id_) is None:
r = get_vanity_to_steam_id_or_random_response(id_, current_app)
r = get_vanity_to_steam_id_or_random_response(id_)
if r is None:
return redirect(url_for('home'))
id_ = r['response']['steamid']
Expand Down Expand Up @@ -51,7 +51,7 @@ def compare_player_redir(id_):
print(request.form)
other = request.form['other']
if len(other) != 17 or re.match(regex, other) is None:
r = get_vanity_to_steam_id_or_random_response(other, current_app)
r = get_vanity_to_steam_id_or_random_response(other)
if r is None:
return redirect(url_for('players.view_player', id_=id_))
other = r['response']['steamid']
Expand Down Expand Up @@ -89,7 +89,7 @@ def render_player_history(id_, page_number):
page_number = int(page_number)
print(re.match(regex, id_))
if len(id_) != 17 or re.match(regex, id_) is None:
r = get_vanity_to_steam_id_or_random_response(id_, current_app)
r = get_vanity_to_steam_id_or_random_response(id_)
if r is None:
return redirect(url_for('home'))
id_ = r['response']['steamid']
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from flask import current_app
from sqlalchemy import desc

from backend.blueprints.spa_api.service_layers.utils import with_session
from backend.database.objects import Game
from backend.database.wrapper.query_filter_builder import QueryFilterBuilder
from .replay import Replay
Expand All @@ -15,21 +16,20 @@ def __init__(self, total_count: int, replays: List[Replay]):
self.replays = [replay.__dict__ for replay in replays]

@staticmethod
def create_from_id(id_: str, page: int, limit: int) -> 'MatchHistory':
session = current_app.config['db']()
@with_session
def create_from_id(id_: str, page: int, limit: int, session=None) -> 'MatchHistory':
games = [player_game.game_object
for player_game in player_wrapper.get_player_games_paginated(session, id_, page, limit)]
total_count = player_wrapper.get_total_games(session, id_)
match_history = MatchHistory(total_count, [Replay.create_from_game(game) for game in games])
session.close()
return match_history

@staticmethod
def create_with_filters(page: int, limit: int, **kwargs) -> 'MatchHistory':
@with_session
def create_with_filters(page: int, limit: int, session=None, **kwargs) -> 'MatchHistory':
# TODO: move this somewhere else and make it reusable
if limit > 100:
limit = 100
session = current_app.config['db']()
builder = QueryFilterBuilder().as_game().with_stat_query([Game])
QueryFilterBuilder.apply_arguments_to_query(builder, kwargs)
query = builder.build_query(session)
Expand All @@ -43,5 +43,4 @@ def create_with_filters(page: int, limit: int, **kwargs) -> 'MatchHistory':
count = query.count()
games = query.order_by(desc(Game.match_date))[page * limit: (page + 1) * limit]
matches = MatchHistory(count, [Replay.create_from_game(game) for game in games])
session.close()
return matches
42 changes: 19 additions & 23 deletions backend/blueprints/spa_api/service_layers/replay/tag.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import List

from flask import g, current_app
from flask import g

from backend.blueprints.spa_api.service_layers.utils import with_session
from ...errors.errors import CalculatedError, TagNotFound
from backend.database.objects import Tag as DBTag
from backend.database.wrapper.tag_wrapper import TagWrapper, DBTagNotFound
Expand All @@ -17,68 +18,63 @@ def create_from_dbtag(tag: DBTag):
return Tag(tag.name, tag.owner)

@staticmethod
def create(name: str) -> 'Tag':
session = current_app.config['db']()

@with_session
def create(name: str, session=None) -> 'Tag':
# Check if tag exists
try:
dbtag = TagWrapper.get_tag(g.user.platformid, name, session)
dbtag = TagWrapper.get_tag(session, g.user.platformid, name)
tag = Tag.create_from_dbtag(dbtag)
session.close()
return tag
except DBTagNotFound:
pass
dbtag = TagWrapper.create_tag(session, g.user.platformid, name)
tag = Tag.create_from_dbtag(dbtag)
session.close()
return tag

@staticmethod
def rename(current_name: str, new_name: str) -> 'Tag':
session = current_app.config['db']()

@with_session
def rename(current_name: str, new_name: str, session=None) -> 'Tag':
# Check if name already exists
try:
TagWrapper.get_tag(g.user.platformid, new_name, session)
session.close()
TagWrapper.get_tag(session, g.user.platformid, new_name)
raise CalculatedError(409, f"Tag with name {new_name} already exists.")
except DBTagNotFound:
pass

try:
dbtag = TagWrapper.rename_tag(session, g.user.platformid, current_name, new_name)
except DBTagNotFound:
session.close()
raise TagNotFound()
tag = Tag.create_from_dbtag(dbtag)
session.close()
return tag

@staticmethod
def delete(name: str) -> None:
@with_session
def delete(name: str, session=None) -> None:
try:
TagWrapper.delete_tag(g.user.platformid, name)
TagWrapper.delete_tag(session, g.user.platformid, name)
except DBTagNotFound:
raise TagNotFound()

@staticmethod
def get_all() -> List['Tag']:
session = current_app.config['db']()
@with_session
def get_all(session=None) -> List['Tag']:
dbtags = TagWrapper.get_tags(session, g.user.platformid)
tags = [Tag.create_from_dbtag(dbtag) for dbtag in dbtags]
session.close()
return tags

@staticmethod
def add_tag_to_game(name: str, replay_id: str) -> None:
@with_session
def add_tag_to_game(name: str, replay_id: str, session=None) -> None:
try:
TagWrapper.add_tag_to_game(replay_id, g.user.platformid, name)
TagWrapper.add_tag_to_game(session, replay_id, g.user.platformid, name)
except DBTagNotFound:
raise TagNotFound()

@staticmethod
def remove_tag_from_game(name: str, replay_id: str) -> None:
@with_session
def remove_tag_from_game(name: str, replay_id: str, session=None) -> None:
try:
TagWrapper.remove_tag_from_game(replay_id, g.user.platformid, name)
TagWrapper.remove_tag_from_game(session, replay_id, g.user.platformid, name)
except DBTagNotFound:
raise TagNotFound()
14 changes: 14 additions & 0 deletions backend/blueprints/spa_api/service_layers/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
from typing import List

from flask import current_app

from backend.database.objects import PlayerGame


def with_session(decorated_function):
def wrapper_func(*args, **kwargs):
session = current_app.config['db']()
try:
kwargs['session'] = session
result = decorated_function(*args, **kwargs)
finally:
session.close()
return result
return wrapper_func


def sort_player_games_by_team_then_id(player_games: List[PlayerGame]) -> List[PlayerGame]:
def get_id(player_game: PlayerGame):
return player_game.id
Expand Down
2 changes: 1 addition & 1 deletion backend/blueprints/spa_api/spa_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def api_get_current_user():
def api_get_player(id_or_name):
if len(id_or_name) != 17 or re.match(re.compile('\d{17}'), id_or_name) is None:
# Treat as name
response = get_vanity_to_steam_id_or_random_response(id_or_name, current_app)
response = get_vanity_to_steam_id_or_random_response(id_or_name)
if response is None:
raise CalculatedError(404, "User not found")
steam_id = response['response']['steamid']
Expand Down
7 changes: 4 additions & 3 deletions backend/blueprints/steam.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import requests
from flask import jsonify, request, redirect, url_for, Blueprint, current_app

from backend.blueprints.spa_api.service_layers.utils import with_session
from backend.database.wrapper.player_wrapper import get_random_player, create_default_player

try:
Expand All @@ -21,7 +22,7 @@
def resolve_steam():
if 'name' not in request.form:
return jsonify({})
r = get_vanity_to_steam_id_or_random_response(request.form['name'], current_app)
r = get_vanity_to_steam_id_or_random_response(request.form['name'])
if r is None:
steamid = request.form['name']
else:
Expand Down Expand Up @@ -73,13 +74,13 @@ def steam_id_to_profile(steam_id):
return resp.json()


def get_vanity_to_steam_id_or_random_response(vanity, current_app):
@with_session
def get_vanity_to_steam_id_or_random_response(vanity, session=None):
try:
return vanity_to_steam_id(vanity)
except BaseException as e:
logger.warning(e)
traceback.print_exc()
session = current_app.config['db']()
player = get_random_player(session)
return {
'response': {
Expand Down
42 changes: 8 additions & 34 deletions backend/database/wrapper/tag_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def create_tag(session, user_id: str, name: str) -> Tag:

@staticmethod
def rename_tag(session, user_id: str, old_name: str, new_name: str) -> Tag:
tag = TagWrapper.get_tag(user_id, old_name, session)
tag = TagWrapper.get_tag(session, user_id, old_name)
tag.name = new_name
session.commit()
return tag
Expand All @@ -27,36 +27,20 @@ def get_tags(session, user_id: str) -> List[Tag]:
return session.query(Tag).filter(Tag.owner == user_id).all()

@staticmethod
def delete_tag(user_id: str, name: str):
session = current_app.config['db']()
try:
tag = TagWrapper.get_tag(user_id, name, session)
except DBTagNotFound:
session.close()
raise DBTagNotFound()
def delete_tag(session, user_id: str, name: str):
tag = TagWrapper.get_tag(session, user_id, name)
session.delete(tag)
session.commit()
session.close()

@staticmethod
def get_tag(user_id: str, name: str, session=None) -> Tag:
no_ses_ref = session is None

if no_ses_ref:
session = current_app.config['db']()

def get_tag(session, user_id: str, name: str) -> Tag:
tag = session.query(Tag).filter(Tag.owner == user_id, Tag.name == name).first()

if no_ses_ref:
session.close()

if tag is None:
raise DBTagNotFound()
return tag

@staticmethod
def add_tag_to_game(game_id: str, user_id: str, tag_name: str) -> None:
session = current_app.config['db']()
def add_tag_to_game(session, game_id: str, user_id: str, tag_name: str) -> None:
tag: Tag = session.query(Tag).filter(Tag.owner == user_id, Tag.name == tag_name).first()
if tag is None:
raise DBTagNotFound()
Expand All @@ -67,16 +51,10 @@ def add_tag_to_game(game_id: str, user_id: str, tag_name: str) -> None:
game.tags.append(tag)
session.commit()
# TODO maybe add else
session.close()

@staticmethod
def remove_tag_from_game(game_id: str, user_id: str, tag_name: str) -> None:
session = current_app.config['db']()
try:
tag = TagWrapper.get_tag(user_id, tag_name, session)
except DBTagNotFound:
session.close()
raise DBTagNotFound()
def remove_tag_from_game(session, game_id: str, user_id: str, tag_name: str) -> None:
tag = TagWrapper.get_tag(session, user_id, tag_name)
game = session.query(Game).filter(Game.hash == game_id).first()
if game is None:
raise ReplayNotFound()
Expand All @@ -85,20 +63,16 @@ def remove_tag_from_game(game_id: str, user_id: str, tag_name: str) -> None:
game.tags.remove(tag)
session.commit()
except ValueError:
session.close()
raise DBTagNotFound()
session.close()

@staticmethod
def get_tagged_games(user_id: str, names):
session = current_app.config['db']()
def get_tagged_games(session, user_id: str, names):
game_tags = session.query(GameTag.game_id) \
.join(Tag) \
.filter(Tag.owner == user_id) \
.filter(Tag.name.in_(names)) \
.group_by(GameTag.game_id) \
.having(func.count(GameTag.game_id) == len(names)).all()
session.close()

if len(game_tags) == 0:
raise ReplayNotFound()
Expand Down
Loading

0 comments on commit 95b9a02

Please sign in to comment.