Exemplo n.º 1
0
    def init_appconfig(self):
        if self.appconfig is None:
            self.appconfig = AppConfig()

        self.appconfig_exists = self.appconfig.exists()
        if self.appconfig_exists:
            self.appconfig.load()
Exemplo n.º 2
0
def main():
    #load the config
    config = AppConfig()

    print('start')
    """Start the bot."""
    # Create the EventHandler and pass it your bot's token.
    print(config.config['Telegram']['key'])
    updater = Updater(config.config['Telegram']['key'])

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("convert", convert))

    # on noncommand i.e message - echo the message on Telegram
    #dp.add_handler(MessageHandler(Filters.text, convert))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
    def test_get_description_illegal_values(self):
        ''' Test what happens if illegal or not existing values are being
            tried to be accessed.
        '''
        config = AppConfig()
        config.init_default_config(os.path.join(self.config_dir,
                'test_data.txt'))

        # try to access a value that does not exist
        with self.assertRaises(AppConfigValueException):
            config.get_description('server', 'alpha')

        # set a new value with no description and access it.
        config.set('server', 'alpha', "12")
        desc, ctype, default = config.get_description('server', 'alpha')
        self.assertTrue(desc == '')
        self.assertTrue(default == '')
        self.assertTrue(ctype == str)

        # access section which does not exist
        with self.assertRaises(AppConfigValueException):
            config.get_description('sunrise', 'alpha')

        # set value of a not existing section and access it again
        config.set('sunrise', 'alpha', 12)
        desc, ctype, default = config.get_description('sunrise', 'alpha')
        self.assertTrue(desc == '')
        self.assertTrue(default == '')
        self.assertTrue(ctype == str)
    def test_init_config(self):
        ''' Initialize the config object with default values and check values.
        '''
        config = AppConfig()
        with self.assertRaises(AppConfigValueException):
            config.init_default_config(os.path.join(self.config_dir,
                    'test_config.txt'))
        config.init_default_config(os.path.join(self.config_dir,
                'test_data.txt'))

        self.assertTrue(config.application_name == 'appconfig_test')
        self.assertTrue(config.application_author == 'python')
        self.assertTrue(config.application_version == '1.0')

        self._check_value(config, 'client', 'first', 'Aldebarans', str,
                'Start', 'Start')
        self._check_value(config, 'client', 'second', 'Altairians', unicode,
                'Stop', 'Stop')
        self._check_value(config, 'client', 'third', 'Amoeboid Zingatularians',
                int, 12, 12)
        self._check_value(config, 'client', 'forth', 'Bartledanians', float,
                12.2, 12.2)
        self._check_value(config, 'client', 'fifth', 'Belcerebons', bool, True,
                True)

        self._check_value(config, 'server', 'first', 'Betelgeusians', str,
                'End', 'End')
        self._check_value(config, 'server', 'second', 'Blagulon Kappans',
                unicode, 'Accelerate', 'Accelerate')
        self._check_value(config, 'server', 'third', 'Dentrassis', int, -12,
                -12)
        self._check_value(config, 'server', 'forth', 'Dolphins', float, 3.3333,
                3.3333)
        self._check_value(config, 'server', 'fifth',
                "G'Gugvunnts and Vl'hurgs", bool, False, False)
Exemplo n.º 5
0
    def __init__(self, config):

        self.__config = AppConfig().databaseOptions().get('sqlite').get(config)
        self.__dbfile = self.__config.get('dbfile')
        self.__pragma = self.__config.get('pragma')
        self.__conn = None

        # init data dir if not exists
        dataDir = os.path.sep.join(self.__dbfile.split(os.path.sep)[:-1])
        os.makedirs(dataDir, exist_ok=True)
Exemplo n.º 6
0
 def parse_file(control_filename):
     with open(control_filename) as f:
         parsed_yaml = yaml.load(f)
     filenames_list = parsed_yaml["files"]
     app_config_files = [
         AppConfigFile(os.path.join(System.frontdown_dir,
                                    files["source"]), files["target"],
                       files.get("link")) for files in filenames_list
     ]
     app_config = AppConfig(app_config_files)
     return app_config
