Update build script for client/server use.
This commit is contained in:
11
dsst/dsst_server/__main__.py
Normal file
11
dsst/dsst_server/__main__.py
Normal file
@@ -0,0 +1,11 @@
|
||||
import os.path
|
||||
import sys
|
||||
|
||||
# Add current directory to python path
|
||||
path = os.path.realpath(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(path)))
|
||||
|
||||
from dsst_server import server
|
||||
|
||||
if __name__ == '__main__':
|
||||
server.main()
|
||||
@@ -3,10 +3,21 @@ from common import models
|
||||
|
||||
|
||||
def map_base_fields(cls, db_model):
|
||||
"""Automatically map fields of db models to common models
|
||||
:param cls: common.models class to create
|
||||
:param db_model: database model from which to map
|
||||
:return: An common.models object
|
||||
"""
|
||||
model = cls()
|
||||
attrs = [attr for attr in db_model._meta.fields]
|
||||
for attr in attrs:
|
||||
setattr(model, attr, getattr(db_model, attr))
|
||||
db_attr = getattr(db_model, attr)
|
||||
# Check if the attribute is an relation to another db model
|
||||
# In that case just take its id
|
||||
if hasattr(db_attr, 'id'):
|
||||
setattr(model, attr, getattr(db_attr, 'id'))
|
||||
else:
|
||||
setattr(model, attr, getattr(db_model, attr))
|
||||
return model
|
||||
|
||||
|
||||
|
||||
@@ -5,8 +5,12 @@ Example:
|
||||
from sql import Episode
|
||||
query = Episode.select().where(Episode.name == 'MyName')
|
||||
"""
|
||||
|
||||
from peewee import *
|
||||
import sys
|
||||
try:
|
||||
from peewee import *
|
||||
except ImportError:
|
||||
print('peewee package not installed')
|
||||
sys.exit(0)
|
||||
|
||||
db = MySQLDatabase(None)
|
||||
|
||||
@@ -56,7 +60,7 @@ class Drink(Model):
|
||||
class Enemy(Model):
|
||||
id = AutoField()
|
||||
name = CharField()
|
||||
optional = BooleanField()
|
||||
boss = BooleanField()
|
||||
season = ForeignKeyField(Season, backref='enemies')
|
||||
|
||||
class Meta:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
This module contains shorthand functions for common queries to ease access from the UI
|
||||
"""
|
||||
from data_access.sql import *
|
||||
from dsst_server.data_access import sql
|
||||
|
||||
|
||||
def get_episodes_for_season(season_id: int) -> list:
|
||||
@@ -10,8 +10,8 @@ def get_episodes_for_season(season_id: int) -> list:
|
||||
:return: List of sql.Episode or empty list
|
||||
"""
|
||||
try:
|
||||
return list(Season.get(Season.id == season_id).episodes)
|
||||
except Episode.DoesNotExist:
|
||||
return list(sql.Season.get(sql.Season.id == season_id).episodes)
|
||||
except sql.Episode.DoesNotExist:
|
||||
return []
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ def get_player_deaths_for_season(season_id: int, player_id: int) -> int:
|
||||
:return: Number of deaths of the player in the season
|
||||
"""
|
||||
deaths = 0
|
||||
for episode in list(Season.get(Season.id == season_id).episodes):
|
||||
for episode in list(sql.Season.get(sql.Season.id == season_id).episodes):
|
||||
deaths = deaths + len([death for death in list(episode.deaths) if death.player.id == player_id])
|
||||
return deaths
|
||||
|
||||
@@ -34,19 +34,33 @@ def get_player_victories_for_season(season_id: int, player_id: int) -> int:
|
||||
:return: Number of all victories of the player in the season
|
||||
"""
|
||||
victories = 0
|
||||
for episode in list(Season.get(Season.id == season_id).episodes):
|
||||
for episode in list(sql.Season.get(sql.Season.id == season_id).episodes):
|
||||
victories = victories + len([vic for vic in list(episode.victories) if vic.player.id == player_id])
|
||||
return victories
|
||||
|
||||
|
||||
def players_for_season(season_id: int) -> set:
|
||||
season_eps = list(sql.Season.get(sql.Season.id == season_id).episodes)
|
||||
players = set()
|
||||
for ep in season_eps:
|
||||
players.update([player for player in ep.players])
|
||||
return players
|
||||
|
||||
|
||||
def enemy_attempts(enemy_id: int) -> int:
|
||||
return sql.Death.select().where(sql.Death.enemy == enemy_id).count()
|
||||
|
||||
|
||||
def create_tables():
|
||||
"""Create all database tables"""
|
||||
models = [Season, Episode, Player, Drink, Enemy, Death, Victory, Penalty, Episode.players.get_through_model()]
|
||||
models = [sql.Season, sql.Episode, sql.Player, sql.Drink, sql.Enemy, sql.Death, sql.Victory, sql.Penalty,
|
||||
sql.Episode.players.get_through_model()]
|
||||
for model in models:
|
||||
model.create_table()
|
||||
|
||||
|
||||
def drop_tables():
|
||||
"""Drop all data in database"""
|
||||
models = [Season, Episode, Player, Drink, Enemy, Death, Victory, Penalty, Episode.players.get_through_model()]
|
||||
db.drop_tables(models)
|
||||
models = [sql.Season, sql.Episode, sql.Player, sql.Drink, sql.Enemy, sql.Death, sql.Victory, sql.Penalty,
|
||||
sql.Episode.players.get_through_model()]
|
||||
sql.db.drop_tables(models)
|
||||
@@ -4,6 +4,9 @@ from playhouse import shortcuts
|
||||
|
||||
|
||||
class ReadFunctions:
|
||||
@staticmethod
|
||||
def load_db_meta(*_):
|
||||
return sql.db.database
|
||||
|
||||
@staticmethod
|
||||
def load_seasons(*_):
|
||||
@@ -25,4 +28,20 @@ class ReadFunctions:
|
||||
|
||||
@staticmethod
|
||||
def load_drinks(*_):
|
||||
return [mapping.db_to_drink(drink) for drink in sql.Drink.select()]
|
||||
return [mapping.db_to_drink(drink) for drink in sql.Drink.select()]
|
||||
|
||||
@staticmethod
|
||||
def load_season_stats(season_id, *_):
|
||||
season = sql.Season.get(sql.Season.id == season_id)
|
||||
players = sql_func.players_for_season(season_id)
|
||||
model = models.SeasonStats()
|
||||
model.player_kd = [(player.name,
|
||||
sql_func.get_player_victories_for_season(season_id, player.id),
|
||||
sql_func.get_player_deaths_for_season(season_id, player.id))
|
||||
for player in players]
|
||||
model.enemies = [(enemy.name,
|
||||
sql_func.enemy_attempts(enemy.id),
|
||||
sql.Victory.select().where(sql.Victory.enemy == enemy.id).exists(),
|
||||
enemy.boss)
|
||||
for enemy in season.enemies]
|
||||
return model
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import pickle
|
||||
import socket
|
||||
|
||||
@@ -8,7 +9,7 @@ import os
|
||||
from common import util, models
|
||||
from dsst_server import read_functions, write_functions, tokens
|
||||
from dsst_server.func_proxy import FunctionProxy
|
||||
from dsst_server.data_access import sql
|
||||
from dsst_server.data_access import sql, sql_func
|
||||
|
||||
PORT = 12345
|
||||
HOST = socket.gethostname()
|
||||
@@ -16,16 +17,18 @@ BUFFER_SIZE = 1024
|
||||
|
||||
|
||||
class DsstServer:
|
||||
def __init__(self):
|
||||
def __init__(self, config={}):
|
||||
self.socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
print('Created socket')
|
||||
|
||||
self.socket_server.bind((HOST, PORT))
|
||||
print(f'Bound socket to {PORT} on host {HOST}')
|
||||
print('Bound socket to {} on host {}'.format(PORT, HOST))
|
||||
|
||||
# Initialize database
|
||||
sql.db.init('dsst', user='dsst', password='dsst')
|
||||
print(f'Database initialized ({sql.db.database})')
|
||||
db_config = config.get('database')
|
||||
sql.db.init(db_config.get('db_name'), user=db_config.get('user'), password=db_config.get('password'))
|
||||
sql_func.create_tables()
|
||||
print('Database initialized ({})'.format(sql.db.database))
|
||||
|
||||
# Load access tokens and map them to their allowed methods
|
||||
read_actions = util.list_class_methods(read_functions.ReadFunctions)
|
||||
@@ -35,7 +38,7 @@ class DsstServer:
|
||||
'rw': read_actions + write_actions
|
||||
}
|
||||
self.tokens = {token: parm_access[perms] for token, perms in tokens.TOKENS}
|
||||
print(f'Loaded auth tokens: {self.tokens.keys()}')
|
||||
print('Loaded auth tokens: {}'.format(self.tokens.keys()))
|
||||
|
||||
def run(self):
|
||||
self.socket_server.listen(5)
|
||||
@@ -44,15 +47,15 @@ class DsstServer:
|
||||
while True:
|
||||
client, address = self.socket_server.accept()
|
||||
try:
|
||||
print(f'Connection from {address}')
|
||||
print('Connection from {}'.format(address))
|
||||
data = util.recv_msg(client)
|
||||
request = pickle.loads(data)
|
||||
print(f'Request: {request}')
|
||||
print('Request: {}'.format(request))
|
||||
# Validate auth token in request
|
||||
token = request.get('auth_token')
|
||||
if token not in self.tokens:
|
||||
util.send_msg(client, pickle.dumps({'success': False, 'message': 'Auth token invalid'}))
|
||||
print(f'Rejected request from {address}. Auth token invalid ({token})')
|
||||
print('Rejected request from {}. Auth token invalid ({})'.format(address, token))
|
||||
continue
|
||||
# Check read functions
|
||||
action_name = request.get('action')
|
||||
@@ -61,14 +64,14 @@ class DsstServer:
|
||||
try:
|
||||
value = action(request.get('args'))
|
||||
except Exception as e:
|
||||
response = {'success': False, 'message': f'Exception was thrown on server.\n{e}'}
|
||||
response = {'success': False, 'message': 'Exception was thrown on server.\n{}'.format(e)}
|
||||
util.send_msg(client, pickle.dumps(response))
|
||||
raise
|
||||
response = {'success': True, 'data': value}
|
||||
util.send_msg(client, pickle.dumps(response))
|
||||
continue
|
||||
else:
|
||||
msg = f'Action does not exist on server ({request.get("action")})'
|
||||
msg = 'Action does not exist on server ({})'.format(request.get('action'))
|
||||
util.send_msg(client, pickle.dumps({'success': False, 'message': msg}))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
@@ -77,8 +80,14 @@ class DsstServer:
|
||||
print('Connection to client closed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
server = DsstServer()
|
||||
def load_config(config_path: str) -> dict:
|
||||
with open(config_path) as config_file:
|
||||
return json.load(config_file)
|
||||
|
||||
|
||||
def main():
|
||||
config = os.path.join(os.path.expanduser('~'), '.config', 'dsst', 'server.json')
|
||||
server = DsstServer(load_config(config))
|
||||
try:
|
||||
server.run()
|
||||
except KeyboardInterrupt:
|
||||
|
||||
Reference in New Issue
Block a user