예제 #1
0
def loadSettings(filepath):
    """读取配置"""
    try:
        return jsoncfg.load_config(filepath)
    except Exception as e:
        print('failed to load configure[%s] :%s' % (filepath, e))
        return None
예제 #2
0
def run():
    try:
        # catch term/int signals
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        print "WorldpayWithin Sample Producer (with callbacks)..."
        global wpw
        global config

        print "Load configuration."
        config = jsoncfg.load_config('config/producerCallbacksWT.json')

        wpWithinEventListener = TheEventListener()
        # add listeners to the events
        # wpWithinEventListener.onBeginServiceDelivery += doBeginServiceDelivery
        # wpWithinEventListener.onEndServiceDelivery += doEndServiceDelivery
        wpw = WPWithinWrapperImpl.WPWithinWrapperImpl(config.host(),
                                                      config.port(), True,
                                                      wpWithinEventListener,
                                                      9095)
        wpw.setup("Producer Example", "Example WorldpayWithin producer")
        svc = WWTypes.WWService()
        svc.setName("Car charger")
        svc.setDescription("Can charge your hybrid / electric car")
        svc.setId(1)
        ccPrice = WWTypes.WWPrice()
        ccPrice.setId(1)
        ccPrice.setDescription("Kilowatt-hour")
        ccPrice.setUnitDescription("One kilowatt-hour")
        ccPrice.setUnitId(1)
        ppu = WWTypes.WWPricePerUnit()
        ppu.setAmount(25)
        ppu.setCurrencyCode("GBP")
        ccPrice.setPricePerUnit(ppu)
        prices = {}
        prices[ccPrice.getId()] = ccPrice
        svc.setPrices(prices)
        # [ CLIENT KEY, SERVICE KEY] : From online.worldpay.com
        wpw.initProducer(config.pspConfig())
        wpw.addService(svc)
        broadcastDuration = 20000
        durationSeconds = broadcastDuration / 1000
        wpw.startServiceBroadcast(broadcastDuration)  #20000
        repeat = 0
        while repeat < durationSeconds:
            print "Producer Waiting " + str(durationSeconds -
                                            repeat) + " seconds to go..."
            time.sleep(1)
            repeat = repeat + 1
        print "Stopped broadcasting, RPC still running"
        repeat2 = 0
        while repeat2 < 99999999999:
            print "Producer keeping alive (to receive callbacks...)"
            time.sleep(1)
            repeat2 = repeat2 + 1
    except WWTypes.WPWithinGeneralException as e:
        print "WPWithinGeneralException caught:", e
    except Exception as exc:
        print "Exception caught:", exc
예제 #3
0
def backTestSymbol(symbol, startDate, endDate=''):
    """将Multicharts导出的csv格式的历史数据插入到Mongo数据库中"""
    from vnApp.strategies.stgKingKeltner import stgKingKeltner
    from vnApp.strategies.stgBBand import stgBBand

    settings = None
    try:
        conf_fn = os.path.dirname(os.path.dirname(
            os.path.abspath(__file__))) + '/conf/BT_AShare.json'
        settings = jsoncfg.load_config(conf_fn)
    except Exception as e:
        print('failed to load configure[%s]: %s' % (conf_fn, e))
        return

    # 创建回测引擎
    engine = bt.BackTest(acnt.Account_AShare, settings)

    # # 设置引擎的回测模式为K线
    # engine.setBacktestingMode(engine.BAR_MODE)

    # # 设置产品相关参数
    # # account.setSlippage(0.2)     # 股指1跳
    # engine.setRate(30/10000)   # 万30
    # engine.setSize(100)         # 股指合约大小
    # engine.setPriceTick(0.2)    # 股指最小价格变动

    # # 设置回测用的数据起始日期
    # engine.setStartDate(startDate)
    # engine.setEndDate(endDate)
    # engine.setDatabase('VnTrader_1Min_Db', symbol)

    # 在引擎中创建策略对象
    d = {}
    strategyList = [stgBBand]  # , stgKingKeltner]
    engine.batchBacktesting(strategyList, d)