Exemplo n.º 7
0
    def __init__(self):

        self.__sessionOption = AppConfig().sessionOptions()

        # check if folder not exist then create the data dir
        dataDir = self.__sessionOption.get('data_dir')
        if dataDir and not os.path.isdir(dataDir):
            try:
                os.makedirs(dataDir)

            except Exception as ex:
                print(ex)
Exemplo n.º 8
0
def serverStart(kwargs={}):
    app = Bottle()
    appConfig = AppConfig()
    bottle.TEMPLATES.clear()

    # register routes
    for appRoute in appConfig.registerRoutes():
        app.route(appRoute[0], appRoute[1], appRoute[2])

    # start system cleaner
    SystemCleaner().startCleaner()

    serverOptions = appConfig.severOptions()
    host = serverOptions.get('host') if not kwargs.get('host') else kwargs.get('host')
    port = serverOptions.get('port') if not kwargs.get('port') else kwargs.get('port')
    reloader = serverOptions.get('reloader') if not kwargs.get('reloader') else kwargs.get('reloader')
    debug = serverOptions.get('debug') if not kwargs.get('debug') else kwargs.get('debug')
    server = serverOptions.get('server') if not kwargs.get('server') else kwargs.get('server')
    interval = serverOptions.get('interval') if not kwargs.get('interval') else kwargs.get('interval')
    certfile = serverOptions.get('ssl').get('certfile') if not kwargs.get('certfile') else kwargs.get('certfile')
    keyfile = serverOptions.get('ssl').get('keyfile') if not kwargs.get('keyfile') else kwargs.get('keyfile')
    
    if os.access(os.getcwd(), os.W_OK) or (os.is_file(appserverPIDFile) and os.access(appserverPIDFile, os.W_OK)):
        # try to check the address already bind or not
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        alreadyRun = False
        try:
            s.bind((host, port))
            writePID(str(os.getpid()))

        except Exception as ex:
            alreadyRun = True
            print('server already running or address already in used {}:{} -> {}'.format(host, port, ex))

            # if in debug mode try kill the server and force alradyRun to false
            if reloader and debug:
                serverStop(kwargs)
                alreadyRun = False

        finally:
            s.close()

        if not alreadyRun:
            overrideBuiltinPrint()

            if certfile is None or keyfile is None:
                run(app=app, host=host, port=port, reloader=reloader, debug=debug, server=server, interval=interval)

            else:
                run(app=app, host=host, port=port, reloader=reloader, debug=debug, server=server, interval=interval, certfile=certfile, keyfile=keyfile)

    else:
        print('''You don't have write access to {}, need read write access!'''.format(os.getcwd()))
    def test_save_default_config(self):
        ''' Test the save functionality of the config module '''
        config = AppConfig()
        config.init_default_config(os.path.join(self.config_dir,
                'test_data.txt'))

        config.save(os.path.join(self.config_dir, 'test_default_output.txt'))
        config.save(os.path.join(self.config_dir,
                'test_default_output_verbose.txt'), True)
        # with directory
        config.save(os.path.join(self.config_dir, 'step',
                'test_default_output.txt'))

        config.set('client', 'first', 42)
        config.set('client', 'second', 42)
        config.set('server', 'first', 42)
        config.set('server', 'second', 42)
        config.save(os.path.join(self.config_dir, 'test_save_output.txt'))
        config.save(os.path.join(self.config_dir,
                'test_save_output_verbose.txt'), True)

        # read the generated default output file (only two sections expected
        # nothing else should be in here since we haven't changed one value.
        sections, values, comments = \
                self._parse_config_file('test_default_output.txt')
        self.assertTrue(sections == 2)
        self.assertTrue(values == 0)
        self.assertTrue(comments == 0)

        # search the verbose file with 3 lines of comment for each entry
        sections, values, comments = \
                self._parse_config_file('test_default_output_verbose.txt')
        self.assertTrue(sections == 2)
        self.assertTrue(values == 0)
        self.assertTrue(comments == 30)

        # read the config file after two value for each section where set
        sections, values, comments = \
                self._parse_config_file('test_save_output.txt')
        self.assertTrue(sections == 2)
        self.assertTrue(values == 4)
        self.assertTrue(comments == 0)

        # search the verbose file with 3 lines of comment for each entry and
        # some value where set with a none standard value
        sections, values, comments = \
                self._parse_config_file('test_save_output_verbose.txt')
        self.assertTrue(sections == 2)
        self.assertTrue(values == 4)
        self.assertTrue(comments == 30)
