Ejemplo n.º 1
0
def database():
    admin_db_config = load_config(
        'deployment/config/admin_config.toml')['database']
    test_db_config = load_config(
        'deployment/config/test_config.toml')['database']

    setup_db(executor_config=admin_db_config, target_config=test_db_config)
    yield
    teardown_db(executor_config=admin_db_config, target_config=test_db_config)
Ejemplo n.º 2
0
 def __init__(self, TOKEN = settings.load_config("GET_TOKEN"),
              ADMIN_ID = settings.load_config("GET_ADMIN_ID"),
              PASSWORD = settings.load_config("GET_PASSWORD"),
              CURRENT_MODULE = 'ssh'):
     self.current_module = CURRENT_MODULE
     self.offset = 0
     self.token = TOKEN
     self.password = PASSWORD
     self.admin_id = ADMIN_ID
     self.temp_id = TEMP_ID
     self.current_time = 0
     self.now_plus_10 = 0
Ejemplo n.º 3
0
def run_game(width: int, height: int, fps: int, starting_scene: SceneBase):
    """Main function that moves everything. Don't delete it."""
    pygame.mixer.pre_init(44100, -16, 2, 1024)
    os.environ['SDL_VIDEO_CENTERED'] = "1"
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    game_icon = pygame.image.load("assets/images/icon.png")
    pygame.display.set_icon(game_icon)
    pygame.mouse.set_visible(False)
    clock = pygame.time.Clock()

    # Load game data
    resources.load_assets()
    settings.load_config()
    settings.load_jokes()

    # Start first scene
    active_scene = starting_scene()

    while active_scene is not None:
        # Handle events
        pressed_keys = pygame.key.get_pressed()

        filtered_events = []
        for event in pygame.event.get():
            quit_attempt = False
            if event.type == pygame.QUIT:
                quit_attempt = True
            elif event.type == pygame.KEYDOWN:
                alt_pressed = (pressed_keys[pygame.K_LALT]
                               or pressed_keys[pygame.K_RALT])
                if event.key == settings.get_key("exit"):
                    quit_attempt = True
                elif event.key == pygame.K_F4 and alt_pressed:
                    quit_attempt = True

            if quit_attempt:
                active_scene.terminate()
            else:
                filtered_events.append(event)

        # Scene does its stuff
        active_scene.process_input(filtered_events, pressed_keys)
        now = pygame.time.get_ticks()
        active_scene.update(now)
        active_scene.render(screen)

        # To next scene or continue in the same
        active_scene = active_scene.next

        pygame.display.flip()
        clock.tick(fps)
        pygame.display.set_caption(f"Snake - {clock.get_fps():2.0f} fps")
Ejemplo n.º 4
0
def main():
    options = load_config()

    parser = argparse.ArgumentParser(prog="gdanmaku")
    parser.add_argument(
        "--server",
        type=str,
        default=options["http_stream_server"],
        help="danmaku stream server"
    )

    parser.add_argument(
        '--config',
        action="store_true",
        help="run configuration window"
    )

    args = parser.parse_args()

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    signal.signal(signal.SIGTERM, signal.SIG_DFL)

    if args.config:
        app_config()
    else:
        main_app = Main(args.server)
        main_app.run()
Ejemplo n.º 5
0
def main():
    options = load_config()

    parser = argparse.ArgumentParser(prog="gdanmaku")
    parser.add_argument(
        "--server",
        type=str,
        default=options["http_stream_server"],
        help="danmaku stream server"
    )

    parser.add_argument(
        '--config',
        action="store_true",
        help="run configuration window"
    )

    args = parser.parse_args()

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    signal.signal(signal.SIGTERM, signal.SIG_DFL)

    if args.config:
        app_config()
    else:
        main_app = Main(args.server)
        main_app.run()
Ejemplo n.º 6
0
def init_app():
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(load_config())
    print app.config['DATABASE_PATH']
    register_urls(app, patterns)
    config_db_with_app(app)
    return app
Ejemplo n.º 7
0
    def __init__(self):
        self.configs = settings.load_config()

        self.host = self.configs.RABBIT_HOST
        self.port = self.configs.RABBIT_PORT
        self.username = self.configs.RABBIT_USER
        self.password = self.configs.RABBIT_PASSWORD
        self.vhost = self.configs.RABBIT_VHOST
        self.exchange = self.configs.EXCHANGE_NAME