예제 #4
0
def run_consumer(event_name):
    # catch term/int signals
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    print 'Starting Alexa Consumer Written in Python.'
    global wpw
    global config

    print 'Load configuration.'
    config = jsoncfg.load_config('config/consumerOWP.json')

    wpw = WPWithinWrapperImpl.WPWithinWrapperImpl(config.host(), config.port(), False)
    try:
        wpw.setup("FunPay", "consumer of the Selected Event")
        wpwDevice = wpw.getDevice()
        print "::" + wpwDevice.getUid() + ":" + wpwDevice.getName() + ":" + wpwDevice.getDescription() + ":" + str(wpwDevice.getServices()) + ":" + wpwDevice.getIpv4Address() + ":" + wpwDevice.getCurrencyCode()
        if wpwDevice != None:
            print "Successfully got a device"
            devices = discoverDevices()
            if devices != None:
                #onlyRunOnce = 0
                for svcMsg in devices:
                    # Should pick the first device discovered
                    #onlyRunOnce = onlyRunOnce + 1
                    connectToDevice(svcMsg)
                    svcDetails = getAvailableServices()
                    #onlyRunOnce2 = 0
                    if svcDetails != None:
                        for svcDetail in svcDetails:
                            #onlyRunOnce2 = onlyRunOnce2 + 1
                            svcPrices = getServicePrices(svcDetail.getServiceId())
                            if svcPrices != None:
                                #onlyRunOnce3 = 0
                                for svcPrice in svcPrices:
                                    print "#" + svcPrice.getDescription().lower().strip() + "#"
                                    print "#" + event_name.lower().strip() + "#"
                                    if svcPrice.getDescription().lower().strip() == event_name.lower().strip():
                                    #onlyRunOnce3 = onlyRunOnce3 + 1
                                    #Select the first price in the list
                                        tpr = getServicePriceQuote(svcDetail.getServiceId(), 1, svcPrice.getId())
                                        print 'Client ID: {0}\n'.format(tpr.getClientId())
                                        print 'Server ID: {0}\n'.format(tpr.getServerId())
                                        paymentResponse = purchaseService(svcDetail.getServiceId(), tpr)
                                    else:
                                        print "Skipping " + svcPrice.getDescription()
                                #if onlyRunOnce3 != 0:
                                #    break
                        #if onlyRunOnce2 != 0:
                        #    break
                    #if onlyRunOnce != 0:
                    #    break
        else:
            print "Could not get device"
        wpw.stopRPCAgent()
    except WWTypes.WPWithinGeneralException as wpge:
        print "WPWithinGeneralException caught:", wpge
    except Exception as exc:
        print "Exception caught:", exc
예제 #5
0
 def test_load_config(self, mock_load_utf_text_file, mock_loads_config):
     res = load_config('filename')
     self.assertEqual(res, 'loads_config_return_value')
     mock_loads_config.assert_called_with('{k:0}')
     mock_load_utf_text_file.assert_called_with(
         'filename',
         default_encoding='UTF-8',
         use_utf8_strings=True,
     )
예제 #6
0
 def test_load_config(self, mock_load_utf_text_file, mock_loads_config):
     res = load_config('filename')
     self.assertEqual(res, 'loads_config_return_value')
     mock_loads_config.assert_called_with('{k:0}')
     mock_load_utf_text_file.assert_called_with(
         'filename',
         default_encoding='UTF-8',
         use_utf8_strings=True,
     )