Exemplo n.º 10
0
    def get_javascript_links(self, file_or_Link):
        ## returns and can even save  a list of
        # all javascript links to a database
        # managed by appconfi
        js = self.find_all_elements(file_or_Link, 'script')
        jsfilelinks = []
        for ele in js:

            link = self.get_attribute(ele, 'src')
            link = self.strip_link(link)
            jsfilelinks.append(link)

        AppConfig().new_data('js', file_or_Link, jsfilelinks)

        return jsfilelinks
Exemplo n.º 11
0
    def __init__(self, config):
        self.__config = AppConfig().databaseOptions().get('mongodb').get(
            config)
        self.__host = self.__config.get('host')
        self.__user = self.__config.get('user')
        self.__port = self.__config.get('port')
        self.__password = self.__config.get('password')
        self.__sslCertFile = self.__config.get('ssl_certfile')
        self.__sslKeyFile = self.__config.get('ssl_keyfile')
        self.__sslPassphrase = self.__config.get('ssl_pem_passphrase')
        self.__useSsl = False

        if self.__sslCertFile and self.__sslKeyFile:
            self.__useSsl = True

        self.__conn = None
Exemplo n.º 12
0
    def __init__(self, config):
        self.__config = AppConfig().databaseOptions().get('mariadb').get(
            config)
        self.__host = self.__config.get('host')
        self.__user = self.__config.get('user')
        self.__port = self.__config.get('port')
        self.__password = self.__config.get('password')
        self.__db = self.__config.get('db')
        self.__ssl = {}

        ssl = self.__config.get('ssl')
        if ssl:
            for sslcert in ssl:
                if ssl.get(sslcert):
                    self.__ssl[sslcert] = ssl.ge(sslcert)

        self.__conn = None
Exemplo n.º 13
0
    def __init__(self):

        self.__sessionOption = AppConfig().sessionOptions()

        # check if folder not exist then create the data dir
        dataDir = self.__sessionOption.get('data_dir')
        if dataDir and not os.path.isdir(dataDir):
            try:
                os.makedirs(dataDir)

            except Exception as ex:
                print(ex)

        # initialize session
        # add default session
        currentUtcTime = self.__getCurrentUtcTimeHash()

        # init session if not exist
        request.get_cookie('s', currentUtcTime.get('hexdigest'))
Exemplo n.º 14
0
    def __init__(self, config):
        self.__config = AppConfig().databaseOptions().get('postgre').get(
            config)
        self.__host = self.__config.get('host')
        self.__user = self.__config.get('user')
        self.__port = self.__config.get('port')
        self.__password = self.__config.get('password')
        self.__db = self.__config.get('db')
        self.__sslMode = 'disable'
        self.__sslrootcert = None
        self.__sslcert = None
        self.__sslkey = None

        ssl = self.__config.get('ssl')
        if ssl:
            self.__sslrootcert = ssl.get('sslrootcert')
            self.__sslcert = ssl.get('sslcert')
            self.__sslkey = ssl.get('sslkey')

            if self.__sslrootcert or self.__sslcert or self.__sslkey:
                self.__sslMode = 'verify-full'

        self.__conn = None
Exemplo n.º 15
0
 def debugPrint(*args, **kwargs):
     if AppConfig().severOptions().get('debug'):
         _print(*args, **kwargs)
Exemplo n.º 16
0
    def checkConsistancy(self):
        errFound = False
        print("Question Bank: Consistancy Check... ")
        if not self.qb:
            print("Consistancy Check called without setting Question Bank")
        for t in self.testsAll.keys():  # Scan all tests
            tData = self.testsAll[t]
            qs = self.qb.getQuestions(tData["Qbank1"][0], tData["Qbank1"][1], level=tData["Qbank1"][3], \
                 numOfQuestions = tData["Qbank1"][2], retType='D', exam=True)
            if len(qs) != tData["NoOfQuestions"]:
                errFound = True
                print(
                    tData["TestName"] +
                    " Does not have enough questions or Questio Bank specified does not exist."
                )
        if errFound:
            exit(1)
        else:
            return True