Ejemplo n.º 8
0
    def on_confirm_button(self, widget):
        server = self.server_entry.get_text()
        if self.save_default_btn.get_active():
            options = load_config()
            options["http_stream_server"] = server
            save_config(options)

        self.emit("server-selected", server)
        self.close()
Ejemplo n.º 9
0
 def __init__(self, server=None):
     self.server = server
     server_selection = ServerSelectionWindow(self.server)
     server_selection.connect('server-selected', self.on_server_selected)
     self.app = GDanmakuApp(self)
     self.thread_sub = None
     self.enabled = True
     self.options = load_config()
     self.live_danmakus = {}
Ejemplo n.º 10
0
    def on_confirm_button(self, widget):
        server = self.server_entry.get_text()
        if self.save_default_btn.get_active():
            options = load_config()
            options["http_stream_server"] = server
            save_config(options)

        self.emit("server-selected", server)
        self.close()
Ejemplo n.º 11
0
def main(config_path):
    config = load_config(config_path)
    logging.basicConfig(level=logging.DEBUG)
    app = init_app(config)
    app_config = config.get('app', None)
    if not app_config:
        web.run_app(app, port=app_config.get('port', 8080))
    else:
        web.run_app(app, port=8080)
Ejemplo n.º 12
0
 def __init__(self, server=None):
     self.server = server
     server_selection = ServerSelectionWindow(self.server)
     server_selection.connect('server-selected', self.on_server_selected)
     self.app = GDanmakuApp(self)
     self.thread_sub = None
     self.enabled = True
     self.options = load_config()
     self.live_danmakus = {}
Ejemplo n.º 13
0
 def __init__(self):
     _config = settings.load_config()
     self.host = _config.MONGO_HOST
     self.port = _config.MONGO_PORT
     self.database = _config.MONGO_DATABASE
     self.username = _config.MONGO_USERNAME
     self.password = _config.MONGO_PASSWORD
     self.connect_timeout = _config.MONGO_CONNECT_TIMEOUT
     self.conn = self.get_instance
Ejemplo n.º 14
0
def tables_and_data(database):
    test_db_config = load_config(
        'deployment/config/test_config.toml')['database']

    create_tables(target_config=test_db_config)
    create_sample_data(target_config=test_db_config)

    yield

    drop_tables(target_config=test_db_config)