예제 #7
0
def run():
    try:
        print "WorldpayWithin Sample Producer..."
        global wpw
        global config

        print "Load configuration."
        config = jsoncfg.load_config('config/producerWT.json')

        wpw = WPWithinWrapperImpl.WPWithinWrapperImpl(config.host(),
                                                      config.port(), False)
        wpw.setup("Producer Example", "Example WorldpayWithin producer")
        svc = WWTypes.WWService()
        svc.setName("Car charger")
        svc.setDescription("Can charge your hybrid / electric car")
        svc.setId(1)
        ccPrice = WWTypes.WWPrice()
        ccPrice.setId(1)
        ccPrice.setDescription("Kilowatt-hour")
        ccPrice.setUnitDescription("One kilowatt-hour")
        ccPrice.setUnitId(1)
        ppu = WWTypes.WWPricePerUnit()
        ppu.setAmount(25)
        ppu.setCurrencyCode("GBP")
        ccPrice.setPricePerUnit(ppu)
        prices = {}
        prices[ccPrice.getId()] = ccPrice
        svc.setPrices(prices)
        print "WorldpayWithin Sample Producer: About to init the producer with crendentials"
        # [ CLIENT KEY, SERVICE KEY] : From online.worldpay.com
        wpw.initProducer(config.pspConfig())
        print "WorldpayWithin Sample Producer: Adding service"
        wpw.addService(svc)
        broadcastDuration = 20000
        durationSeconds = broadcastDuration / 1000
        print "WorldpayWithin Sample Producer: Starting broadcast..."
        wpw.startServiceBroadcast(broadcastDuration)  #20000
        repeat = 0
        while repeat < durationSeconds:
            print "Producer Waiting " + str(durationSeconds -
                                            repeat) + " seconds to go..."
            time.sleep(1)
            repeat = repeat + 1
        print "Stopped broadcasting, RPC still running"
        repeat2 = 0
        while repeat2 < 99999999999:
            print "Producer keeping alive (to receive callbacks...)"
            time.sleep(1)
            repeat2 = repeat2 + 1
    except WWTypes.WPWithinGeneralException as e:
        print "WPWithinGeneralException caught:", e
    except Exception as exc:
        print "Exception caught:", exc
예제 #8
0
def main(argv):
    conf = {}
    try:
        opts, args = getopt.getopt(argv, "hc:", ["conf="])
    except getopt.GetoptError:
        print('missing params')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("--conf", '-c'):
            conf['conf'] = arg
    if not(conf.get('conf')):
        print('missing params')
        sys.exit(1)
    config = jsoncfg.load_config(conf['conf'])

    run(config.marathon, config.nginx, config.domain_map)
예제 #9
0
파일: main.py 프로젝트: pvorotnikov/my-home
def main():

    global client, config

    # Get arguments
    parser = argparse.ArgumentParser(prog=PROGRAM, description=__doc__)
    parser.add_argument('config', metavar='CONFIG FILE', help="Configuration file")
    parser.add_argument('-v', '--version', action='version', version=VERSION)
    parser.add_argument('-x', '--verbose', action='store_true', help="Enable verbose logging")
    args = parser.parse_args()


    # Set logging level
    if args.verbose:
        logging.basicConfig(stream=sys.stdout, format=VERBOSE_LOGGING_FORMAT, level=logging.INFO)
    else:
        logging.basicConfig(stream=sys.stdout, format=DEFAULT_LOGGING_FORMAT, level=logging.DEBUG)

    # load config
    config = load_config(args.config)
    client = Client(on_connect, on_message, host=config.HOST.value, port=config.PORT.value)
