예제 #1
0
    async def get_all_feedback(cls, reference: str) -> List[Feedback]:
        Logger(cls.__name__).info(
            f'Getting all feedbacks - reference: {reference}')

        cursor = Mongo.get().feedback.find({
            'reference': reference
        }).sort([('reference', 1)])
        result = []
        while await cursor.fetch_next:
            result.append(cls.__to_object(cursor.next_object()))
        return result
예제 #2
0
def start():
    # Parse command line argument_parsing
    port, processes, db_data, env = ArgumentParsingUtils.parse_arguments()
    # Set up logger
    Logger.set_up()
    # Create Tornado application
    Logger(__name__).info('Setting up application...')
    app = AppCreator.create_app()
    # Start server on given port and with given processes
    ServerCreator.create(app, port).start(processes)
    # Establish database connection for each process
    Mongo.init(**db_data)
    Mongo.create_indexes()
    app.settings['db'] = Mongo.get()
    # Create basic database entries
    ResourceLoader.load_resources(env)
    # Set up rules engine
    SpecialtyResolver.set_up(env)
    PriorityResolver.set_up(env)
    # Start event loop
    Logger(__name__).info(f'Listening on http://localhost:{port}.')
    IOLoop.current().start()
예제 #3
0
    def __init__(self):

        # Request
        self.request = request

        # Jsonify
        self.jsonify = jsonify

        # Flask Framework
        self.flask = Flask(__name__)

        # MongoDB
        self.mongo = Mongo()
예제 #4
0
    def start(cls):
        # Read command line arguments
        context: ApplicationContext = ArgumentParsingUtils.parse_arguments()

        #initiate application logging
        Logger.initiate_logger(context.logger_configs)
        
        #getting logger
        logger = Logger(cls.__name__)
        logger.info('Initializing the application...')
        logger.debug(f'Configurations: {context}')

        settings = {
            'template_path': abspath(join(dirname(__file__), '../../views/templates')),
            'static_path': abspath(join(dirname(__file__), '../../views/static'))
        }
        # Create application by assigning routes and the location of view files
        app = Application(Router.routes(), **settings)
        
        # Server creation
        server = HTTPServer(app)
        server.bind(context.port)
        server.start(context.process)
        
        # Connect to MongoDB server
        Mongo.init(context.db_configs)
        # This is done so that every incoming request has a pointer to the database connection
        app.settings['db'] = Mongo.get()

        # initiating minio client
        MinioClient.init(context.minio_configs)
        # schedule log file uploader in an interval of hours
        scheduler = TornadoScheduler()
        scheduler.add_job(UploadLogsToMinio.upload_files_to_minio, 'interval', hours=context.logger_configs.log_upload_interval)
        scheduler.start()

        logger.info(f'Listining on port {context.port}')
        IOLoop.current().start()
 def collection(cls):
     return Mongo.get().family_groups
예제 #6
0
 def collection(cls):
     return Mongo.get().consultations
예제 #7
0
 def collection(cls):
     return Mongo.get().queue
예제 #8
0
from flask import Blueprint, jsonify

from src.database.mongo import Mongo

api_module = Blueprint('api', __name__, url_prefix='/api')

db = Mongo()


@api_module.route('/')
def api_index():
    return jsonify({"let's pretend this is json": "yes"})
 def collection(cls):
     return Mongo.get().doctors
예제 #10
0
 def collection(cls):
     return Mongo.get().authentication
예제 #11
0
 def collection(cls):
     return Mongo.get().affiliates
예제 #12
0
class UserLeague:

    db = Mongo()
    collection = db.get_collection('user_leagues')

    def __init__(self, user_league_id: Union[str, ObjectId]):
        if isinstance(user_league_id, str):
            user_league_id = ObjectId(user_league_id)

        self._id = user_league_id

        league = self.collection.find_one({"_id": self._id})

        if not league:
            # Can't find that ID
            raise AttributeError()

        self.name = league['name']  # Display Name
        self.participants = league['participants']  # List of User IDs
        self.creator = league['creator']  # The Creator of the League
        self.leagues = league['leagues']  # List of Soccer League IDs

    def add_user(self, user):
        if user._id in self.participants:
            return None

        coll = self.collection
        coll.update_one({'_id': self._id},
                        {'$push': {
                            'participants': user._id
                        }})

        self.participants.append(user._id)

        user.update_user_leagues(self._id)

        return self

    @classmethod
    def new(cls, display_name: str, user, soccer_leagues: list):
        coll = cls.collection

        insert = coll.insert_one({
            "name": display_name,
            "creator": user._id,
            "participants": [user._id],
            "leagues": soccer_leagues
        })

        return UserLeague(insert.inserted_id)

    @classmethod
    def get_all(cls):
        coll = cls.collection

        leagues = [league for league in coll.find()]

        return leagues

    def __str__(self):
        return str(self.json())

    def json(self):
        return jsonify(
            doc_to_dict({
                "_id": self._id,
                "name": self.name,
                "creator": self.creator,
                "participants": self.participants,
                "leagues": self.leagues,
            }))
 def prepare(self):
     # This is needed so that every request can access globally to the database
     Mongo.set(self.settings['db'])