Ejemplo n.º 15
0
    def __init__(self, server, is_main=False):
        super(ServerSelectionWindow,
              self).__init__(type=Gtk.WindowType.TOPLEVEL, title="Danmaku")

        self.options = load_config()
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
                       spacing=0,
                       margin=10)
        self.add(vbox)

        # Stream Server
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10,
                       margin=10)
        server_label = Gtk.Label("Server:")
        hbox.pack_start(server_label, False, True, 0)

        server_entry = Gtk.Entry()
        server_entry.set_width_chars(30)
        server_entry.set_text(server)
        hbox.pack_start(server_entry, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)
        self.server_entry = server_entry

        # check
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10,
                       margin=10)
        save_default_btn = Gtk.CheckButton.new_with_label("Save as default")
        hbox.pack_end(save_default_btn, False, True, 0)
        vbox.pack_start(hbox, True, True, 0)
        self.save_default_btn = save_default_btn

        # Buttons
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=20,
                       margin=10)
        cancel_button = Gtk.Button("Cancel")
        cancel_button.connect("clicked", Gtk.main_quit)
        hbox.pack_start(cancel_button, True, True, 0)

        ok_button = Gtk.Button("OK")
        ok_button.connect("clicked", self.on_confirm_button)
        hbox.pack_start(ok_button, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        if is_main:
            self.connect("delete-event", Gtk.main_quit)

        self.show_all()
Ejemplo n.º 16
0
 def __init__(self, params):
     threading.Thread.__init__(self)
     self.event_guid = params[0]
     self.time_stamp = params[1]
     self.user_guid = params[2]
     self.portal_from_guid = params[3]
     self.portal_to_guid = params[4]
     self.plext_text = params[5]
     self.action_type = params[6]
     self.plext_type = params[7]
     self.plext_team = params[8]
     self.is_secured = params[9]
     self.conn = None
     cfg = settings.load_config()
     self.conn = pymysql.connect(host = cfg['db_host'], port = int(cfg['db_port']), user = cfg['db_user'],\
         passwd = cfg['db_passwd'], db = cfg['db_name'])
Ejemplo n.º 17
0
def main(config_path):
    config = load_config(config_path)
    log_level = logging.getLevelName(config['app']['loglevel'])
    logging.basicConfig(level=log_level)
    db_url = construct_db_url(config['database'])
    engine = create_engine(db_url)
    Session = sessionmaker(bind=engine)
    session = Session()

    users = generate_users(session, 10)
    products = generate_products(session, 100)
    shops = generate_shop(session, 10)
    products_shops = generate_product_shop(session, 200, products, shops)
    baskets = generate_basket(session, 50, users)
    generate_product_in_basket(session, baskets, products_shops)
    generate_order(session, users)
Ejemplo n.º 18
0
 def __init__(self, params):
     threading.Thread.__init__(self)
     self.event_guid = params[0]
     self.time_stamp = params[1]
     self.user_guid = params[2]
     self.portal_from_guid = params[3]
     self.portal_to_guid = params[4]
     self.plext_text = params[5]
     self.action_type = params[6]
     self.plext_type = params[7]
     self.plext_team = params[8]
     self.is_secured = params[9]
     self.conn = None
     cfg = settings.load_config()
     self.conn = pymysql.connect(host = cfg['db_host'], port = int(cfg['db_port']), user = cfg['db_user'],\
         passwd = cfg['db_passwd'], db = cfg['db_name'])
Ejemplo n.º 19
0
    def __init__(self, server, is_main=False):
        super(ServerSelectionWindow, self).__init__(
            type=Gtk.WindowType.TOPLEVEL, title="Danmaku")

        self.options = load_config()
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
                       spacing=0, margin=10)
        self.add(vbox)

        # Stream Server
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10, margin=10)
        server_label = Gtk.Label("Server:")
        hbox.pack_start(server_label, False, True, 0)

        server_entry = Gtk.Entry()
        server_entry.set_width_chars(30)
        server_entry.set_text(server)
        hbox.pack_start(server_entry, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)
        self.server_entry = server_entry

        # check
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10, margin=10)
        save_default_btn = Gtk.CheckButton.new_with_label("Save as default")
        hbox.pack_end(save_default_btn, False, True, 0)
        vbox.pack_start(hbox, True, True, 0)
        self.save_default_btn = save_default_btn

        # Buttons
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=20, margin=10)
        cancel_button = Gtk.Button("Cancel")
        cancel_button.connect("clicked", Gtk.main_quit)
        hbox.pack_start(cancel_button, True, True, 0)

        ok_button = Gtk.Button("OK")
        ok_button.connect("clicked", self.on_confirm_button)
        hbox.pack_start(ok_button, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        if is_main:
            self.connect("delete-event", Gtk.main_quit)

        self.show_all()
Ejemplo n.º 20
0
def send_mail(to_addr, url, md5_hash):
    configpath = sys.argv[2]
    email_data = load_config(configpath)['email']

    msg = MIMEMultipart()
    msg['From'] = email_data['EM_LOGIN']
    msg['To'] = to_addr
    msg['Subject'] = "MD5_Hash"

    body = "Here is the md5-hash:\n" + md5_hash + "\nand the url:\n" + url
    msg.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email_data['EM_LOGIN'], email_data['EM_PASS'])
    text = msg.as_string()
    server.sendmail(email_data['EM_LOGIN'], to_addr, text)
    server.quit()
Ejemplo n.º 21
0
def create_app():
    # app配置
    app = Flask(__name__, instance_relative_config=True)
    config = load_config()
    app.config.from_object(config)

    #数据库
    db.init_app(app)
    migrate.init_app(app, db=db)

    app.register_blueprint(main_mod)
    #解析json
    ma.init_app(app)
    #上传图片配置
    configure_uploads(app, photos)
    # flask内置的保护机制,每次请求需要带上密钥,因此关闭它,
    # CSRFProtect(app)
    return app