예제 #10
0
def runChildProcess():
    """子进程运行函数"""
    print('-'*20)

    # dirname(dirname(abspath(file)))
    settings= None
    try :
        conf_fn = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/conf/DR_huobi.json'
        settings= jsoncfg.load_config(conf_fn)
    except Exception as e :
        print('failed to load configure[%s]: %s' % (conf_fn, e))
        return

    # 创建日志引擎
    le = Logger()
    le.setLogLevel(le.LEVEL_INFO)
    le.addConsoleHandler()
    le.info(u'启动行情记录运行子进程')
    
    ee = EventChannel()
    le.info(u'事件引擎创建成功')
    
    me = MainRoutine(ee, settings)

    me.addMarketData(mdHuobi, settings['marketdata'][0])
    me.addApp(DataRecorder, settings['datarecorder'])
    le.info(u'主引擎创建成功')

    ee.register(EVENT_LOG, le.processLogEvent)
    ee.register(EVENT_ERROR, processErrorEvent)
    le.info(u'注册日志事件监听')

    me.start()
    le.info(u'MainRoutine starts')

    input()
예제 #11
0
def get_config_obj(filename='config.json'):
    """Read a JSON file and return a configuration dictionary"""
    config_obj = jsoncfg.load_config(filename)
    return config_obj
예제 #12
0
파일: dpid.py 프로젝트: 0xa76d/dpid
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import time

import dpilib.sources
import dpilib.routers

import jsoncfg

config = jsoncfg.load_config('dpid.conf')

# Init Router objects

routers_list = []

for router in config.routers:
    module = router.module()

    if hasattr(dpilib.routers, module):
        router_class = getattr(dpilib.routers, module).Router

        router_config = {}
        for option in router_class.config:
            router_config[option] = getattr(router, option).__call__(
                router_class.config[option])
예제 #13
0
 def __init__(self, configFilePath):
     # create config parser
     self.config = jsoncfg.load_config(configFilePath)
예제 #14
0
파일: dpid.py 프로젝트: 0xa76d/dpid
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import time

import dpilib.sources
import dpilib.routers

import jsoncfg

config = jsoncfg.load_config('dpid.conf')

# Init Router objects

routers_list = []

for router in config.routers:
        module = router.module()

        if hasattr(dpilib.routers, module):
            router_class = getattr(dpilib.routers, module).Router

            router_config = {}
            for option in router_class.config:
                router_config[option] = getattr(router, option).__call__(router_class.config[option])
예제 #15
0
def load(path):
    return JsonConfigMapper().visit(jsoncfg.load_config(path))
