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)
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 get_trial_period(self, last_billing): default_trial_period = AppConfig.get("default_trial_period") if last_billing is None: return default_trial_period url = self.get_url( 'recurring_application_charges/{}.json'.format(last_billing)) header = self.get_header() header['Content-Type'] = 'application/json' r = requests.get(url, headers=header) try: rdict = loads(r.content)['recurring_application_charge'] except KeyError: return default_trial_period activated_on = rdict['activated_on'] if activated_on is None: return default_trial_period activated = datetime.datetime.strptime(activated_on, '%Y-%m-%d') today = datetime.datetime.today() period = default_trial_period - (today - activated).days if period < 0: return 0 if period > default_trial_period: return default_trial_period return period
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
def add_billing(self, last_billing): url = self.get_url('recurring_application_charges.json') header = self.get_header() header['Content-Type'] = 'application/json' trial_days = self.get_trial_period(last_billing) r = requests.post( url, data=dumps({ "recurring_application_charge": { "name": "Recurring charge", "price": 1.99, "test": AppConfig.get("environment") == "development", "trial_days": trial_days, "return_url": "http://{}.myshopify.com/admin/apps/customerce".format( self.shop.name) } }), headers=header) if r.status_code == 201: rdict = loads(r.content)['recurring_application_charge'] self.shop.billing_id = rdict['id'] save_shop(self.shop) return rdict['confirmation_url'] return None
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
def get_button(): shop_name = request.args.get("shop") if shop_name is not None: return send_from_directory( AppConfig.get("shop_scripts_directory"), '{}.js'.format(shop_name.replace('.myshopify.com', ''))) else: abort(404)
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'))
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') if PY2: self._check_value(config, 'client', 'second', 'Altairians', unicode, 'Stop', 'Stop') else: self._check_value(config, 'client', 'second', 'Altairians', str, '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') if PY2: self._check_value(config, 'server', 'second', 'Blagulon Kappans', unicode, 'Accelerate', 'Accelerate') else: self._check_value(config, 'server', 'second', 'Blagulon Kappans', str, '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)
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
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)
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
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
def build_script(shop): var = '' if shop.button_enabled and valid_phone(shop.phone): if shop.sticky_bar_enabled and shop.sticky_label_text is not None and shop.sticky_label_text != '': var = build_text_script(shop) else: var = build_whatsapp_button_script(shop) path = AppConfig.get("shop_scripts_directory") + '{}.js'.format(shop.name) try: remove(path) except FileNotFoundError: pass f = open(path, 'a') f.write(var)
class MongoDbConn(): 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 def connect(self): try: if self.__user != '' and self.__password: self.__conn = pymongo.MongoClient( host=self.__host, port=self.__port, username=self.__user, password=self.__password, ssl=self.__useSsl, ssl_certfile=self.__sslCertFile, ssl_keyfile=self.__sslKeyFile, ssl_pem_passphrase=self.__sslPassphrase) else: self.__conn = pymongo.MongoClient( host=self.__host, port=self.__port, ssl=self.__useSsl, ssl_certfile=self.__sslCertFile, ssl_keyfile=self.__sslKeyFile, ssl_pem_passphrase=self.__sslPassphrase) except Exception as ex: print(ex) return self.__conn def close(self): if self.__conn: self.__conn.close()
def test_load_config(self): ''' test the config file loader ''' tmp_config_file = os.path.join(self.config_dir, 'test_load_config.txt') config = AppConfig() config.init_default_config(os.path.join(self.config_dir, 'test_data.txt')) f = open(tmp_config_file, 'w') f.write('[client]\n') f.write('first = The End\n') f.write('third = 1337\n') f.close() config.load(tmp_config_file) self._check_value(config, 'client', 'first', 'Aldebarans', str, 'Start', 'The End') self._check_value(config, 'client', 'third', 'Amoeboid Zingatularians', int, 12, 1337) os.remove(tmp_config_file) with self.assertRaises(AppConfigValueException): config.load(tmp_config_file)
def __init__(self, config): appConfig = AppConfig().smtpOptions() self.__config = appConfig.get(config)
class SqliteConn(): ''' sqlite connection this connection will depend on the appconfig.py databseOptions: 'sqlite':{ 'conn1': { 'pragma':[the pragma list], 'dbfile':path to database file } } usage: from plugins.dbconn import SqliteConn conn = SqliteConn('conn1') test initialize the table create: from.models.sqlite_example.example_create_table import CreateTableExample conn.createTable(CreateTableExample()) all return value should be in form of: { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':return value of data } data: fetchAll will return list of sqlite row object fetchOne will return one sqlite row object execute will no return any data ''' CODE_OK = 'ok' CODE_FAIL = 'fail' 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) def __connect(self): # connect to sqlite file self.__conn = sqlite3.connect(self.__dbfile) self.__conn.row_factory = sqlite3.Row return self.__conn.cursor() def __close(self): if self.__conn: self.__conn.close() def __executePragma(self, cur): if self.__pragma and len(self.__pragma): cur.executescript(';'.join( ['PRAGMA {}'.format(pragma) for pragma in self.__pragma])) self.__conn.commit() def execute(self, query): ''' execute non return data query, like insert, update, delete data return value: { 'code':'ok'|'fail', 'message':'success message'|'error message' } ''' outputMessage = {'code': SqliteConn.CODE_FAIL, 'message': None} try: cur = self.__connect() self.__executePragma(cur) cur.execute(query) self.__conn.commit() outputMessage['code'] = SqliteConn.CODE_OK outputMessage['message'] = 'Success executed sql command' except Exception as ex: outputMessage['message'] = 'fail executed sql command {}'.format( ex) finally: self.__close() return outputMessage def fetchAll(self, query): ''' fetch all query data as list of row sqlite object { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':None|[list of sqlite row object] } ''' outputMessage = { 'code': SqliteConn.CODE_FAIL, 'message': None, 'data': None } try: cur = self.__connect() self.__executePragma(cur) cur.execute(query) data = cur.fetchall() outputMessage['code'] = SqliteConn.CODE_OK outputMessage['message'] = 'Success executed sql command' outputMessage['data'] = data except Exception as ex: outputMessage['message'] = 'fail executed sql command {}'.format( ex) finally: self.__close() return outputMessage def fetchOne(self, query): ''' fetch one query data as single row sqlite object { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':None|sqlite row object } ''' outputMessage = { 'code': SqliteConn.CODE_FAIL, 'message': None, 'data': None } try: cur = self.__connect() self.__executePragma(cur) cur.execute(query) data = cur.fetchone() outputMessage['code'] = SqliteConn.CODE_OK outputMessage['message'] = 'Success executed sql command' outputMessage['data'] = data except Exception as ex: outputMessage['message'] = 'fail executed sql command {}'.format( ex) finally: self.__close() return outputMessage def createTable(self, models): """ create table that will receive parameter as models of object creation of table for example we have the current class of creation table definition: the self.createOrder should be ordering of creation table class CreateTableExample(): def __init__(self): self.createOrder = [ 'createUsers', 'createAddress' ] def createUsers(self): return ''' CREATE TABLE IF NOT EXISTS Users( userid UNSIGNED INT, username VARCHAR(255), PRIMARY KEY (userid, username) ); ''' def createAddress(self): return ''' CREATE TABLE IF NOT EXISTS Address( uid UNSIGNED INT, uname VARCHAR(255), addrid UNSIGNED INT, addrname VARCHAR(255), PRIMARY KEY (addrid), FOREIGN KEY (uid, uname) REFERENCES Users(userid, username) ON DELETE CASCADE ON UPDATE NO ACTION ); ''' { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':None|[list of sqlite row object] } with class creation table above we can use as: from plugins.dbconn import SqliteConn conn = SqliteConn('conn1') conn.createTable(CreateTableExample()) """ outputMessage = {'code': SqliteConn.CODE_FAIL, 'message': None} try: createOrder = getattr(models, 'createOrder') for create in createOrder: exeCreate = getattr(models, create) outputMessage = self.execute(exeCreate()) except Exception as ex: outputMessage[ 'message'] = 'fail executed create table command {}'.format(ex) return outputMessage
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'))
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_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('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('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) if PY2: self._check_value(config, 'client', 'second', 'Altairians', unicode, 'Stop', '12.45') else: self._check_value(config, 'client', 'second', 'Altairians', str, '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") if PY2: self._check_value(config, 'server', 'second', 'Blagulon Kappans', unicode, 'Accelerate', 'Arther Dent') else: self._check_value(config, 'server', 'second', 'Blagulon Kappans', str, '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)
def test_save_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)
import logging import sys from flask import Flask from appconfig import AppConfig from firebase_admin import credentials, initialize_app try: cred = credentials.Certificate('db_credentials.json') initialize_app(cred, {'databaseURL': AppConfig.get("db_url")}) except FileNotFoundError: logging.error('Database credentials file not found') sys.exit() app = Flask(__name__, static_folder="static", template_folder="static/templates") from api.admin_blueprint import admin_blueprint from api.install_blueprint import install_blueprint from api.root_blueprint import root_blueprint from api.script_blueprint import script_blueprint app.register_blueprint(root_blueprint) app.register_blueprint(install_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(script_blueprint) if __name__ == '__main__': app.run(
def test_save_default_config(self): ''' Test the save functionality with a default config file ''' config = AppConfig() config.init_default_config(os.path.join(self.config_dir, 'test_data.txt')) config.save() # read the generated default output file (only three sections expected # nothing else should be in here since we haven't changed one value. # but added the default config file sections, values, comments = \ self._parse_config_file(config.get(config.application_name, 'config_file')) self.assertTrue(sections == 3) self.assertTrue(values == 0) self.assertTrue(comments == 0) config.save(verbose=True) # search the verbose file with 3 lines of comment for each entry sections, values, comments = \ self._parse_config_file(config.get(config.application_name, 'config_file')) self.assertTrue(sections == 3) self.assertTrue(values == 0) self.assertTrue(comments == 34) config.set('client', 'first', 42) config.set('client', 'second', 42) config.set('server', 'first', 42) config.set('server', 'second', 42) config.save() config.save() # read the config file after two value for each section where set sections, values, comments = \ self._parse_config_file(config.get(config.application_name, 'config_file')) self.assertTrue(sections == 3) self.assertTrue(values == 4) self.assertTrue(comments == 0) config.save(verbose=True) # 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(config.get(config.application_name, 'config_file')) self.assertTrue(sections == 3) self.assertTrue(values == 4) self.assertTrue(comments == 34) # load default config config.load_default() self.assertTrue(config.get('client', 'first') == "42") os.remove(config.get(config.application_name, 'config_file'))
def redirect_to_install_confirmation(self): url = AppConfig.get("redirect_url").format( self.shop.name, AppConfig.get("API_KEY"), "{}/install/confirm".format(AppConfig.url), AppConfig.get("scopes")) return url
class PostgreConn(): CODE_OK = 'ok' CODE_FAIL = 'fail' 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 def __connect(self): self.__conn = psycopg2.connect( host=self.__host, user=self.__user, password=self.__password, dbname=self.__db, port=self.__port, cursor_factory=psycopg2.extras.DictCursor, sslmode=self.__sslMode, sslrootcert=self.__sslrootcert, sslcert=self.__sslcert, sslkey=self.__sslkey) return self.__conn.cursor() def __close(self): if self.__conn: self.__conn.close() def execute(self, query): ''' execute non return data query, like insert, update, delete data return value: { 'code':'ok'|'fail', 'message':'success message'|'error message' } ''' outputMessage = {'code': PostgreConn.CODE_FAIL, 'message': None} try: cur = self.__connect() cur.execute(query) self.__conn.commit() outputMessage['code'] = PostgreConn.CODE_OK outputMessage['message'] = 'Success executed sql command' except Exception as ex: outputMessage['message'] = 'fail executed sql command {}'.format( ex) finally: self.__close() return outputMessage def fetchAll(self, query): ''' fetch all query data as list of row sqlite object { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':None|[list of sqlite row object] } ''' outputMessage = { 'code': PostgreConn.CODE_FAIL, 'message': None, 'data': None } try: cur = self.__connect() cur.execute(query) data = cur.fetchall() outputMessage['code'] = PostgreConn.CODE_OK outputMessage['message'] = 'Success executed sql command' outputMessage['data'] = data except Exception as ex: outputMessage['message'] = 'fail executed sql command {}'.format( ex) finally: self.__close() return outputMessage def fetchOne(self, query): ''' fetch one query data as single row sqlite object { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':None|sqlite row object } ''' outputMessage = { 'code': PostgreConn.CODE_FAIL, 'message': None, 'data': None } try: cur = self.__connect() cur.execute(query) data = cur.fetchone() outputMessage['code'] = PostgreConn.CODE_OK outputMessage['message'] = 'Success executed sql command' outputMessage['data'] = data except Exception as ex: outputMessage['message'] = 'fail executed sql command {}'.format( ex) finally: self.__close() return outputMessage def createTable(self, models): """ create table that will receive parameter as models of object creation of table for example we have the current class of creation table definition: the self.createOrder should be ordering of creation table class CreateTableExample(): def __init__(self): self.createOrder = [ 'createUsers', 'createAddress' ] def createUsers(self): return ''' CREATE TABLE IF NOT EXISTS Users( userid INTEGER, username VARCHAR(255), PRIMARY KEY (userid, username) ); ''' def createAddress(self): return ''' CREATE TABLE IF NOT EXISTS Address( uid INTEGER, uname VARCHAR(255), addrid INTEGER, addrname VARCHAR(255), PRIMARY KEY (addrid), FOREIGN KEY (uid, uname) REFERENCES Users(userid, username) ON DELETE CASCADE ON UPDATE NO ACTION ); ''' { 'code':'ok'|'fail', 'message':'success message'|'error message', 'data':None|[list of sqlite row object] } with class creation table above we can use as: from plugins.dbconn import PostgreConn conn = PostgreConn('conn1') conn.createTable(CreateTableExample()) """ outputMessage = {'code': PostgreConn.CODE_FAIL, 'message': None} try: createOrder = getattr(models, 'createOrder') for create in createOrder: exeCreate = getattr(models, create) outputMessage = self.execute(exeCreate()) except Exception as ex: outputMessage[ 'message'] = 'fail executed create table command {}'.format(ex) return outputMessage
class ShopifyApi: def __init__(self, shop): self.shop = shop url = AppConfig.get("shop_admin_url") def get_url(self, context): return self.url.format(self.shop.name, context) def get_header(self): header = {'X-Shopify-Access-Token': self.shop.token} return header def token_valid(self): url = self.get_url('shop.json') header = self.get_header() r = requests.get(url, headers=header) return not r.status_code == 401 def confirm_installation(self, auth): r = requests.post(AppConfig.get("access_token_url").format( self.shop.name), data={ 'client_id': AppConfig.get("API_KEY"), 'client_secret': AppConfig.get("API_SECRET"), 'code': auth }) self.shop.token = (r.json()["access_token"]) def redirect_to_install_confirmation(self): url = AppConfig.get("redirect_url").format( self.shop.name, AppConfig.get("API_KEY"), "{}/install/confirm".format(AppConfig.url), AppConfig.get("scopes")) return url def update_sticky_bar(self): url = self.get_url('script_tags.json') header = self.get_header() header['Content-Type'] = 'application/json' build_script(self.shop) if self.shop.script_tag_id is None: r = requests.post(url, data=dumps({ "script_tag": { "event": "onload", "src": AppConfig.url + '/shop_scripts' } }), headers=header) if r.status_code == 201: self.shop.script_tag_id = loads(r.content)['script_tag']['id'] def add_billing(self, last_billing): url = self.get_url('recurring_application_charges.json') header = self.get_header() header['Content-Type'] = 'application/json' trial_days = self.get_trial_period(last_billing) r = requests.post( url, data=dumps({ "recurring_application_charge": { "name": "Recurring charge", "price": 1.99, "test": AppConfig.get("environment") == "development", "trial_days": trial_days, "return_url": "http://{}.myshopify.com/admin/apps/customerce".format( self.shop.name) } }), headers=header) if r.status_code == 201: rdict = loads(r.content)['recurring_application_charge'] self.shop.billing_id = rdict['id'] save_shop(self.shop) return rdict['confirmation_url'] return None def activate_billing(self): url = self.get_url( 'recurring_application_charges/{}/activate.json'.format( self.shop.billing_id)) header = self.get_header() header['Content-Type'] = 'application/json' r = requests.post(url, headers=header) return r.status_code def get_trial_period(self, last_billing): default_trial_period = AppConfig.get("default_trial_period") if last_billing is None: return default_trial_period url = self.get_url( 'recurring_application_charges/{}.json'.format(last_billing)) header = self.get_header() header['Content-Type'] = 'application/json' r = requests.get(url, headers=header) try: rdict = loads(r.content)['recurring_application_charge'] except KeyError: return default_trial_period activated_on = rdict['activated_on'] if activated_on is None: return default_trial_period activated = datetime.datetime.strptime(activated_on, '%Y-%m-%d') today = datetime.datetime.today() period = default_trial_period - (today - activated).days if period < 0: return 0 if period > default_trial_period: return default_trial_period return period
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"
class Session(): 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')) def __readSessionFile(self, sessionFile): loadedData = dict() f = None try: f = open(sessionFile, mode='rb') loadedData = Unpickler(f).load() except Exception as e: print('Warning when read session file %s' % e) finally: if f: f.close() return loadedData def _writeSessionFile(self, sessionFile, loadedData): f = None try: f = open(sessionFile, mode='wb') Pickler(f, protocol=pickle.HIGHEST_PROTOCOL).dump(loadedData) except Exception as e: print('Warning when read session file %s' % e) finally: if f: f.close() def setMaxAge(self, maxAge): ''' setMaxAge(value) set max age of the session ''' try: currentUtcTime = self.__getCurrentUtcTimeHash() # get cookie from current request if not exist just add it cookieSessionData = request.get_cookie( 's', currentUtcTime.get('hexdigest')) # create session file if os.path.isdir(self.__sessionOption.get('data_dir')): sessionFile = os.path.join( self.__sessionOption.get('data_dir'), cookieSessionData) if os.path.isfile(sessionFile): loadedData = self.__readSessionFile(sessionFile) # set max ages for current session if isinstance(loadedData, dict): loadedData['max_age'] = maxAge self._writeSessionFile(sessionFile, loadedData) response.set_cookie('s', cookieSessionData, max_age=maxAge) except Exception as e: print(e) def __getCurrentUtcTimeHash(self): utcdt = datetime.datetime.utcnow().isoformat() mdsHash = md5(utcdt.encode('utf-8')) utcnowDiggest = { 'utc_datetime': utcdt, 'hexdigest': mdsHash.hexdigest() } return utcnowDiggest def add(self, key, value): ''' add(key, value) add value to session, if key already exist will update the last value ''' try: currentUtcTime = self.__getCurrentUtcTimeHash() # get cookie from current request if not exist just add it cookieSessionData = request.get_cookie( 's', currentUtcTime.get('hexdigest')) # create session file if os.path.isdir(self.__sessionOption.get('data_dir')): sessionFile = os.path.join( self.__sessionOption.get('data_dir'), cookieSessionData) isNotNewSession = os.path.isfile(sessionFile) loadedData = dict() if isNotNewSession: loadedData = self.__readSessionFile(sessionFile) if isinstance(loadedData, dict): loadedData[key] = value # if default max_ages None set default to 30 days 2592000 seconds # if max ages is not defined ye then add to session data and cookies data if (loadedData.get('max_age') is None): loadedData['max_age'] = self.__sessionOption.get( 'default_max_age') # add created date if not exist in the data if (loadedData.get('date_created') is None): loadedData['date_created'] = currentUtcTime[ 'utc_datetime'] self._writeSessionFile(sessionFile, loadedData) # set default max age if new if (not isNotNewSession): response.set_cookie( 's', cookieSessionData, max_age=self.__sessionOption.get('default_max_age')) else: response.set_cookie('s', cookieSessionData) else: raise Exception('Session dir is not exist %s' % self.__sessionOption.get('data_dir')) except Exception as e: print(e) def clear(self): ''' clear() clear all instance of session ''' try: currentUtcTime = self.__getCurrentUtcTimeHash() # get cookie from current request if not exist just add it cookieSessionData = request.get_cookie( 's', currentUtcTime.get('hexdigest')) # create session file if os.path.isdir(self.__sessionOption.get('data_dir')): sessionFile = os.path.join( self.__sessionOption.get('data_dir'), cookieSessionData) if (os.path.isfile(sessionFile)): os.remove(sessionFile) response.set_cookie('s', cookieSessionData, max_age=0) response.delete_cookie(cookieSessionData) except Exception as e: print(e) def get(self, key=None): ''' get() get available current session session ''' sessionData = None try: currentUtcTime = self.__getCurrentUtcTimeHash() # get cookie from current request if not exist just add it cookieSessionData = request.get_cookie( 's', currentUtcTime.get('hexdigest')) # create session file if os.path.isdir(self.__sessionOption.get('data_dir')): sessionFile = os.path.join( self.__sessionOption.get('data_dir'), cookieSessionData) if os.path.isfile(sessionFile): if key: sessionData = self.__readSessionFile(sessionFile).get( key) else: sessionData = self.__readSessionFile(sessionFile) except Exception as e: print(e) return sessionData def remove(self, key): ''' remove(key) remove session key, will return deleted session key value pair {key, value} ''' removedData = {} try: currentUtcTime = self.__getCurrentUtcTimeHash() # get cookie from current request if not exist just add it cookieSessionData = request.get_cookie( 's', currentUtcTime.get('hexdigest')) # create session file if os.path.isdir(self.__sessionOption.get('data_dir')): sessionFile = os.path.join( self.__sessionOption.get('data_dir'), cookieSessionData) if os.path.isfile(sessionFile): loadedData = self.__readSessionFile(sessionFile) if isinstance(loadedData, dict): if loadedData.get(key) is not None: removedData[key] = loadedData.pop(key) self._writeSessionFile(sessionFile, loadedData) except Exception as e: print(e) return removedData def getExpired(self): ''' getExpired() get expired session file, will return list of absolute path from expired session file ''' expiredSession = list() if os.path.isdir(self.__sessionOption.get('data_dir')): files = os.listdir(self.__sessionOption.get('data_dir')) for fname in files: sessionFile = os.path.sep.join( [self.__sessionOption.get('data_dir'), fname]) if os.path.isfile(sessionFile): sessionData = self.__readSessionFile(sessionFile) if isinstance(sessionData, dict): sessionDatetime = sessionData.get('date_created') sessionMaxAge = sessionData.get('max_age') if sessionDatetime is not None and sessionMaxAge is not None: timeDelta = datetime.datetime.utcnow( ) - datetime.datetime.strptime( sessionDatetime, '%Y-%m-%dT%H:%M:%S.%f') totalTimeDeltaInSeconds = timeDelta.days * 86400 + timeDelta.seconds # if expired add to expiredSession if totalTimeDeltaInSeconds >= sessionMaxAge: expiredSession.append(sessionFile) return expiredSession def CleanExpiredSession(self): for expiredSession in self.getExpired(): os.remove(expiredSession)
def __init__(self): self.__systemToClean = AppConfig().systemCleaner()
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')))
# 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 debugPrint(*args, **kwargs): if AppConfig().severOptions().get('debug'): _print(*args, **kwargs)
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)