Ejemplo n.º 22
0
def create_app():
    # app配置

    config = load_config()
    app.config.from_object(config)

    # 数据库
    db.init_app(app)
    # with app.app_context():#无法解决 mysql connect has gone
    #     db.metadata.bind = db.engine
    app.app_context().push()
    # with app.app_context():
    #     db.create_all()

    migrate.init_app(app, db=db)
    from apps.main.view import mod as main_mod
    app.register_blueprint(main_mod)
    from apps.user.view import mod as user_mod
    app.register_blueprint(user_mod)
    from apps.fund.view import mod as fund_mod
    app.register_blueprint(fund_mod)

    from apps.youheng.view import mod as youheng_mod
    app.register_blueprint(youheng_mod)

    #解析json
    ma.init_app(app)
    #上传图片配置
    configure_uploads(app, photos)
    # flask内置的保护机制,每次请求需要带上密钥,因此关闭它,
    # CSRFProtect(app)
    scheduler = APScheduler()
    scheduler.init_app(app)
    scheduler.start()

    return app
Ejemplo n.º 23
0
def _runit(scanner_file, run_file, power_file=None, test=False):
    """Given scanner and run settings file, initiate scanning run.
    """
    # Load settings files
    scanner_settings = settings.load_config(scanner_file, "scanner")
    run_settings = settings.load_config(run_file, "run")
    if power_file is None:
        power_settings = settings.Settings(**generic_power_settings)
    else:
        power_settings = settings.load_config(power_file, "power")

    # Create run data object
    run_data = RunData(run_settings, scanner_settings, power_settings)
    run_data.scanner_settings_file = scanner_file
    run_data.run_settings_file = run_file

    # Create power manager
    power_manager = powerfunctions.create_powermanager(power_settings.model,
                                                       power_settings.port)

    if test:
        run_data.scanner_settings.source = "Flatbed"
        run_data.scanner_settings.test_picture = "Color pattern"

    # Clear screen and show settings
    click.clear()
    print("Welcome to Unscanny -- A program for time series scanner imaging")
    print()
    print("Current settings")
    print("================")
    print()
    print(
        settings.formatted_settings_str(run_data.run_settings, "Run Settings"))
    print()
    print(
        settings.formatted_settings_str(run_data.scanner_settings,
                                        "Scanner Settings"))
    print()
    print(settings.formatted_settings_str(power_settings, "Power Settings"))
    print()

    # Confirm settings are correct
    if not click.confirm("Are these settings correct?", default=True):
        click.echo("Exiting: User indicated incorrect settings.")
        run_data.log("Aborted: incorrect run/scanner settings.")
        return run_data

    # Power on scanner
    click.pause("Press any key to initiate power manager...")
    power_manager.power_on(run_data.power_settings.outlet)
    finished_poweron = curses.wrapper(
        countdown_screen,
        run_data.power_settings.on_delay,
        main_txt="""Initiating power manager.\n""",
        abort_key=None)

    # Pick scanner from list of discovered scanners
    while True:
        click.pause("Press any key to continue to scanner menu...")
        device_info, scanner = choose_scanner(test=test)
        if scanner is None:
            if not click.confirm("No scanner found. Retry?"):
                click.echo("Exiting: no scanner found")
                run_data.log("Aborted: no scanner found")
                return run_data
            continue
        break

    # Apply settings to device
    run_data.scanner_settings.device_info = device_info
    scanfunctions.apply_scanner_settings(scanner, run_data.scanner_settings)

    # Confirm begin scanning
    if not click.confirm("\nAre you ready to begin scanning?", default=True):
        click.echo("Exiting: User exited before scanning.")
        run_data.log("Aborted: user exited before scanning")
        return run_data

    # get delay time
    init_delay = click.prompt(
        "Delay (in minutes) before first scan (0 = start immediately)?",
        type=click.IntRange(0, 24 * 60),
        default=0)
    run_data.initial_delay = init_delay

    # run delay loop
    if init_delay > 0:
        if init_delay > (run_data.power_setting.on_delay / 60):
            power_manager.power_off(run_data.power_settings.outlet)
        finished_delay = curses.wrapper(
            delay_loop, init_delay - (run_data.power_setting.on_delay / 60))
        if not finished_delay:
            run_data.log("Aborted: user cancelled during initial delay.")
            return run_data

    # enter scanner loop
    run_data.successful = curses.wrapper(scanner_loop, scanner, power_manager,
                                         run_data)

    # generate log file
    report_file_name = run_data.base_fname() + ".report"
    with open(report_file_name, "w") as f:
        f.write(run_data.generate_report())

    if run_data.successful:
        click.echo("\nSuccessful run. See report: {}".format(report_file_name))
    else:
        click.echo(
            "\nUnsuccessful run. See report: {}".format(report_file_name))

    return run_data
