def __init__(self, application, parent=None): super(ConfigurationDialog, self).__init__(parent) self.application = application self.setWindowTitle(u"QSH config") self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)) layout = QVBoxLayout() layout.addWidget(QtGui.QLabel("Username:"******"Heartbeat interval (ms):")) self.editHeartbeatInterval = QtGui.QLineEdit(str(AppConfig.get_heartbeat_interval())) layout.addWidget(self.editHeartbeatInterval) buttonBox = QtGui.QDialogButtonBox() self.btnCancel = QPushButton(u"Cancel") self.btnCancel.clicked.connect(self.close) buttonBox.addButton(self.btnCancel, QtGui.QDialogButtonBox.RejectRole) self.btnSave = QPushButton(u"Save") self.btnSave.clicked.connect(self.save) buttonBox.addButton(self.btnSave, QtGui.QDialogButtonBox.AcceptRole) layout.addWidget(buttonBox) self.setLayout(layout)
def __init__(self, *args): """ initilized data """ super(TaskDb, self).__init__(*args) self._taskdb_config = AppConfig().get_task_data_config() self._resultdb_config = AppConfig().get_result_data_config()
def conn_mysql_db(): db_conn = MySQLDBUtil.connect(AppConfig.mysql_db_host(), AppConfig.mysql_db_user(), AppConfig.mysql_db_password(), AppConfig.mysql_db_name(), AppConfig.mysql_db_port()) return db_conn
def __init__(self): auth = tweepy.OAuthHandler(AppConfig.get("TWITTER_API_KEY"), AppConfig.get("TWITTER_API_SECRET")) auth.set_access_token(AppConfig.get("TWITTER_ACCESS_TOKEN"), AppConfig.get("TWITTER_ACCESS_SECRET")) self.api = tweepy.API(auth)
def load_app_config(): global app_config if app_config is None: from config import AppConfig app_config = AppConfig() app_config.refresh_configs() return app_config
def CreateOptionChainTable(self, tableName): fl = open(AppConfig().ScriptCreateOptionChainTable(), "r") tblcontent = fl.read() tblname = AppConfig().TableName() tblcontent = tblcontent.replace("TABLENAME", tblname) conn = self.GetConnection() conn.execute(tblcontent) conn.close()
def load_config(): """Loads in the Pins4Days config. Returns: dict: The Pins4Days config contents. """ config = AppConfig( os.environ[REMOTE_APP_CONFIG_PATH_KEY], os.environ[LOCAL_APP_CONFIG_PATH_KEY]) config.load_config() return config.contents
def save(self): AppConfig.set_username(self.editUsername.text()) try: AppConfig.set_heartbeat_interval(int(self.editHeartbeatInterval.text())) except ValueError: pass self.application.trayIcon.updateMenu() self.application.helloAllTimer.stop() self.application.helloAllTimer.start(AppConfig.get_heartbeat_interval()) self.application.connector.helloAll() self.close()
def __init__(self): self.config = AppConfig() self.view = PypubGUI('PyPub', self.config.colors) try: self.config.loadDirs() except ConfigError as err: self.view.onError(err) else: for dirName, dirPath in self.config.dirs.items(): self.view.addDir(dirName, dirPath) self.view.startGUI(self.onAction)
def __init__(self, *args): super(ThunderDownloader, self).__init__(*args) self._thunder_path = AppConfig().get_download_config().get( "thunder_path", "") self._save_path = AppConfig().get_download_config().get( "save_path", "") self._thunder_process = None self._thunder_task_process = None self._download_urls = [] self._file_watcher = QFileSystemWatcher(self) self._file_watcher.addPath(self._save_path) self._file_watcher.directoryChanged.connect(self._on_file_dir_changed)
def __init__(self, options): QtGui.QMainWindow.__init__(self) self.appConfig = AppConfig() self.proxy_config = self.appConfig.getProxyConfig() self.ui = MainGui(self.get_server(), options) self.setCentralWidget(self.ui) self.status_bar = self.statusBar() self.status_bar.showMessage('Server started on port '+ str(self.proxy_config.port)) menubar = self.menuBar() file_menu = menubar.addMenu('&File') file_menu.addAction(QtGui.QAction("Settings", self)) toolbar = self.addToolBar('toolbar') self.server_control_action = QtGui.QAction(self.get_server_status_icon(), "Server start/stop", self) self.server_control_action.triggered.connect(self.toggle_server) clear_action = QtGui.QAction(QtGui.QIcon('assets/clear-icon.png'), "Clear", self) clear_action.triggered.connect(self.ui.clear_view) settings_action = QtGui.QAction(QtGui.QIcon('assets/gear-icon.png'), "Settings", self) settings_action.triggered.connect(self.show_settings) search_field = QtGui.QLineEdit(); search_field.textChanged.connect(self.ui.search_changed) toolbar.addAction(clear_action) toolbar.addAction(self.server_control_action) toolbar.addAction(settings_action) toolbar.addSeparator() toolbar.addWidget(QtGui.QLabel("Filter:")) toolbar.addWidget(search_field) toolbar.addSeparator() toolbar.setMovable(False) self.setStyleSheet(appStyle) self.show()
def __init__(self, *args, **kwargs): super(QSH, self).__init__(*args, **kwargs) self.setQuitOnLastWindowClosed(False) # signals self.aboutToQuit.connect(self.beforeQuit) # dialogs self.screenViewDialog = ScreenViewDialog(self) # networking self.connector = Connector() # tray self.trayIcon = MainTrayIcon(self, callbacks= { "quit": self.quit, "configuration": self.showConfigurationDialog, "incoming": self.showScreenViewDialog }) self.trayIcon.middle_click_callback = self.trayIconMiddleClick # networking callbacks self.connector.known_hosts_updated_callback = self.trayIcon.updateMenu self.connector.got_image_callback = self.processReceivedImage self.connector.receiving_start_callback = self.trayIcon.setIconLoading self.connector.sending_end_callback = self.trayIcon.setIconDefault # hi there! self.connector.updateKnownHosts() # periodically check whether hosts alive self.helloAllTimer = QtCore.QTimer(self) self.connect(self.helloAllTimer, QtCore.SIGNAL("timeout()"), self.connector.updateKnownHosts) self.helloAllTimer.start(AppConfig.get_heartbeat_interval())
def make_alembic_config(cmd_opts: Namespace, base_path: str = BASE_PATH) -> Config: """ Create custom alembic config. :param cmd_opts: Default config :type cmd_opts: Namespace :param base_path: Path of config file :type base_path: str :return: Alembic configuration :rtype: Config """ # Make path to config absolute if not os.path.isabs(cmd_opts.config): cmd_opts.config = os.path.join(base_path, cmd_opts.config) config = Config(file_=cmd_opts.config, cmd_opts=cmd_opts) # Make path to scripts absolute alembic_location = config.get_main_option("script_location") if not os.path.isabs(alembic_location): config.set_main_option("script_location", os.path.join(base_path, alembic_location)) # Set alembic db from application config config.set_main_option("sqlalchemy.url", AppConfig().db_url) return config
def updateMenu(self): self.menu.clear() # DEBUG (app UUID in tray icon popup menu): from config import APP_UUID username = AppConfig.get_username() if username: self.actionMe = QAction(unicode(username), self.parent) else: self.actionMe = QAction(unicode(APP_UUID), self.parent) self.actionMe.setDisabled(True) self.menu.addAction(self.actionMe) self.menu.addSeparator() # known hosts list if self.parent.connector and self.parent.connector.known_hosts: for host_uuid, host_data in self.parent.connector.known_hosts.iteritems(): if host_data["username"]: host_str = "%s - [%s:%s]" % (host_data["username"].decode("utf-8"), host_data["host"].toString(), host_data["port"]) else: host_str = "[%s:%s]" % (host_data["host"].toString(), host_data["port"]) self.menu.addAction(QAction(host_str, self.parent, triggered=partial(self.parent.shareScreen, host_data))) self.menu.addSeparator() # incoming data self.actionShowScreenViewDialog.setDisabled(self.incomingTotal == 0) self.actionShowScreenViewDialog.setText("(%i) Incoming" % self.incomingUnread if self.incomingUnread else "Incoming") self.menu.addAction(self.actionShowScreenViewDialog) self.menu.addSeparator() self.menu.addAction(self.actionShowConfigurationDialog) self.menu.addAction(self.actionQuit)
def main(): app_config = AppConfig() app_config.setup_dirs(app_config.template_dir, app_config.data_dir, app_config.log_dir) # print(json.dumps(app_config.cfg, indent=4)) source_loc = os.path.expanduser(app_config.cfg.get("ws_location")) print("Windows Spotlight Source Location:", source_loc) target_loc = os.path.expanduser(app_config.cfg.get("target_location")) print("Target Location:", target_loc) source_files = helper.get_files_list(source_loc) print("Total {} files found in source location.".format(len(source_files))) device_properties = app_config.cfg.get("device_properties") valid_dims = [(v.get("image_width"), v.get("image_height")) for k, v in device_properties.items()] print("List of valid dimensions:", valid_dims) valid_source_set = helper.get_valid_images( source_files, valid_dims) # List[Tuple[str, str]] print("Valid source files:", len(valid_source_set)) valid_source_files = [] target_files = [] for img_file, img_type in valid_source_set: valid_source_files.append(img_file) target_file = os.path.join( target_loc, img_type, helper.add_file_extension(os.path.basename(img_file), ext='.jpg')) target_files.append(target_file) valid_file_set = helper.get_valid_target_files( valid_source_files, target_files) # List[Tuple[str, str]] print("Files to extract:", len(valid_file_set)) if len(valid_file_set) > 0: helper.transfer_files(valid_file_set, mode='copy') else: print("No new files to transfer!")
def main(): """Main function""" signal.signal(signal.SIGINT, quit_program) logging.info('Initialising connection to SDK server') config = AppConfig() with RazerApp(config.to_dict()) as app: logging.info('Connected to the the SDK server') logging.info('Beginning screen capture (Press Ctrl-C to quit)') while True: try: pixels = ImageProcessor.get_keyboard_pixels() except OSError as ose: logger.error(f'Error grabbing screenshot: {ose.strerror}') continue app.set_colour(pixels)
class PypubApp: def __init__(self): self.config = AppConfig() self.view = PypubGUI('PyPub', self.config.colors) try: self.config.loadDirs() except ConfigError as err: self.view.onError(err) else: for dirName, dirPath in self.config.dirs.items(): self.view.addDir(dirName, dirPath) self.view.startGUI(self.onAction) def onAction(self, actionFlag): dirs = self.view.dirs if actionFlag: print(f'Execution complete...Results:\n{dirs}') else: self.config.saveDirs(dirs)
def SaveOptionChainData(self): data = self.PrepareData() conn = self.GetConnection() fl = open(AppConfig().ScriptInsertOptionChain(), "r") tbl = fl.read() fl.close() if (len(data) > 0): print("Writing to database") conn.executemany(tbl, data) conn.commit() conn.close()
async def main(): config = AppConfig("config.yml") sites = config.get_all_sites() site_configs = [config.get_site_config(site) for site in sites] notify = AsyncNotify(config.get_notify()) # SiteRecord要在这里初始化后,不然每次循环后计数被重置 record = { site: SiteRecord(config.get_site_config(site), notify) for site in sites } while True: tasks = list() for site_config in site_configs: servers = site_config.servers log.info("Site: {} check servers {}".format( site_config.site, servers)) if servers: t = AsyncCheck(site_config) # 将记录对象作为观察者添加进AsyncCheck对象 await t.add_site_record(record[site_config.site]) tasks.append(t.check_servers(servers, site_config.path)) else: log.warning("{} not found servers".format(site_config.site)) await asyncio.wait(tasks) time.sleep(1)
def app(request): app = nonogram_app app.config.from_object(AppConfig(testing=True)) app.config["TESTING"] = True ctx = app.test_request_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def __init__(self, options): QtGui.QMainWindow.__init__(self) self.appConfig = AppConfig() self.proxy_config = self.appConfig.getProxyConfig() self.ui = MainGui(self.get_server(), options) self.setCentralWidget(self.ui) self.status_bar = self.statusBar() self.status_bar.showMessage('Server started on port ' + str(self.proxy_config.port)) menubar = self.menuBar() file_menu = menubar.addMenu('&File') file_menu.addAction(QtGui.QAction("Settings", self)) toolbar = self.addToolBar('toolbar') self.server_control_action = QtGui.QAction( self.get_server_status_icon(), "Server start/stop", self) self.server_control_action.triggered.connect(self.toggle_server) clear_action = QtGui.QAction(QtGui.QIcon('assets/clear-icon.png'), "Clear", self) clear_action.triggered.connect(self.ui.clear_view) settings_action = QtGui.QAction(QtGui.QIcon('assets/gear-icon.png'), "Settings", self) settings_action.triggered.connect(self.show_settings) search_field = QtGui.QLineEdit() search_field.textChanged.connect(self.ui.search_changed) toolbar.addAction(clear_action) toolbar.addAction(self.server_control_action) toolbar.addAction(settings_action) toolbar.addSeparator() toolbar.addWidget(QtGui.QLabel("Filter:")) toolbar.addWidget(search_field) toolbar.addSeparator() toolbar.setMovable(False) self.setStyleSheet(appStyle) self.show()
def run(): log.initial() if not check_arg(): sys.exit(ERROR_ARGS) logging.info('check done.') if not AppConfig(CONFIG_FILE).readConfig(): sys.exit(ERROR_CONFIG_FILE_NOT_FOUND) #db.initial() db2 = db.DbHelper.getInstance() logging.info('-' * 150) for cfg in AppConfig.RTCs: htmlloader = RtcSpider(os.path.join(AppConfig.BASE_PATH, cfg[config.KEY_URL]), AppConfig.MEMBERS) htmlloader.load() logging.info('url:{0}'.format(cfg[config.KEY_URL])) for id in cfg[config.KEY_FIX]: logging.info('fix id:{0}'.format(id)) for fix in htmlloader.extract_fix(id): logging.info(fix) db2.put_fix(cfg[config.KEY_URL], fix) logging.info('=' * 150) #out for id in cfg[config.KEY_OUT]: logging.info('out id:{0}'.format(id)) for out in htmlloader.extract_out(id): logging.info(out) db2.put_out(cfg[config.KEY_URL], out) db2.calc_all() db2.calc_new() db2.calc_last() rpt = report.ReportText() rpt.output_report() db2.save_all()
def create_app(): app = Flask(__name__) config = AppConfig() app.config.from_object(config) app.logger.setLevel(logging.INFO) app.app_context().push() @app.errorhandler(Exception) def exception_handler(e): traceback.print_exc() current_app.logger.error(str(e)) # error_code. g.code = 1003 http_code = 500 error_resp = {'error_code': g.code, 'msg': str(e)} return jsonify(error_resp), http_code @app.before_request def before_request(): # init db session. g.db = get_db_session() g.code = 0 @app.after_request def after_request(response): code = response.status_code if hasattr(g, 'code'): code = g.code # close db session. if g.db is not None: if code != 0 and code != 200: # rollback if failed. g.db.rollback() else: g.db.commit() g.db.close() current_app.logger.info("[Request Log]" + request.path + ' [data] ' + str(request.data)) return response return app
def __init__(self): """ The main class which loads the App config and interacts with the ApiService to retrieve Food truck data. This class is also responsible for how the data is printed on the console. """ self.display_message( "===============================| Foodiezz |===============================\n" ) self.display_message("Hello! Welcome to Foodiezz!") # load the AppConfig config = AppConfig() self.socrata_dataset_id = config.socrata_dataset_id self.page_limit = config.page_limit # initialize the the ApiService object self.api_service = ApiService(config.socrata_domain, config.app_token) self.foodtruck_dataset = {} # initializing PrettyTable object with 'Name' and 'Address' as the header # I am using PrettyTable to print the final output in an organized and structured way on the console. self.foodtruck_table = PrettyTable(field_names=['Name', 'Address']) self.foodtruck_table.min_width = 60 self.total_foodtrucks_open = 0
def main(): app_cfg = AppConfig() LOGGER.info('Input csv path:{}'.format(app_cfg.input)) LOGGER.info('Output csv path:{}'.format(app_cfg.output)) LOGGER.info('Image whitelist:{}'.format(app_cfg.image_whitelist)) csv_input = CsvConfig(app_cfg) csv_input.validate() csv_input.report('w', 'image1', 'image2', 'similarity', 'elapsed') for line in csv_input.contents: start_time = int(round(time.time() * 1000)) image1 = Image(line[0]) image2 = Image(line[1]) (score, diff) = compare_ssim(image1.grayscale, image2.grayscale, full=True) bjorn_score = round(score.item(), 3) if bjorn_score > 0.99: bjorn_score = 0 time_diff = int(round(time.time() * 1000)) - start_time csv_input.report('a', image1.path, image2.path, bjorn_score, time_diff)
def runMigrations(): from alembic.config import Config from alembic import command alembic_cfg = Config("migrations/alembic.ini") from config import Config as AppConfig appConfig = AppConfig() dbURI = appConfig.SQLALCHEMY_DATABASE_URI print(dbURI) from app import create_app, db app = create_app() from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate, upgrade from flask_script import Manager migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', upgrade) manager.run()
def __init__(self, *args, **kwargs): super(QSH, self).__init__(*args, **kwargs) self.setQuitOnLastWindowClosed(False) # signals self.aboutToQuit.connect(self.beforeQuit) # dialogs self.screenViewDialog = ScreenViewDialog(self) # networking self.connector = Connector() # tray self.trayIcon = MainTrayIcon(self, callbacks={ "quit": self.quit, "configuration": self.showConfigurationDialog, "incoming": self.showScreenViewDialog }) self.trayIcon.middle_click_callback = self.trayIconMiddleClick # networking callbacks self.connector.known_hosts_updated_callback = self.trayIcon.updateMenu self.connector.got_image_callback = self.processReceivedImage self.connector.receiving_start_callback = self.trayIcon.setIconLoading self.connector.sending_end_callback = self.trayIcon.setIconDefault # hi there! self.connector.updateKnownHosts() # periodically check whether hosts alive self.helloAllTimer = QtCore.QTimer(self) self.connect(self.helloAllTimer, QtCore.SIGNAL("timeout()"), self.connector.updateKnownHosts) self.helloAllTimer.start(AppConfig.get_heartbeat_interval())
def __init__(self, config_path=None): super().__init__() self.db = BarcodeDatabase() self.session = Session() self.comManager = ComPortManager() self.comThread = QThread() self.comManager.newCodeRead.connect(self.onNewCode) self.comManager.moveToThread(self.comThread) self.comThread.started.connect(self.comManager.ComReader) self.comThread.start() self.setupSound() self.setupUi(self) # Temp button actions assignment self.exitButton.clicked.connect(self.close) self.clearButton.clicked.connect(self.clearSessionData) self.openDbButton.clicked.connect(self.loadNewDatabase) self.saveButton.clicked.connect(self.onSave) self.menuCOM.aboutToShow.connect(self.loadComPortMenu) self.loadDb.triggered.connect(self.loadNewDatabase) self.openDb.triggered.connect(self.onEditDbFile) self.reloadDb.triggered.connect(self.onReloadDb) self.save.triggered.connect(self.onSave) self.clear.triggered.connect(self.clearSessionData) self.BarcodeHistory.itemClicked.connect(self.onItemClicked) self.BarcodeHistory.currentItemChanged.connect(self.onItemClicked) self.app_config = AppConfig(parent=self) self.session.sessionItemRestore.connect(self.onNewCode) self.comManager.newCodeRead.connect(self.session.new_item) self.session.init_session()
@app.after_request def after_request(response): code = response.status_code if hasattr(g, 'code'): code = g.code # close db session. if g.db is not None: if code != 0 and code != 200: # rollback if failed. g.db.rollback() else: g.db.commit() g.db.close() current_app.logger.info("[Request Log]" + request.path + ' [data] ' + str(request.data)) return response return app app = create_app() from feeds_route import * if __name__ == '__main__': config = AppConfig() app.run(host='0.0.0.0', port=config.HTTP_PORT)
from collections import namedtuple, OrderedDict from flask import Flask, g, render_template, request, session, url_for from sqlalchemy import create_engine, MetaData # from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import select, text from config import AppConfig app = Flask('uni-capacity-app') app.secret_key = 'f8f0f791c2d1f02f3c2a7d8eaf5a45aecd6f7fe187f9b709' # DB connection initialization engine = create_engine(AppConfig.configs()['Database']['db_url'], echo=False) meta = MetaData() # Session = sessionmaker(bind=engine) meta.reflect(bind=engine) # DB function area def connect_db(): conn = engine.connect() return conn def get_db_connection(): if not hasattr(g, 'db_conn'): g.db_conn = connect_db() return g.db_conn @app.teardown_appcontext def close_db_connection(error): if hasattr(g, 'db_conn'):
class MainWindow(QtGui.QMainWindow): def __init__(self, options): QtGui.QMainWindow.__init__(self) self.appConfig = AppConfig() self.proxy_config = self.appConfig.getProxyConfig() self.ui = MainGui(self.get_server(), options) self.setCentralWidget(self.ui) self.status_bar = self.statusBar() self.status_bar.showMessage('Server started on port '+ str(self.proxy_config.port)) menubar = self.menuBar() file_menu = menubar.addMenu('&File') file_menu.addAction(QtGui.QAction("Settings", self)) toolbar = self.addToolBar('toolbar') self.server_control_action = QtGui.QAction(self.get_server_status_icon(), "Server start/stop", self) self.server_control_action.triggered.connect(self.toggle_server) clear_action = QtGui.QAction(QtGui.QIcon('assets/clear-icon.png'), "Clear", self) clear_action.triggered.connect(self.ui.clear_view) settings_action = QtGui.QAction(QtGui.QIcon('assets/gear-icon.png'), "Settings", self) settings_action.triggered.connect(self.show_settings) search_field = QtGui.QLineEdit(); search_field.textChanged.connect(self.ui.search_changed) toolbar.addAction(clear_action) toolbar.addAction(self.server_control_action) toolbar.addAction(settings_action) toolbar.addSeparator() toolbar.addWidget(QtGui.QLabel("Filter:")) toolbar.addWidget(search_field) toolbar.addSeparator() toolbar.setMovable(False) self.setStyleSheet(appStyle) self.show() def toggle_server(self): if self.ui.isServerRunning(): self.stopServer() else: self.startServer() def startServer(self): self.status_bar.showMessage('Server started on port '+ str(self.proxy_config.port)) self.ui.start_server(self.get_server()) self.server_control_action.setIcon(self.get_server_status_icon()) def stopServer(self): self.status_bar.showMessage('Server stopped') self.ui.shut_down() self.server_control_action.setIcon(self.get_server_status_icon()) def get_server(self): try: return ProxyServer(self.proxy_config) except: self.status_bar.showMessage('Error running proxy server') def get_server_status_icon(self): if self.ui.isServerRunning(): return QtGui.QIcon('assets/off-icon.png') return QtGui.QIcon('assets/on-icon.png') def show_settings(self): settings_dialog = SettingsDialog(self.appConfig) def closeEvent(self, event): self.ui.terminate()
import os from flask import Flask, render_template from flask_cachebuster import CacheBuster from config import AppConfig import giphy app = Flask(__name__) CacheBuster(config={ 'extensions': ['.js', '.css', '.png'], 'hash_size': 5 }).init_app(app) config = AppConfig(os.environ) @app.route('/') def index(): giphy_url = giphy.get_random(config.GIPHY_API_KEY, config.GIPHY_TAG, config.GIPHY_RATING) return render_template('index.html', giphy_url=giphy_url) if __name__ == '__main__': app.run(host=config.HOST, port=config.PORT)
import web from router import RouteStack from config import AppConfig class Application: base_path = "" config = "" router = "" def __init__(self, base_path): self.base_path = base_path self.config = AppConfig(base_path) def get_path(self): return self.base_path def get_router(self): return self.router base_path = os.path.dirname(os.path.abspath(inspect.stack()[-1][1])) main_conf = AppConfig(base_path) app_conf = main_conf.get_config() router = RouteStack(base_path, app_conf) urls = router.assemble() web.config.debug = app_conf["general"]["debug"] app = web.application(urls, globals())
# -*- coding: utf-8 -*- import argparse import locale import tornado.ioloop import tornado.web import config from config import AppConfig import routes # date of release; run fab timestamp to set it __date__ = "2012-03-01 19:02:03+0000" __version__ = "1" if __name__ == '__main__': args_parser = argparse.ArgumentParser() args_parser.add_argument("-p", "--port", type=int) clargs = vars(args_parser.parse_args()) port = clargs["port"] if port is None: port = 8000 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') application = tornado.web.Application(routes.all, cookie_secret=AppConfig.default().cookie_secret, debug=config.is_debug()) application.listen(port, xheaders=True) tornado.ioloop.IOLoop.instance().start()
def GetConnection(self): conn = sqlite3.connect(AppConfig().ConnectionString()) return conn
if __name__ == '__main__': argsParser = argparse.ArgumentParser(version=__version__, formatter_class=argparse.RawDescriptionHelpFormatter, description=__description__) argsGroup = argsParser.add_mutually_exclusive_group() argsGroup.add_argument('-a', '--add', dest='add_gmail', default=None, nargs=1, help='setup account and authorization to take notification') argsGroup.add_argument('-l', '--list', action='store_true', default=None, help='show the authorized accounts list') argsGroup.add_argument('-r', '--remove', dest='remove_gmail', default=None, nargs=1, help='remove the authorized account') argsGroup.add_argument('--scheduled-task', action='store_true', default=None, help=argparse.SUPPRESS) args = argsParser.parse_args() if AppConfig.init_and_validate(): this = globals() for k, v in dict(args.__dict__).iteritems(): fun = this['__%s' % k] if v and fun and inspect.isfunction(fun): if fun.func_code.co_argcount: fun(args) else: fun() args = None else: sys.exit(-1) if args: print('Please use "--help" option to read help.')
def __init__(self): self.app_config = AppConfig() self.db_config = DBConfig()