예제 #14
0
"""
Get all available leagues
"""

from pprint import pprint

import requests

from src.data.endpoints import Endpoints
from src.database.mongo import Mongo
from src.util.util import get_logger

logger = get_logger(__name__)
ep = Endpoints()
db = Mongo('data_test')


def update_leagues():
    # Get league data from API
    ## resp = requests.get(ep.leagues, headers=ep.headers)
    url = ep.leagues
    resp = ep.get(url)

    # Select only all TIER_ONE leagues -- others we have no data for
    leagues: list = resp.json()['competitions']
    leagues = [league for league in leagues if league['plan'] == 'TIER_ONE']

    # Select desired database location
    collection = db.get_collection('leagues')

    # Remove all
 def prepare(self):
     Mongo.set(self.settings['db'])
예제 #16
0
 def prepare(self):
     # This is needed so that every request can access globally to the database or lock server
     Mongo.set(self.settings['db'])
     LockManager.set(self.settings['lock_manager'])
예제 #17
0
class User:

    db = Mongo()
    collection = db.get_collection('users')

    def __init__(self, user_id: Union[str, ObjectId]):

        if isinstance(user_id, str):
            user_id = ObjectId(user_id)

        self._id = user_id

        user = self.collection.find_one({"_id": self._id})

        if not user:
            # Can't find that ID
            raise AttributeError()

        self.firebase_id = user['firebase_id']  # User's Firebase ID
        self.name = user['name']  # User's displayname
        self.predictions = user['predictions']  # User's predictions
        self.user_leagues = user['user_leagues']  # User's user_leagues

    def create_user_league(self, name: str):
        # Create the new User League
        user_league = UserLeague.new(name, self, [])

        # Save changes to DB
        coll = self.collection
        coll.update(
            {'_id': self._id},
            {'$push': {'user_leagues': user_league._id}}
        )

        # Mimick the changes locally
        self.user_leagues.append(user_league._id)

        return user_league

    def update_user_leagues(self, league_id: ObjectId):
        coll = self.collection
        coll.update_one(
            {'_id': self._id},
            {'$push': {'user_leagues': league_id}}
        )

        self.user_leagues.append(league_id)

        return self

    @classmethod
    def new(cls, firebase_id: str, name: str):
        coll = cls.collection

        insert = coll.insert_one({
            "firebase_id": firebase_id,
            "name": name,
            "predictions": [],
            "user_leagues": [],
        })

        return User(insert.inserted_id)

    @classmethod
    def authenticate(cls, firebase_token: str, display_name: str):
        # If user exists, return, if not, create

        try:
            decoded_token = auth.verify_id_token(firebase_token)
        except ValueError:
            return json_err("Bad request.")
        except auth.ExpiredIdTokenError:
            return json_err("User token expired.", 401)
        except auth.InvalidIdTokenError:
            return json_err("Can't authenticate user.", 401)

        firebase_id = decoded_token['uid']
        # TODO get display_name from FIREBASE
        # user_name = auth.get_user(firebase_id)['user_name']
        user_name = display_name

        # SAMPLE USERS
        # firebase_id = 'abcdefghijklmnoprst1234'
        # user_name = 'lomix'
        # firebase_id = '12345678901234567890'
        # user_name = 'Jakub'
        # firebase_id = 'whoCares'
        # user_name = 'Zur'

        coll = cls.collection

        user = coll.find_one({'firebase_id': firebase_id})

        if user:
            return User(user['_id'])
        else:
            return cls.new(firebase_id, user_name)

    def __str__(self):
        return str(self.json())

    def json(self):
        return jsonify(
            doc_to_dict({
                "_id": self._id,
                "firebase_id": self.firebase_id,
                "name": self.name,
                "predictions": self.predictions,
                "user_leagues": self.user_leagues,
            })
        )
 def collection(cls):
     return Mongo.get().example