Ejemplo n.º 24
0
def init_connection():
    global conn
    if conn == None:
        cfg = settings.load_config()
        conn = pymysql.connect(host = cfg['db_host'], port = int(cfg['db_port']), user = cfg['db_user'],\
            passwd = cfg['db_passwd'], db = cfg['db_name'])
Ejemplo n.º 25
0
from aiohttp import web

from app import create_app
from settings import load_config

if __name__ == '__main__':
    config = load_config('config/dev.toml')['database']
    app = create_app(config)
    import aioreloader
    aioreloader.start()
    web.run_app(app)
Ejemplo n.º 26
0
import traceback
import threading
import logging

import settings

from sleekxmpp.xmlstream import cert

if sys.version_info < (3, 0):
    from sleekxmpp.util.misc_ops import setdefaultencoding
    setdefaultencoding('utf8')
else:
    raw_input = input

xmpp = None
cfg = settings.load_config()

class mail_thread(threading.Thread):

    def __init__(self, mailto, mailbody):
        threading.Thread.__init__(self)
        self.mailto = mailto
        self.mailbody = mailbody

    def run(self):
        global cfg
        session = smtplib.SMTP(cfg['smtp_server'], cfg['smtp_port'])
        session.ehlo()
        session.starttls()
        session.ehlo()
        session.login(cfg['ingress_login'], cfg['ingress_pass'])