if __name__ == "__main__":
    appC = AppConfig(
        "C:\\Users\\kambhs\\Desktop\\Projects\\OnlineExam\\OnlineExamConfig.xlsx"
    )
    qb = QuestionBank(appC)
    testBank = TestBank(appC)
    testBank.setQuestionBank(qb)
    testBank.getQuestions('Java Level 1', exam=True)
    testBank.getTestList(retType='D')
    def test_set_config(self):
        ''' Test seting and getting values from the config object '''
        config = AppConfig()

        # tests without default config loaded
        config.set('client', 'first', 12)
        value = config.get_s('client', 'first')
        self.assertTrue(type(value) == str)
        # this is a string since we don't now anything about it
        self.assertTrue(value == '12')

        config.set('client', 'third', -16)
        value = config.get_s('client', 'third')
        self.assertTrue(type(value) == str)
        # this is a string since we don't now anything about it
        self.assertTrue(value == '-16')

        # and now with default config loaded
        config.init_default_config(os.path.join(self.config_dir,
                'test_data.txt'))

        # check previous set values if the previous value remains.
        self._check_value(config, 'client', 'first', 'Aldebarans', str,
                'Start', "12")
        self._check_value(config, 'client', 'third',
                'Amoeboid Zingatularians', int, 12, -16)

        # now do some test for all kind of types
        config.set('client', 'first', 112)
        self._check_value(config, 'client', 'first', 'Aldebarans', str,
                'Start', "112")
        config.set('client', 'second', 12.45)
        self._check_value(config, 'client', 'second', 'Altairians', unicode,
                'Stop', '12.45')
        config.set('client', 'third', -166)
        self._check_value(config, 'client', 'third',
                'Amoeboid Zingatularians', int, 12, -166)
        config.set('client', 'forth', 11)
        self._check_value(config, 'client', 'forth', 'Bartledanians', float,
                12.2, 11.0)
        config.set('client', 'fifth', False)
        self._check_value(config, 'client', 'fifth', 'Belcerebons', bool,
                True, False)
        # the same with a string
        config.set('client', 'fifth', "False")
        self._check_value(config, 'client', 'fifth', 'Belcerebons', bool,
                True, False)
        config.set('client', 'fifth', "True")
        self._check_value(config, 'client', 'fifth', 'Belcerebons', bool,
                True, True)
        # the same with numbers
        config.set('client', 'fifth', 0)
        self._check_value(config, 'client', 'fifth', 'Belcerebons', bool,
                True, False)
        config.set('client', 'fifth', 1)
        self._check_value(config, 'client', 'fifth', 'Belcerebons', bool,
                True, True)
        # with illegal value
        with self.assertRaises(AppConfigValueException):
            config.set('client', 'fifth', 'no')

        config.set('server', 'first', True)
        self._check_value(config, 'server', 'first', 'Betelgeusians', str,
                'End', 'True')
        config.set('server', 'second', "Arther Dent")
        self._check_value(config, 'server', 'second', 'Blagulon Kappans',
                unicode, 'Accelerate', 'Arther Dent')
        config.set('server', 'third', 42)
        self._check_value(config, 'server', 'third', 'Dentrassis', int, -12,
                42)
        config.set('server', 'forth', 42.43)
        self._check_value(config, 'server', 'forth', 'Dolphins', float,
                3.3333, 42.43)
        config.set('server', 'fifth', True)
        self._check_value(config, 'server', 'fifth',
                "G'Gugvunnts and Vl'hurgs", bool, False, True)
sys.path.insert(0, '../..')

# from candidateinterface import CandidateInteface
from questionbank import QuestionBank
from testbank import TestBank
from appconfig import AppConfig
from flask_cache import Cache

app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