예제 #16
0
def main():
    parser = argparse.ArgumentParser(
        description="Bridge messages between CAN bus and MQTT server")

    parser.add_argument("-c",
                        "--config_name",
                        dest="config_file",
                        help="""Path and name of configuration file""",
                        default="config.json")

    parser.add_argument('-l',
                        '--log_file',
                        dest="log_file",
                        help='''Path and name of log file''',
                        default=None)

    parser.add_argument(
        "-v",
        dest="verbosity",
        help='''Log level''',
        default="INFO",
        choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"])

    args = parser.parse_args()

    numeric_level = getattr(logging, args.verbosity, None)
    if args.log_file:
        logging.basicConfig(level=numeric_level,
                            filename=args.log_file,
                            filemode='w',
                            format='%(asctime)s %(levelname)s:%(message)s')
    else:
        logging.basicConfig(level=numeric_level,
                            format='%(asctime)s %(levelname)s:%(message)s')

    logging.info("Reading configuration")
    try:
        c = jsoncfg.load_config(args.config_file)
    except BaseException as e:
        logging.error("Error reading config file: %s" % e)
        sys.exit(1)

    receivers = dict()
    if jsoncfg.node_exists(c.receivers):
        logging.info("Loading receivers")
        rcvrs = c.receivers
        for i, r in enumerate(jsoncfg.expect_array(rcvrs)):
            name = r.name("receiver_" + str(i))
            try:
                rcvr = CanMessage2MQTT(name, r.unpack_template(),
                                       r.var_names(), r.topic_template(),
                                       r.payload_template())
                canid = r.canid()
            except jsoncfg.JSONConfigValueNotFoundError as e:
                logging.error(
                    "Could not load receiver %s (#%d). Parameter \"%s\" not found at line= %d, col= %d"
                    % (name, i + 1, e.relative_path, e.line, e.column))
                continue
            except ValueError as e:
                logging.error("Could not load receiver %s (#%d): %s" %
                              (name, i + 1, e))
                continue

            if not isinstance(canid, list):
                canids = [canid]
            for canid in canids:
                if isinstance(canid, basestring):
                    try:
                        canid = int(canid, 0)
                    except ValueError as e:
                        logging.error(
                            "Could not add receiver %s (#%d) to listen to can id: %s"
                            % (name, i + 1, e.message))
                        continue
                elif not isinstance(canid, int):
                    logging.error(
                        "Could not add receiver %s (#%d) to listen to can id %s because it is neither string nor int"
                        % (name, i + 1, str(canid)))
                    continue
                receivers[canid] = rcvr

    transmitters = dict()
    if jsoncfg.node_exists(c.transmitters):
        logging.info("Loading transmitters")
        tmtrs = c.transmitters
        for i, t in enumerate(jsoncfg.expect_array(tmtrs)):
            name = t.name("transmitter_" + str(i))
            try:
                tmtr = MQTT2CanMessage(name, t.canid(), t.subscriptions(),
                                       t.pack_template(), t.var_names(),
                                       t.topic_template(None),
                                       t.payload_template())
            except jsoncfg.JSONConfigValueNotFoundError as e:
                logging.error(
                    "Could not load transmitter %s (#%d). Parameter \"%s\" not found at line= %d, col= %d"
                    % (name, i + 1, e.relative_path, e.line, e.column))
                continue
            except ValueError as e:
                logging.error("Could not load transmitter %s (#%d): %s" %
                              (name, i + 1, e))
                continue

            for s in tmtr.subscriptions:
                if s in transmitters:
                    transmitters[s].append(tmtr)
                else:
                    transmitters[s] = [tmtr]

    logging.info("Starting CAN bus")
    if not jsoncfg.node_exists(c.canbus.interface):
        logging.error("No can interface specified. Valid interfaces are: %s" %
                      can.interface.VALID_INTERFACES)
        sys.exit(1)

    try:
        bus = can.interface.Bus(c.canbus.channel(),
                                bustype=c.canbus.interface())
        canBuffer = can.BufferedReader()
        notifier = can.Notifier(bus, [canBuffer], timeout=0.1)
    except BaseException as e:
        logging.error("CAN bus error: %s" % e)
        sys.exit(1)

    logging.info("Starting MQTT")
    client = mqtt.Client(client_id=c.mqtt.client_id("can2mqtt"),
                         protocol=mqtt.MQTTv31)
    client.on_message = on_message
    client.user_data_set((bus, transmitters))
    try:
        mqtt_errno = client.connect(c.mqtt.host("127.0.0.1"),
                                    c.mqtt.port(1883), 60)
        if mqtt_errno != 0:
            raise Exception(error_string(mqtt_errno))

        client.loop_start()
    except BaseException as e:
        logging.error("MQTT error: %s" % e)
        bus.shutdown()
        notifier.stop()
        sys.exit(1)

    logging.info("Adding MQTT subscriptions")
    for s in transmitters:
        try:
            # message_callback_add()
            client.subscribe(s)
        except BaseException as e:
            logging.error("Error adding subscribtion \"%s\": %s" % (s, e))

    if jsoncfg.node_exists(c.canopen.sync_interval):
        logging.info("Adding CANopen sync master")
        sync_interval = c.canopen.sync_interval()
        if isinstance(sync_interval, int):
            sync_interval = float(sync_interval)
        if isinstance(sync_interval, float):
            if jsoncfg.node_exists(c.canopen.sync_count):
                sync_count = c.canopen.sync_count()
            else:
                sync_count = 0
            if not isinstance(sync_count, int):
                logging.warning("Parameter sync_count is not an int. Using 0")
                sync_count = 0
            sync_timer = RepeatedTimer(sync_interval, sync_master, bus,
                                       sync_count)
        else:
            logging.warning(
                "Parameter sync_interval must be int or float. Sync master not activated"
            )
            sync_timer = None
    else:
        sync_timer = None

    if jsoncfg.node_exists(c.canopen.auto_start):
        nmt_auto_start = c.canopen.auto_start()
        if not isinstance(nmt_auto_start, bool):
            logging.warning(
                "Parmeter canopen.auto_start must be boolean. Auto start not activated"
            )
            nmt_auto_start = False
    else:
        nmt_auto_start = False

    logging.info("Starting main loop")
    try:
        while True:
            # test delay for stress test
            # time.sleep(0.005)
            m = canBuffer.get_message()
            if m is not None:
                if nmt_auto_start:
                    do_nmt_auto_start(m, bus)

                if m.arbitration_id in receivers:
                    rcvr = receivers[m.arbitration_id]
                    try:
                        for t, p in rcvr.translate(m):
                            r = client.publish(t, p)
                            if not (r[0] == mqtt.MQTT_ERR_SUCCESS):
                                logging.error(
                                    "Error publishing message \"%s\" to topic \"%s\". Return code %s: %s"
                                    %
                                    (t, p, str(r[0]), mqtt.error_string(r[0])))
                    except BaseException as e:
                        logging.error(
                            "Error relaying message {%s} via receiver %s: %s" %
                            (m, rcvr.name, e))
                        rcvr.error_count += 1
                        if rcvr.error_count >= 10:
                            logging.warning(
                                "Too many relaying errors via receiver %s. Removing this receiver"
                                % rcvr.name)
                            del receivers[m.arbitration_id]

    except KeyboardInterrupt:
        bus.shutdown()
        notifier.stop()
        client.loop_stop()
        client.disconnect()
        if sync_timer:
            sync_timer.stop()
예제 #17
0
파일: base_db.py 프로젝트: cyn0/JMAP
 def __init__(self):
     self.config = jsoncfg.load_config('configs.cfg')
예제 #18
0
 def loadSettings(filename):
     self._settings = jsoncfg.load_config(filename)
예제 #19
0
 def __init__(self):
     BASE_PATH = '../config'
     self.config_path = os.path.join(BASE_PATH, 'CONFIG.cfg')
     self.config = jsoncfg.load_config(self.config_path)
예제 #20
0
def get_config_obj(filename='config.json'):
    """Read a JSON file and return a configuration dictionary"""
    config_obj = jsoncfg.load_config(filename)
    return config_obj
예제 #21
0
 def __init__(self):
     BASE_PATH = '../config'
     self.personalize_config_file = os.path.join(BASE_PATH, 'Personal_config.cfg')
     self.config = jsoncfg.load_config(self.personalize_config_file)
예제 #22
0
def initialize():
    if sc_globals.INITIATED:
        return
    # set default charset
    reload(sys)
    sys.setdefaultencoding('utf8')

    current_dir = os.path.dirname(__file__)
    _change_pwd(current_dir)
    _add_lib_path(current_dir)
    _add_lib_path("%s%s%s" % (current_dir, os.sep, "libs"))
    _add_lib_path("%s%s%s" % (current_dir, os.sep, "sc"))
    _add_lib_path("%s%s%s" % (current_dir, os.sep, "extra_libs"))

    # import libs after the changing of the lib path
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    import jsoncfg
    boot_file = 'config%sboot.json' % (os.sep)
    initiated = False
    try:
        boot_config = jsoncfg.load_config(boot_file)
        sc_globals_editable.LOCAL_ADDRESS = boot_config.local_address("127.0.0.1")
        sc_globals_editable.LOCAL_PORT = boot_config.local_port(61030)
        sc_globals_editable.SERVICE_PORT = boot_config.service_port(5001)
        sc_globals_editable.MAX_WAIT_FOR_WEBSERVER_RETRY = boot_config.max_wait_for_webserver_retry(3)
        sc_globals_editable.APP_NAME = boot_config.app_name("Smart Check UI")
        sc_globals_editable.DEBUG = boot_config.debug(False)
        sc_globals_editable.DB_URL = boot_config.db_url('sqlite:///./config/config.db')
        sc_globals_editable.MAIL_TO = boot_config.mail_to('')
        sc_globals_editable.MME_MAIL_SUBJECT = boot_config.mme_mail_subject('')
        sc_globals_editable.SAEGW_MAIL_SUBJECT = boot_config.saegw_mail_subject('')
        sc_globals_editable.LOG= boot_config.log(True)
        sc_globals_editable.LOG_FILE= boot_config.log_file('scui.log')
        sc_globals_editable.LOG_LEVEL= boot_config.log_level('INFO')
        initiated = True
    except Exception as e:
        print(e)
        pass

    if not initiated:
        sc_globals_editable.LOCAL_ADDRESS = "127.0.0.1"
        sc_globals_editable.LOCAL_PORT = 61030
        sc_globals_editable.SERVICE_PORT = 5001
        sc_globals_editable.MAX_WAIT_FOR_WEBSERVER_RETRY = 3
        sc_globals_editable.APP_NAME = "SmartCheckUI"
        sc_globals_editable.DEBUG = False
        sc_globals_editable.DB_URL = 'sqlite:///./config/config.db'
        sc_globals_editable.MAIL_TO = ''
        sc_globals_editable.MME_MAIL_SUBJECT = ''
        sc_globals_editable.SAEGW_MAIL_SUBJECT = ''
        sc_globals_editable.LOG= True
        sc_globals_editable.LOG_FILE= 'scui.log'
        sc_globals_editable.LOG_LEVEL= 'INFO'

    log_level = logging.DEBUG
    if sc_globals.LOG_LEVEL.lower() == 'debug':
        log_level = logging.DEBUG
    elif sc_globals.LOG_LEVEL.lower() == 'info':
        log_level = logging.INFO
    elif sc_globals.LOG_LEVEL.lower() == 'warning':
        log_level = logging.WARNING
    elif sc_globals.LOG_LEVEL.lower() == 'error':
        log_level = logging.ERROR
    elif sc_globals.LOG_LEVEL.lower() == 'critical':
        log_level = logging.CRITICAL

    logging.basicConfig(level=log_level,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename= sc_globals.LOG_FILE,
                    filemode='a+')
    if not sc_globals.LOG:
        logging.disable(logging.CRITICAL)

    app = Flask(sc_globals.APP_NAME)
    app.config['SECRET_KEY'] = 'scui'
    app.config['UPLOAD_FOLDER'] = 'tmp'
    app.config['MAX_CONTENT_LENGTH'] = 16777216

    if sc_globals.QT_CLIENT:
        app.debug = False
    else:
        app.debug = sc_globals.DEBUG

    app.use_reloader = False

    #session
    app.secret_key = '\x80p;\x05\\}\xba\x8bd\xd8\xb0M#`B\xe9\x8c\x07"\xb0Q&V\xb5"`'

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = sc_globals.DB_URL

    db = SQLAlchemy(app)

    sc_globals_editable.APP = app
    sc_globals_editable.DB = db

    sc_globals_editable.INITIATED = True
예제 #23
0
def initialize():
    if sc_globals.INITIATED:
        return
    # set default charset
    reload(sys)
    sys.setdefaultencoding('utf8')

    current_dir = os.path.dirname(__file__)
    _change_pwd(current_dir)
    _add_lib_path(current_dir)
    _add_lib_path("%s%s%s" % (current_dir, os.sep, "libs"))
    _add_lib_path("%s%s%s" % (current_dir, os.sep, "sc"))
    _add_lib_path("%s%s%s" % (current_dir, os.sep, "extra_libs"))

    # import libs after the changing of the lib path
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    import jsoncfg
    boot_file = 'config%sboot.json' % (os.sep)
    initiated = False
    try:
        boot_config = jsoncfg.load_config(boot_file)
        sc_globals_editable.LOCAL_ADDRESS = boot_config.local_address(
            "127.0.0.1")
        sc_globals_editable.LOCAL_PORT = boot_config.local_port(61030)
        sc_globals_editable.SERVICE_PORT = boot_config.service_port(5001)
        sc_globals_editable.MAX_WAIT_FOR_WEBSERVER_RETRY = boot_config.max_wait_for_webserver_retry(
            3)
        sc_globals_editable.APP_NAME = boot_config.app_name("Smart Check UI")
        sc_globals_editable.DEBUG = boot_config.debug(False)
        sc_globals_editable.DB_URL = boot_config.db_url(
            'sqlite:///./config/config.db')
        sc_globals_editable.MAIL_TO = boot_config.mail_to('')
        sc_globals_editable.MME_MAIL_SUBJECT = boot_config.mme_mail_subject('')
        sc_globals_editable.SAEGW_MAIL_SUBJECT = boot_config.saegw_mail_subject(
            '')
        sc_globals_editable.LOG = boot_config.log(True)
        sc_globals_editable.LOG_FILE = boot_config.log_file('scui.log')
        sc_globals_editable.LOG_LEVEL = boot_config.log_level('INFO')
        initiated = True
    except Exception as e:
        print(e)
        pass

    if not initiated:
        sc_globals_editable.LOCAL_ADDRESS = "127.0.0.1"
        sc_globals_editable.LOCAL_PORT = 61030
        sc_globals_editable.SERVICE_PORT = 5001
        sc_globals_editable.MAX_WAIT_FOR_WEBSERVER_RETRY = 3
        sc_globals_editable.APP_NAME = "SmartCheckUI"
        sc_globals_editable.DEBUG = False
        sc_globals_editable.DB_URL = 'sqlite:///./config/config.db'
        sc_globals_editable.MAIL_TO = ''
        sc_globals_editable.MME_MAIL_SUBJECT = ''
        sc_globals_editable.SAEGW_MAIL_SUBJECT = ''
        sc_globals_editable.LOG = True
        sc_globals_editable.LOG_FILE = 'scui.log'
        sc_globals_editable.LOG_LEVEL = 'INFO'

    log_level = logging.DEBUG
    if sc_globals.LOG_LEVEL.lower() == 'debug':
        log_level = logging.DEBUG
    elif sc_globals.LOG_LEVEL.lower() == 'info':
        log_level = logging.INFO
    elif sc_globals.LOG_LEVEL.lower() == 'warning':
        log_level = logging.WARNING
    elif sc_globals.LOG_LEVEL.lower() == 'error':
        log_level = logging.ERROR
    elif sc_globals.LOG_LEVEL.lower() == 'critical':
        log_level = logging.CRITICAL

    logging.basicConfig(
        level=log_level,
        format=
        '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename=sc_globals.LOG_FILE,
        filemode='a+')
    if not sc_globals.LOG:
        logging.disable(logging.CRITICAL)

    app = Flask(sc_globals.APP_NAME)
    app.config['SECRET_KEY'] = 'scui'
    app.config['UPLOAD_FOLDER'] = 'tmp'
    app.config['MAX_CONTENT_LENGTH'] = 16777216

    if sc_globals.QT_CLIENT:
        app.debug = False
    else:
        app.debug = sc_globals.DEBUG

    app.use_reloader = False

    #session
    app.secret_key = '\x80p;\x05\\}\xba\x8bd\xd8\xb0M#`B\xe9\x8c\x07"\xb0Q&V\xb5"`'

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = sc_globals.DB_URL

    db = SQLAlchemy(app)

    sc_globals_editable.APP = app
    sc_globals_editable.DB = db

    sc_globals_editable.INITIATED = True