Ejemplo n.º 27
0
        cancel_button = Gtk.Button("Cancel")
        cancel_button.connect("clicked", Gtk.main_quit)
        hbox.pack_start(cancel_button, True, True, 0)

        ok_button = Gtk.Button("OK")
        ok_button.connect("clicked", self.on_confirm_button)
        hbox.pack_start(ok_button, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        if is_main:
            self.connect("delete-event", Gtk.main_quit)

        self.show_all()

    def on_confirm_button(self, widget):
        server = self.server_entry.get_text()
        if self.save_default_btn.get_active():
            options = load_config()
            options["http_stream_server"] = server
            save_config(options)

        self.emit("server-selected", server)
        self.close()


if __name__ == "__main__":
    options = load_config()
    sel_win = ServerSelectionWindow(options["http_stream_server"], is_main=True)
    Gtk.main()
# vim: ts=4 sw=4 sts=4 expandtab
Ejemplo n.º 28
0
def run():
	config = load_config("rss.yaml")
	for site in config.sites:
		fetch_feed(site.name, site.feed)	
Ejemplo n.º 29
0
    def __init__(self, is_main=True):
        super(ConfigPanel, self).__init__(
            type=Gtk.WindowType.TOPLEVEL, title="Danmaku")

        self.options = load_config()
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
                       spacing=10, margin=10)
        self.add(vbox)

        # Stream Server
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10, margin=10)
        server_label = Gtk.Label("Server:")
        hbox.pack_start(server_label, False, True, 0)

        server_entry = Gtk.Entry()
        server_entry.set_text(self.options["http_stream_server"])
        server_entry.connect("changed", self.on_server_changed)

        hbox.pack_start(server_entry, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        # Font Selection
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10, margin=10)
        font_label = Gtk.Label("Font:")
        hbox.pack_start(font_label, False, True, 0)

        font_button = Gtk.FontButton(
            font_name=u"{} {}".format(self.options['font_family'],
                                      self.options['font_size']))

        font_button.connect("font-set", self.on_font_select)
        hbox.pack_start(font_button, False, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        # Speed Scale
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=10, margin=10)
        speed_label = Gtk.Label("Speed:")
        hbox.pack_start(speed_label, False, True, 0)

        speed_scale = Gtk.Scale(
            orientation=Gtk.Orientation.HORIZONTAL,
            adjustment=Gtk.Adjustment(
                self.options['speed_scale'], 0.5, 2.0, 0.01, 0, 0)
        )
        speed_scale.connect("change-value", self.on_speed_select)
        hbox.pack_start(speed_scale, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        # Buttons
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
                       spacing=20, margin=10)
        cancel_button = Gtk.Button("Cancel")
        cancel_button.connect("clicked", lambda _: self.close())
        hbox.pack_start(cancel_button, True, True, 0)

        ok_button = Gtk.Button("OK")
        ok_button.connect("clicked", self.on_confirm_button)
        hbox.pack_start(ok_button, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        if is_main:
            self.connect("delete-event", Gtk.main_quit)

        self.show_all()
Ejemplo n.º 30
0
 def reload_config(cls, *args):
     options = load_config()
     cls._font_family = options['font_family']
     cls._speed_scale = options['speed_scale']
     cls._font_size = options['font_size']
Ejemplo n.º 31
0
color_styles = {
    "white": ((1, 1, 1), (0, 0, 0), ),
    "black": ((0, 0, 0), (1, 1, 1), ),
    "blue": ((20/255.0, 95/255.0, 198/255.0), (1, 1, 1), ),
    "lightblue": ((100/255.0, 172/255.0, 239/255.0), (0, 0, 0), ),
    "cyan": ((0, 1, 1), (0, 0, 0), ),
    "red": ((231/255.0, 34/255.0, 0), (1, 1, 1), ),
    "yellow": ((1, 221/255.0, 0), (0, 0, 0), ),
    "green": ((4/255.0, 202/255.0, 0), (0, 0, 0), ),
    "purple": ((0.5, 0, 0.5), (1, 1, 1), ),
}

TEST = False

OPTIONS = load_config()


class Danmaku(Gtk.Window):
    _lock = Lock()
    count = 0
    vertical_slots = None

    _font_family = OPTIONS['font_family']
    _speed_scale = OPTIONS['speed_scale']
    _font_size = OPTIONS['font_size']
    _height = _font_size + 6

    @classmethod
    def reload_config(cls, *args):
        options = load_config()
Ejemplo n.º 32
0
 def __init__(self):
     self.rabbitmq = RabbitMQClient()
     self._mongo = MongoDB()
     self.configs = settings.load_config()
Ejemplo n.º 33
0
 def test_non_dict_config(self):
     io = StringIO.StringIO("Test")
     with self.assertRaises(Exception):
         settings.load_config(io)
Ejemplo n.º 34
0
async def client(aiohttp_client):
    config = load_config('deployment/config/test_config.toml')
    app = await init_app(config)
    return await aiohttp_client(app)
Ejemplo n.º 35
0
        cancel_button.connect("clicked", Gtk.main_quit)
        hbox.pack_start(cancel_button, True, True, 0)

        ok_button = Gtk.Button("OK")
        ok_button.connect("clicked", self.on_confirm_button)
        hbox.pack_start(ok_button, True, True, 0)
        vbox.pack_start(hbox, True, True, 0)

        if is_main:
            self.connect("delete-event", Gtk.main_quit)

        self.show_all()

    def on_confirm_button(self, widget):
        server = self.server_entry.get_text()
        if self.save_default_btn.get_active():
            options = load_config()
            options["http_stream_server"] = server
            save_config(options)

        self.emit("server-selected", server)
        self.close()


if __name__ == "__main__":
    options = load_config()
    sel_win = ServerSelectionWindow(options["http_stream_server"],
                                    is_main=True)
    Gtk.main()
# vim: ts=4 sw=4 sts=4 expandtab
Ejemplo n.º 36
0
 def test_bad_yaml(self):
     io = StringIO.StringIO("Foo: Foo\nFoo")
     with self.assertRaises(Exception):
         settings.load_config(io)
Ejemplo n.º 37
0
from flask import url_for
from flask_restplus import Api

import settings

_config = settings.load_config()
_doc = "/docs"
if _config.SWAGGER_VISIBLE in ("false", "False", False):
    _doc = False


class MyApi(Api):
    @property
    def specs_url(self):
        """
        The Swagger specifications absolute url (ie. `swagger.json`)
        :rtype: str
        """

        return url_for(self.endpoint("specs"), _external=False)


api = MyApi(
    version="1.0",
    title=_config.SWAGGER_TITLE,
    description=_config.SWAGGER_DESCRIPTION,
    doc=_doc,
    ordered=True,
    catch_all_404s=True,
    security=["apikey", "accessToken"],
    authorizations={
Ejemplo n.º 38
0
def init_connection():
    global conn
    if conn == None:
        cfg = settings.load_config()
        conn = pymysql.connect(host = cfg['db_host'], port = int(cfg['db_port']), user = cfg['db_user'],\
            passwd = cfg['db_passwd'], db = cfg['db_name'])
Ejemplo n.º 39
0
from app.error_handlers import configuration as config_error_handlers
from app.restplus import configuration as config_resplus
from app.midlewares import configuration as config_middlewares
from app.routes import import_routes
from app.cli import configuration as config_cli

# Initialize Flask
app = Flask(__name__, static_folder="static")
app.url_map.strict_slashes = False
blueprint = Blueprint("api", __name__, url_prefix=None)

# Proxy
app.wsgi_app = ProxyFix(app.wsgi_app)

# Configuration Cors
CORS(app, resources={r"/*": {"origins": "*"}})

# Load configuration
app.config.from_object(settings.load_config())

# Configuration Cli
config_cli(app=app)

# Initialize Restplus and import Routes
config_resplus(app=app, blueprint=blueprint)
import_routes()

# Configuration Middlewares and Error Handlers
config_middlewares(app=app)
config_error_handlers(app=app)
Ejemplo n.º 40
0
async def main(configpath):
    config = load_config(configpath)
    logging.basicConfig(level=logging.DEBUG)
    app = await init_app(config)
Ejemplo n.º 41
0
import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import MetaData
import models
from settings import load_config

load_config()
db_uri = os.getenv("DATABASE")

metadata = MetaData()
engine = create_engine(db_uri)
models.Base.metadata.create_all(bind=engine)
session_maker = sessionmaker(bind=engine)

class Storage:
    def __init__(self):
        self.db = session_maker()
        pass

    def create_or_get_tag(self, tag):
        db = self.db
        tmp_tag = db.query(models.Tag).filter(models.Tag.url == tag['url']).first()
        if not tmp_tag:
            tmp_tag = models.Tag(**tag)
            try:
                db.add(tmp_tag)
                db.commit()
            except Exception:
                db.rollback()
Ejemplo n.º 42
0
async def init_db(app):
    dsn = construct_db_url(load_config('config/user_config.toml')['database'])
    pool = await asyncpgsa.create_pool(dsn=dsn)
    app['db_pool'] = pool
    return pool
Ejemplo n.º 43
0
        abort(404, 'Page not found.')

@route('/:blog')
@view('blogmain.html')
def render_blog_main(blog):
    try:
        blog = request.db.query(models.Blog).filter(models.Blog.name == blog).one()
        return {'title': blog.title, 'blog': blog}
    except (sqlalchemy.orm.exc.NoResultFound, KeyError):
        abort(404, 'Page not found.')

@route('/theme/u/:theme/theme.html')
def get_user_theme_html(theme):
    pass

@route('/theme/u/:uid/:theme/:filename')
def get_user_theme_resource(uid, theme, filename):
    try:
        loader = DropboxLoader(uid, cache_opts=cache_opts)
        return loader.get('/sites/themes/%s/%s' % (theme, filename))
    except KeyError:
        abort(404, 'Page not found.')

settings.load_config()
setup_logging()

if __name__ == '__main__':
    models.init('sqlite:///data/dropblog.db')
    bottle.run(app=app, reloader=True)

from datetime import datetime, timedelta
import requests
import settings
import threading
import urllib
import modules


settings.check_config()
offset = 0
TEMP_ID = 0  # Временный ID админа.Присваивается отправлением пароля
URL = 'https://api.telegram.org/bot'  # Адрес HTTP Bot API
current_time = 0
now_plus_10 = 0
CURRENT_MODULE = 'first_module'
TOKEN = settings.load_config("GET_TOKEN")
ADMIN_ID = settings.load_config("GET_ADMIN_ID")
PASSWORD = settings.load_config("GET_PASSWORD")


class Handler:
    def __init__(self, TOKEN = settings.load_config("GET_TOKEN"),
                 ADMIN_ID = settings.load_config("GET_ADMIN_ID"),
                 PASSWORD = settings.load_config("GET_PASSWORD"),
                 CURRENT_MODULE = 'ssh'):
        self.current_module = CURRENT_MODULE
        self.offset = 0
        self.token = TOKEN
        self.password = PASSWORD
        self.admin_id = ADMIN_ID
        self.temp_id = TEMP_ID