# Create our own items and get ready
# TODO: ALl DB Parameters need to come from the XLS-FILE..but that gets more UNSAFE from security perspective
appC = AppConfig("OnlineExamConfig.xlsx")
questionsBanks = QuestionBank(appC)
testBank = TestBank(appC)
testBank.setQuestionBank(questionsBanks)
testBank.checkConsistancy()

# app = Flask(__name__)

# login = LoginManager(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "/login"
login_manager.unauthorized_handler = '/login'

app.config[
    "SQLALCHEMY_DATABASE_URI"] = "mysql://*****:*****@localhost:3306/online_exam"
Exemplo n.º 19
0
 def __init__(self, config):
     appConfig = AppConfig().imapOptions()
     self.__config = appConfig.get(config)
     self.__dataDir = os.path.sep.join((self.__config.get('data_dir'), self.__config.get('user')))
Exemplo n.º 20
0
 def __init__(self, config):
     appConfig = AppConfig().smtpOptions()
     self.__config = appConfig.get(config)
Exemplo n.º 21
0
# Load the kubernetes configuration from the kubeconfig file
try:
    config.load_incluster_config()
except:
    try:
        config.load_kube_config()
    except:
        log.fatal("Cannot load neither incluster or kubeconfig.")
        sys.exit(1)

# Instantiate the kubernetes clients
v1 = client.CoreV1Api()
extv1beta1 = client.ExtensionsV1beta1Api()

# Load the app config
appConfig = AppConfig()

# Get the public ips
ips = find_ips(v1)
log.info("Found external ip addresses: %s" % ips)

# Log config
log.info("Watching ingresses with annotation %s" %
         appConfig.annotation_trigger)

# Instantiate the watcher
w = watch.Watch()

# Configure signal handlers
signal.signal(signal.SIGINT, lambda s, frame: w.stop())
signal.signal(signal.SIGINT, lambda s, frame: log.critical("Received SIGINT"))
    def test_loading_illegal_config_description_files(self):
        ''' Test the mechanism to load config description files with illegal
            values.
        '''
        # read simple config description file with missing value (default
        # value)
        data = {"application_name": 'appconfig-test',
                "Client": {
                    "fifth": {"type": "bool",
                        "description": "Belcerebons"}}}
        dfd = open(os.path.join(self.config_dir, 'test_data2.txt'), 'w')
        dfd.write(json.dumps(data))
        dfd.close()

        with self.assertRaises(AppConfigValueException):
            config = AppConfig()
            config.init_default_config(os.path.join(self.config_dir,
                    'test_data2.txt'))

        # read simple config description file with missing value (type
        # value)
        data = {"application_name": 'appconfig-test',
                "Client": {
                    "fifth": {"default": True,
                        "description": "Belcerebons"}}}
        dfd = open(os.path.join(self.config_dir, 'test_data2.txt'), 'w')
        dfd.write(json.dumps(data))
        dfd.close()

        with self.assertRaises(AppConfigValueException):
            config = AppConfig()
            config.init_default_config(os.path.join(self.config_dir,
                    'test_data2.txt'))

        # read simple config description file with missing value (description
        # value)
        data = {"application_name": 'appconfig-test',
                "Client": {
                    "fifth": {"default": True, "type": 'bool'}}}
        dfd = open(os.path.join(self.config_dir, 'test_data2.txt'), 'w')
        dfd.write(json.dumps(data))
        dfd.close()

        with self.assertRaises(AppConfigValueException):
            config = AppConfig()
            config.init_default_config(os.path.join(self.config_dir,
                    'test_data2.txt'))

        # read simple config description file with an unsuproted type
        data = {"application_name": 'appconfig-test',
                "Client": {
                    "fifth": {"default": True, "type": 'value',
                        "description": "Belcerebons"}}}
        dfd = open(os.path.join(self.config_dir, 'test_data2.txt'), 'w')
        dfd.write(json.dumps(data))
        dfd.close()

        with self.assertRaises(AppConfigValueException):
            config = AppConfig()
            config.init_default_config(os.path.join(self.config_dir,
                    'test_data2.txt'))
Exemplo n.º 23
0
    def __init__(self):

        self.__systemToClean = AppConfig().systemCleaner()