Beispiel #1
0
    def get(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        db_name = 'curio'
        dbc = DatabaseController()
        result = {}

        population_query = "SELECT fips, pop13_sqmi, \
            ST_AsGeoJSON(wkb_geometry) FROM \
            censustracts;"

        population = dbc.fetch_records(db_name, population_query)

        max_population = 0
        result['population'] = []
        for item in population['data']:
            row_list = item.split('*#*')
            if max_population < float(row_list[1]):
                max_population = float(row_list[1])
            geojson = {}
            geojson['type'] = "Feature"
            geojson['geometry'] = loads(row_list[2])
            row_list[2] = geojson
            result['population'].append(row_list)

        result['max_population'] = max_population

        self.write(json.dumps(result))
Beispiel #2
0
    def get(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        db_name = 'curio'
        dbc = DatabaseController()
        result = {}

        population_query = "SELECT fips, pop13_sqmi, \
            ST_AsGeoJSON(wkb_geometry) FROM \
            censustracts;"

        population = dbc.fetch_records(db_name, population_query)

        max_population = 0
        result['population'] = []
        for item in population['data']:
            row_list = item.split('*#*')
            if max_population < float(row_list[1]):
                max_population = float(row_list[1])
            geojson = {}
            geojson['type'] = "Feature"
            geojson['geometry'] = loads(row_list[2])
            row_list[2] = geojson
            result['population'].append(row_list)

        result['max_population'] = max_population

        self.write(json.dumps(result))
Beispiel #3
0
    def handle_new_request(self, query_function, query_args, request_type):
        # check query_function is a key in the definitions_dict
        if self.request_has_function(query_function):

            if not self.request_query_has_errors(query_function, query_args):
                db = DatabaseController()
                sql = self.definitions_dict[query_function]['sql']

                # run the query on the DB
                self.body = db.run_query(sql, query_args)

                self._set_response(200)
                self.wfile.write(self.body.encode('utf-8'))

                self.request_text_change.emit(self.command + "," + self.path)
                client_address, client_port = self.client_address
                client_text_string = "Request type : " \
                                     + request_type + "\n" \
                                     + "\nIP Address : " \
                                     + str(client_address) \
                                     + "\n\nPort : " \
                                     + str(client_port) \
                                     + "\n\nVariables : \n"

                for key, val in query_args.items():
                    client_text_string += f"{key} : {val}\n"

                self.client_text_change.emit(client_text_string)

                self.response_text_change.emit(self.body)
Beispiel #4
0
class CardImporter:
    def __init__(self, data_folder_path):
        self.folder_path = data_folder_path + "Card/"
        self.table_name = "card"
        columns = [
            "id", "clan", "cost", "deck_limit", "fate", "glory", "honor",
            "influence_cost", "influence_pool", "is_banned", "is_restricted",
            "is_unique", "military", "military_bonus", "name", "name_extra",
            "political", "political_bonus", "role_restriction", "side",
            "strength", "strength_bonus", "text", "type"
        ]
        self.columns = create_comma_separated_string(columns)
        self.key = "id"
        self.update = create_update_on_conflict_statement(columns[1:])
        self.database_controller = DatabaseController()

    def execute_import(self):
        values = []
        for file in listdir(self.folder_path):
            with open(self.folder_path + file,
                      encoding="UTF-8") as card_json_str:
                card_json = json.load(card_json_str)[0]
                value = self.get_value(card_json)
                values.append(value)
        values_string = ", ".join(values)
        self.database_controller.upsert(self.table_name, self.columns,
                                        values_string, self.key, self.update)

    def get_value(self, entry):
        value = "("
        value += "\'" + transform_string(entry["id"]) + "\', "
        value += get_nullable_value(entry, "clan") + ", "
        value += get_nullable_value(entry, "cost") + ", "
        value += get_nullable_value(entry, "deck_limit") + ", "
        value += get_nullable_value(entry, "fate") + ", "
        value += get_nullable_value(entry, "glory") + ", "
        value += get_nullable_value(entry, "honor") + ", "
        value += get_nullable_value(entry, "influence_cost") + ", "
        value += get_nullable_value(entry, "influence_pool") + ", "
        value += get_nullable_value(entry, "is_banned") + ", "
        value += get_nullable_value(entry, "is_restricted") + ", "
        value += get_nullable_value(entry, "unicity") + ", "
        value += get_nullable_value(entry, "military") + ", "
        value += get_nullable_value(entry, "military_bonus") + ", "
        value += get_nullable_value(entry, "name") + ", "
        value += get_nullable_value(entry, "name_extra") + ", "
        value += get_nullable_value(entry, "political") + ", "
        value += get_nullable_value(entry, "political_bonus") + ", "
        value += get_nullable_value(entry, "role_restriction") + ", "
        value += get_nullable_value(entry, "side") + ", "
        value += get_nullable_value(entry, "strength") + ", "
        value += get_nullable_value(entry, "strength_bonus") + ", "
        value += get_nullable_value(entry, "text") + ", "
        value += get_nullable_value(entry, "type")
        value += ")"
        return value
Beispiel #5
0
 def __init__(self, data_folder_path):
     self.folder_path = data_folder_path + "Card/"
     self.table_name = "card"
     columns = [
         "id", "clan", "cost", "deck_limit", "fate", "glory", "honor",
         "influence_cost", "influence_pool", "is_banned", "is_restricted",
         "is_unique", "military", "military_bonus", "name", "name_extra",
         "political", "political_bonus", "role_restriction", "side",
         "strength", "strength_bonus", "text", "type"
     ]
     self.columns = create_comma_separated_string(columns)
     self.key = "id"
     self.update = create_update_on_conflict_statement(columns[1:])
     self.database_controller = DatabaseController()
Beispiel #6
0
 def __init__(self, data_folder_path):
     self.data_file = data_folder_path + "Label/en.json"
     self.table_name = "label"
     columns = ["id", "value"]
     self.columns = create_comma_separated_string(columns)
     self.key = "id"
     self.update = create_update_on_conflict_statement(columns[1:])
     self.database_controller = DatabaseController()
 def __init__(self, data_folder_path):
     self.data_file = data_folder_path + "Cycle.json"
     self.table_name = "cycle"
     columns = ["id", "name", "position", "size"]
     self.columns = create_comma_separated_string(columns)
     self.key = "id"
     self.update = create_update_on_conflict_statement(columns[1:])
     self.database_controller = DatabaseController()
Beispiel #8
0
    def get(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        db_name = 'curio'
        dbc = DatabaseController()

        result = {}
        result['station_details'] = []
        result['station_availability'] = []


        station_details_query = "SELECT station_id, station_name, \
            lat, lng FROM cogo_stations ORDER BY station_id;"

        station_details = dbc.fetch_records(db_name, \
            station_details_query)

        for item in station_details['data']:
            row_list = item.split('*#*')
            result['station_details'].append(row_list)


        station_availability_query = "SELECT \
                    cogo_station_status.station_id, \
                    available_docks, total_docks, \
                    available_bikes, avail_time, lat, lng FROM \
                    cogo_station_status INNER JOIN cogo_stations \
                    ON cogo_station_status.station_id = \
                    cogo_stations.station_id \
                    GROUP BY avail_time, \
                    cogo_station_status.obj_id, lat, lng \
                    ORDER BY avail_time DESC, \
                    cogo_station_status.station_id;"

        station_availability = dbc.fetch_records(db_name, \
            station_availability_query)

        time_fmt = '%Y-%m-%d %H:%M:%S'
        for item in station_availability['data']:
            row_list = item.split('*#*')
            # tstamp = datetime.strptime(row_list[4], time_fmt)
            result['station_availability'].append(row_list)


        self.write(json.dumps(result))
Beispiel #9
0
class Manager:
    """All program-user interactions and operations handling."""

    logger = logging.getLogger('manager')
    logging.basicConfig(level=logging.INFO)

    def __init__(self):
        self.dc = DatabaseController()

    def read_username(self) -> str:
        """Read username and check in database if it's unique.

        :return: user username
        :rtype: str
        """

        self.logger.info('Enter username (3 characters length min.): ')
        username = input()
        while self.dc.user_exists_in_database(username) or len(username) < 3:
            self.logger.info('Username taken or invalid, choose another username (3 characters length min.):')
            username = input()
        return username

    def read_password(self) -> str:
        """Read and make user confirm his password.

        :return: user password
        :rtype: str
        """

        self.logger.info('Enter your password (3 characters length min.): ')
        password = input()
        self.logger.info('Repeat your password: '******'Invalid password, try again (3 characters length min.): ')
            password = input()
            self.logger.info('Repeat your password: '******'t add user.")
            self.logger.info(type(ae))
            self.logger.info(ae)
        else:
            self.logger.info('User added.')

    def show_users(self) -> None:
        """Displays all user data from database."""

        for user in self.dc.get_all_users():
            self.logger.info(user)

    def log_in(self) -> bool:
        """Verifies login and password, simulates logging in with given credentials.

        :return: True if logged in, False if not
        :rtype: bool
        """

        self.logger.info('Enter your username:'******'Enter your password:'******'No account with given username found.')
            return False
        else:
            if h.check_if_hashed_passwords_match(password, user):
                self.logger.info('Successfully logged in.')
                return True
            else:
                self.logger.info('Wrong password, try to log in again.')
                return False

    def delete_user(self) -> None:
        """Deletes user from database."""

        self.logger.info('Enter username of user you want to be deleted:')
        username = input()
        try:
            self.dc.delete_user(username)
        except ValueError as e:
            self.logger.info('There is no user with that username.')
        else:
            self.logger.info('User deleted.')
Beispiel #10
0
 def __init__(self):
     self.dc = DatabaseController()
Beispiel #11
0
def profile(databases, count, iterations):
    '''
  Main method of profiling.

  Will perform n iterations of all tasks specified on all databases specified.
  '''

    database_controller = DatabaseController(databases, count)

    database_controller.connect()

    for i in xrange(iterations):
        database_controller.insert()
        database_controller.read()
        database_controller.delete()

    database_controller.close()

    database_controller.report()