Esempio n. 1
0
def main(argv=sys.argv[1:]) -> int:
    """main entry point for ghast"""
    parser = get_parser()
    args = parser.parse_args(argv)
    init_logging(args, "ghast.log")

    __log__.info("starting ghast server on "
                 "host: {} port: {} "
                 "graylog_http_alert_url: {} "
                 "graylog_http_alert_script: {}".format(
                     args.host, args.port, args.graylog_http_alert_url,
                     args.graylog_http_alert_script))

    # Setup and start the flask / cheroot server
    ghast.server.API_HTTPS = args.api_https
    ghast.server.ALERT_SCRIPT_PATH = args.graylog_http_alert_script
    ghast.server.APP.register_blueprint(ghast.server.API_BLUEPRINT,
                                        url_prefix=args.graylog_http_alert_url)
    if args.debug:
        ghast.server.APP.run(host=args.host, port=args.port, debug=True)
    else:
        path_info_dispatcher = PathInfoDispatcher({'/': ghast.server.APP})
        server = WSGIServer((args.host, args.port), path_info_dispatcher)
        try:
            server.start()
        except KeyboardInterrupt:
            __log__.info("stopping server: KeyboardInterrupt detected")
            server.stop()
            return 0
        except Exception:
            __log__.exception("stopping server: unexpected exception")
            raise

    return 0
Esempio n. 2
0
def test_dispatch_no_script_name():
    """Despatch despite lack of SCRIPT_NAME in environ."""
    # Bare bones WSGI hello world app (from PEP 333).
    def app(environ, start_response):
        start_response(
            '200 OK', [
                ('Content-Type', 'text/plain; charset=utf-8'),
            ],
        )
        return [u'Hello, world!'.encode('utf-8')]

    # Build a dispatch table.
    d = PathInfoDispatcher([
        ('/', app),
    ])

    # Dispatch a request without `SCRIPT_NAME`.
    response = wsgi_invoke(
        d, {
            'PATH_INFO': '/foo',
        },
    )
    assert response == {
        'status': '200 OK',
        'headers': [
            ('Content-Type', 'text/plain; charset=utf-8'),
        ],
        'body': b'Hello, world!',
    }
Esempio n. 3
0
    def run(self):
        import utils.runtime_handler
        utils.runtime_handler.enable_traceback_hook(
        )  # Enable custom traceback handling (to strip build path info)

        self._shutdown_handler.add_task()

        if self._use_ssl:
            self._init_ssl()

        ks = _KeyStore.query.first()
        if ks is not None:
            _app.config['SECRET_KEY'] = ks.flask_secret
        else:
            # Temporary static key for first run. We should roll this occasionally.
            _app.config[
                'SECRET_KEY'] = b'\xee\xf0\xabc>\xc8\xa4S\xa1\x89\xff\xa3\xaf\xcfX\xac'

        self._jwt = JWT(_app, user_authenticate, user_identity)

        self._wsgi_server = WSGIServer((self._host, int(self._port)),
                                       PathInfoDispatcher({'/': _app}))

        # TODO: Issue with SSL:
        # Firefox causes a (socket.error 1) exception to be thrown on initial connection (before accepting cert)
        # This is internal to cheroot, so it may be difficult to handle

        print('LiquiTrader is ready for action!')
        print(
            f'Visit http{"s" if self._use_ssl else ""}://{self._host}:{self._port} in your favorite browser'
        )
        print('to start trading!')

        self._wsgi_server.start()
Esempio n. 4
0
def start_ui(url, port, interpreter, quiet, language):
    openurl = "localhost" if url == "0.0.0.0" else url

    if not quiet:
        print("Booting CherryPy server...")

    d = PathInfoDispatcher({'/': create_app(interpreter, language)})
    server = WSGIServer((url, port), d)

    try:
        p = multiprocessing.Process(target=delayed_browser_open,
                                    args=(openurl, port))
        p.start()

        if not quiet:
            print("Hosting at http://" + openurl + ":" + str(port) +
                  "/#loaded")

        server.start()
    except KeyboardInterrupt:
        if not quiet:
            print("Stopping CherryPy server...")

        server.stop()

        if not quiet:
            print("Stopped")
Esempio n. 5
0
def get_server(cmd_line_args):
    args = _parse_args(cmd_line_args)
    logger = _get_logger(args)
    a = create_app([args['sql_source']], {})
    d = PathInfoDispatcher({'/': a})
    server = WSGIServer((args['url'], args['port']), d)
    return logger, server, a
Esempio n. 6
0
def main(argv=sys.argv[1:]) -> int:
    """main entry point for the autotradeweb server"""
    parser = get_parser()
    args = parser.parse_args(argv)
    init_logging(args, "autotradeweb.log")

    # monkey patch courtesy of
    # https://github.com/noirbizarre/flask-restplus/issues/54
    # so that /swagger.json is served over https
    if not args.disable_https:

        @property
        def specs_url(self):
            """Monkey patch for HTTPS"""
            return url_for(self.endpoint("specs"), _external=True, _scheme="https")

        Api.specs_url = specs_url

    __log__.info("starting server: host: {} port: {}".format(args.host, args.port))
    APP.config["SQLALCHEMY_DATABASE_URI"] = args.database
    if args.debug:
        APP.run(host=args.host, port=args.port, debug=True)
    else:
        path_info_dispatcher = PathInfoDispatcher({"/": APP})
        # See SRS: S.8.R.4
        server = WSGIServer((args.host, args.port), path_info_dispatcher)
        try:
            server.start()
        except KeyboardInterrupt:
            __log__.info("stopping server: KeyboardInterrupt detected")
            server.stop()
            return 0
        except Exception:
            __log__.exception("stopping server: unexpected exception")
            raise
Esempio n. 7
0
def start_ui(url, port, interpreter, quiet):
    openurl = "localhost" if url == "0.0.0.0" else url

    if not quiet:
        print("Initializing CherryPy server...")

    os.environ["FLASK_APP"] = "satyrnUI.satyrnUI"
    os.environ["FLASK_ENV"] = "production"

    d = PathInfoDispatcher({'/': create_app(interpreter)})
    server = WSGIServer((url, port), d)

    try:
        p = multiprocessing.Process(target=delayed_browser_open,
                                    args=(openurl, port))
        p.start()

        if not quiet:
            print("Hosting at http://" + openurl + ":" + str(port) +
                  "/#loaded")

        server.start()
    except KeyboardInterrupt:
        if not quiet:
            print("Stopping CherryPy server...")

        server.stop()

        if not quiet:
            print("Stopped")
Esempio n. 8
0
def start_server(config: Type[Config],
                 task_definitions: Dict[str, Tuple[int, Callable]]):
    """
    Starts the flask application using a cheroot WSGI server
    :param config: The configuration to use
    :param task_definitions: The background tasks, consisting of:
                                - the name of the task
                                - the time to wait before running
                                  the task again
                                - a function that takes no arguments that
                                  executes the task
    :return: None
    """
    if not config.TELEGRAM_API_KEY == "" \
            and not config.TESTING \
            and config.TELEGRAM_WHOAMI:  # pragma: no cover
        try:
            config.initialize_telegram()
            Config.TELEGRAM_BOT_CONNECTION.bot.logger.setLevel(logging.WARNING)
        except TimedOut:
            print("Could not initialize telegram")
            sys.exit(1)
        task_definitions.update({"telegram_bg": (30, telegram_whoami)})
    __start_background_tasks(task_definitions)

    app.logger.info("STARTING FLASK")
    server = Server(("0.0.0.0", config.HTTP_PORT),
                    PathInfoDispatcher({"/": app}))

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 9
0
def main(argv=sys.argv[1:]) -> int:
    """main entry point undiscord flask/cheroot server"""
    parser = get_parser()
    args = parser.parse_args(argv)
    init_logging(args, "undiscord_server.log")

    graph_dir = os.path.abspath(args.graph_dir)
    os.makedirs(graph_dir, exist_ok=True)

    __log__.info("starting server: host: {} port: {} graph_dir: {}".format(
        args.host, args.port, graph_dir))

    undiscord.server.server.GRAPH_DIR = graph_dir

    if args.debug:
        undiscord.server.server.APP.run(host=args.host,
                                        port=args.port,
                                        debug=True)
    else:
        path_info_dispatcher = PathInfoDispatcher(
            {'/': undiscord.server.server.APP})
        server = WSGIServer((args.host, args.port), path_info_dispatcher)
        try:
            server.start()
        except KeyboardInterrupt:
            __log__.info("stopping server: KeyboardInterrupt detected")
            server.stop()
            return 0
        except Exception:
            __log__.exception("stopping server: unexpected exception")
            raise
Esempio n. 10
0
    def runtime(self, flask_instance: Flask, mode: int = ENABLE_FLASK):
        """
            This method deploys a REST endpoint as using different technologies according to the "mode" value.
            This endpoint will listen for incoming REST requests on different route paths.
        """

        if mode == ENABLE_FLASK:
            # simply run Flask
            flask_instance.run(host=self._listening_address,
                               port=self._listening_port,
                               threaded=True)
        elif mode == ENABLE_CHERRYPY:
            # Run Flask wrapped by Cherrypy
            cherrypy.tree.graft(flask_instance, "/")
            cherrypy.config.update({
                "server.socket_host": self._listening_address,
                "server.socket_port": self._listening_port,
                "engine.autoreload.on": False,
            })
            cherrypy.engine.start()
            cherrypy.engine.block()
        elif mode == ENABLE_WSGISERVER:
            # Run Flask wrapped by a WSGI Server.
            dispatcher = PathInfoDispatcher({'/': flask_instance})
            server = WSGIServer(
                (self._listening_address, self._listening_port), dispatcher)
            try:
                server.start()
                # server.block
            except KeyboardInterrupt:
                server.stop()
        else:
            raise RuntimeError("Invalid runtime mode was selected.")
Esempio n. 11
0
def start_rest_service(port, num_threads, ovms_port):
    available_models = get_available_models()
    dispatcher = PathInfoDispatcher(
        {'/': create_dispatcher(available_models, ovms_port)})
    server = WSGIServer(('0.0.0.0', port), dispatcher, numthreads=num_threads)
    logger.info(f"AMS service will start listening on port {port}")
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 12
0
def start_web_rest_server(models, rest_port):
    d = PathInfoDispatcher({'/': create_rest_api(models)})
    server = WSGIServer(('0.0.0.0', rest_port),
                        d,
                        numthreads=1,
                        request_queue_size=50)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 13
0
    def setUp(self):
        self.app = create_app(TestConfig)
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()

        d = PathInfoDispatcher({'/': self.app})
        self.server = WSGIServer(('0.0.0.0', 5000), d)

        Thread(target=self.server.start).start()

        self.driver = webdriver.Firefox()
Esempio n. 14
0
def main():
    args = get_args()
    app = create_app(args.output)

    d = PathInfoDispatcher({"/": app})
    server = WSGIServer((args.netmask, args.port), d)
    try:
        print(f"Logging location set to: {args.output}")
        print(f"Listening on {args.netmask}:{args.port}....")
        server.start()
    except KeyboardInterrupt:
        print("Exiting....")
        sys.exit(0)
Esempio n. 15
0
def start_web_rest_server(models, rest_port, num_threads):
    d = PathInfoDispatcher({'/': create_rest_api(models)})
    server = WSGIServer(('0.0.0.0', rest_port), d,
                        numthreads=num_threads,
                        request_queue_size=GLOBAL_CONFIG[
                            'rest_requests_queue_size'])
    logger.info("REST server listens on port {port} and will be "
                "serving models: {models}".format(port=rest_port,
                                                  models=list(models.keys())))
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 16
0
    def start(self):
        d = PathInfoDispatcher({'/': self.app})
        self.server = Server(('0.0.0.0', self.rpcport), d)
        self.proxy_thread = threading.Thread(target=self.server.start)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()

        # Now that bitcoind is running on the real rpcport, let's tell all
        # future callers to talk to the proxyport. We use the bind_addr as a
        # signal that the port is bound and accepting connections.
        while self.server.bind_addr[1] == 0:
            pass
        self.rpcport = self.server.bind_addr[1]
        logging.debug("BitcoinRpcProxy proxying incoming port {} to {}".format(self.rpcport, self.bitcoind.rpcport))
Esempio n. 17
0
    def start(self):
        d = PathInfoDispatcher({"/": self.app})
        self.server = Server(("0.0.0.0", self.proxyport), d)
        self.proxy_thread = threading.Thread(target=self.server.start)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()
        BitcoinD.start(self)

        # Now that bitcoind is running on the real rpcport, let's tell all
        # future callers to talk to the proxyport. We use the bind_addr as a
        # signal that the port is bound and accepting connections.
        while self.server.bind_addr[1] == 0:
            pass
        self.proxiedport = self.rpcport
        self.rpcport = self.server.bind_addr[1]
        logging.debug(
            "bitcoind reverse proxy listening on {}, forwarding to {}".format(
                self.rpcport, self.proxiedport
            )
        )
Esempio n. 18
0
def main():
    clear_screen()
    print_logo()

    with AdbInstaller() as installer:
        installer.install()

    AdbWrapper().disconnect_all()
    success("Açık kalan ADB bağlantıları kapatıldı!")

    web.api_key = "Girilmedi!"
    success("Sunucu başlatılıyor!")

    try:
        http_server = WSGIServer(("127.0.0.1", 5000),
                                 PathInfoDispatcher({'/': website_app}))
        success("Sunucu başlatıldı!")
        success("Arayüz adresi: http://localhost:5000")
        http_server.start()
    except KeyboardInterrupt:
        clear_screen()
        success("Kapatılıyor!")
        _exit(0)
Esempio n. 19
0
def start(ip, port, head_callback, front_callback):
    global listening
    global server
    global head_process_callback
    global front_process_callback

    if hasattr(thismodule, "listening") and listening:
        return

    head_process_callback = head_callback
    front_process_callback = front_callback

    listening = True

    current_ip = os.environ.get('SERVER_HOST', str(ip))
    try:
        current_port = int(os.environ.get('SERVER_PORT', str(port)))
    except ValueError:
        current_port = port

    d = PathInfoDispatcher({'/': web_server})
    server = Server((current_ip, current_port), d)

    server.safe_start()
Esempio n. 20
0
from flask_jwt_extended import JWTManager, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt
import logging

LOGGINGFORMAT = '%(asctime)-15s %(levelname)-8s %(name)-8s %(message)s'
logging.basicConfig(level=logging.DEBUG,
                    format=LOGGINGFORMAT,
                    datefmt='%d-%b-%y %H:%M:%S')

mapp = Flask(__name__)
mapp.secret_key = 'super secret key'

mapp.config['PROPAGATE_EXCEPTIONS'] = True

mapp.config['JWT_SECRET_KEY'] = 'test-123'
mapp.config['JWT_DECODE_AUDIENCE'] = 'testapp'
mapp.config['JWT_ENCODE_AUDIENCE'] = 'testapp'
api.init_app(mapp)

jwt = JWTManager(mapp)
#register error handlers (inbuilt)
jwt._set_error_handler_callbacks(api)

#host multiple instances
d = PathInfoDispatcher({'/product-api': mapp})
server = WSGIServer(('0.0.0.0', 8083), d)
#docker run -d -p 8088:8088 -t nginx
#start web server
try:
    server.start()
except KeyboardInterrupt:
    server.stop()
Esempio n. 21
0
from flask import Flask
from flask_restful import Api
from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher

from viridi.resources.city_data import CityData
from viridi.resources.city_news import CityNews

APP = Flask(__name__)
API = Api(APP)

DISPATCHER = PathInfoDispatcher({'/': APP})
SERVER = WSGIServer(('0.0.0.0', 8080), DISPATCHER)

API.add_resource(CityData, '/data')
API.add_resource(CityNews, '/news')

if __name__ == '__main__':
    print('Running on port 8080')
    SERVER.safe_start()
Esempio n. 22
0
LOGGINGFORMAT = '%(asctime)-15s %(levelname)-8s %(name)-8s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=LOGGINGFORMAT, datefmt='%d-%b-%y %H:%M:%S')

mapp=Flask(__name__)
mapp.secret_key = os.getenv('tokenkey')


mapp.config['PROPAGATE_EXCEPTIONS'] = True

mapp.config['JWT_SECRET_KEY']=os.getenv('tokenkey')
mapp.config['JWT_DECODE_AUDIENCE']=os.getenv('usc')
#mapp.config['JWT_ENCODE_AUDIENCE']='testapp'
api.init_app(mapp)


jwt = JWTManager(mapp)
#register error handlers (inbuilt)
jwt._set_error_handler_callbacks(api)




#host multiple instances
d=PathInfoDispatcher({'/':mapp})
server=WSGIServer(('0.0.0.0',80),d)
#docker run -d -p 8088:8088 -t nginx
#start web server
try:
      server.start()
except KeyboardInterrupt:
      server.stop()
Esempio n. 23
0
def main():
    clear_screen()
    print_logo()
    redirect_url = ask(
        "Giriş yapıldıktan sonra nereye yönlendirilsin (Varsayılan: https://www.instagram.com)"
    )
    port = ask("Web sunucusu hangi port'u kullansın (Varsayılan: 80)")

    if (port != "" and (port.isdigit()) == False):
        error("Hatalı giriş!")
        _exit(0)

    try_accounts = ask(
        "Girilen kullanıcılar denensin mi (Varsayılan: Hayır) [E/H]")
    print("")

    if ((try_accounts != "") and (try_accounts.lower() != "e")
            and (try_accounts.lower() != "h")):
        error("Hatalı giriş!")
        _exit(0)

    if (redirect_url != ""):
        info("Yönlendirme '{0}' olarak ayarlandı!".format(redirect_url))
        SETTINGS["REDIRECT_URL"] = redirect_url
    else:
        info("Varsayılan yönlendirme adresi kullanılıyor!")
        SETTINGS["REDIRECT_URL"] = "https://www.instagram.com"

    if (port != ""):
        info("Sunucunun web portu '{0}' olarak ayarlandı!".format(port))
        SETTINGS["PORT"] = int(port)
    else:
        info("Varsayılan sunucu portu kullanılıyor!")
        SETTINGS["PORT"] = 80

    if (try_accounts != ""):
        if (try_accounts.lower() == "e"):
            info("Sunucuya girilen kullanıcılar giriş yapılarak denenecektir!")
            SETTINGS["TRY_ACCOUNTS"] = True

    print("")
    if ("arm" not in uname().machine):
        success("NGROK servisi başlatılıyor!")
        public_url = ngrok.connect()
        web_url = ngrok.connect(SETTINGS["PORT"], "http")
        success("Port yönlendirme başarılı!")
        print("")
        success("Web sunucusu {0} adresinde açıldı!".format(web_url))
        print("")
    else:
        info(
            "Program Termux'dan çalıştırılıyor! NGROK'u 'ngrok http 80' komutuyla manuel başlatmalısınız!"
        )
        print("")
        success("Web sunucusu http://localhost:{0} adresinde açıldı!".format(
            SETTINGS["PORT"]))
        print("")

    try:
        http_server = WSGIServer(('0.0.0.0', SETTINGS["PORT"]),
                                 PathInfoDispatcher({'/': website_app}))
        http_server.start()
    except:
        info(
            "Program yönetici olarak çalıştırılmadığından dolayı web portu 5000 olarak değiştirildi!"
        )
        SETTINGS["PORT"] = 5000
        http_server = WSGIServer(('0.0.0.0', SETTINGS["PORT"]),
                                 PathInfoDispatcher({'/': website_app}))
        http_server.start()
Esempio n. 24
0
        config = json.load(f)
        if 'email' in config['snips_console']:
            email = config['snips_console']['email']
        if 'password' in config['snips_console']:
            password = config['snips_console']['password']
        assistant_zip = config['assistant']

    # Replicate code from funcs.sh to locate the assistant_zip file
    # If it doesn't exist in /share/snips, check /share.  If it's in
    # neither, assume it's in /share/snips!
    test_path1 = Path('/share/snips') / assistant_zip
    if test_path1.exists():
        assistant_zip = test_path1
    else:
        test_path2 = Path('/share') / assistant_zip
        if test_path2.exists():
            assistant_zip = test_path2
        else:
            assistant_zip = test_path1

    dispatcher = PathInfoDispatcher({'/': app.wsgi_app, root: app.wsgi_app})
    server = WSGIServer((host, port), dispatcher)

    try:
        info("Starting server!")
        server.start()
    except Exception as e:
        error("caught exception: {}".format(e))
        server.stop()

Esempio n. 25
0
        5: "lumières in-reception",
        6: "lumières banque",
        7: "lumières salle petit-déj buffet",
        8: "lumières salle petit-déj tables",
    }
    state_relais = {relai: lock_door.is_on(relai) for relai in list_relais.keys()}
    return {"list_relais":list_relais, "state_relais":state_relais, "myip":get_ip()}


@pyaccess.route("/turn/<state>/<relai_ch>")
def turn(state, relai_ch):
    lock_door.turn(state, int(relai_ch))
    resp = Response(f"{datetime.now().strftime('%H:%M:%S')} {relai_ch} : {state}")
    resp.set_header('Access-Control-Allow-Origin', '*')
    return resp

lock_door.init_GPIO()

from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
d = PathInfoDispatcher({"/": pyaccess})
server = WSGIServer(("0.0.0.0", 8080), d)

if __name__ == "__main__":
    try:
        # pyaccess.run(host="0.0.0.0", port=8080)
        server.start()
        pass
    except KeyboardInterrupt:
        server.stop()

Esempio n. 26
0
from cheroot.wsgi import Server as WSGIServer,PathInfoDispatcher
import signal
import TestResourceServer
import AuthanticationServer

#host multiple instances
d=PathInfoDispatcher({'/app':TestResourceServer.TestApp,'/auth':AuthanticationServer.AuthApp})
server=WSGIServer(('0.0.0.0',8088),d)
#docker run -d -p 8088:8088 -t nginx
#start web server
try:
      server.start()
except KeyboardInterrupt:
      server.stop()
Esempio n. 27
0
def api(db):
    @returns_json
    def get_data(environ, start_response):
        key = pop_path_info(environ)
        with eliot.start_action(action_type='api:get-data', key=key) as action:
            data = db.get(key)
            if data is None:
                action.add_success_fields(found=False)
                start_response('404 Not Found', [])
                return {'error': 'not_found', 'key': key}
            else:
                action.add_success_fields(found=True)
                return data

    @returns_json
    def insert_data(environ, start_response):
        with eliot.start_action(action_type='api:insert-data') as action:
            instream = make_line_iter(
                get_input_stream(environ, safe_fallback=False))
            lines = (json.loads(line.decode('utf-8')) for line in instream)
            keys = db.insert(lines)
            action.add_success_fields(inserted_count=len(keys))
            return {'message': 'Inserted OK', 'keys': keys}

    @returns_json
    def search_data(environ, start_response):
        with eliot.start_action(action_type='api:search-data') as action:
            qs = parse_qs(get_query_string(environ))
            query = {key: value[0] for key, value in qs.items()}
            if '_start_time' in query:
                query['_start_time'] = _make_search_date(query['_start_time'])
            if '_end_time' in query:
                query['_end_time'] = _make_search_date(query['_end_time'])
            if '_count' in query:
                query['_count'] = int(query['_count'])
            if '_summary' in query:
                summarise = query['_summary'] == 'true'
                aggregate = query['_summary'] == 'aggregate'
                del query['_summary']
            else:
                summarise = False
                aggregate = False
            action.add_success_fields(query=query)
            query_result = db.search(**query)
            if summarise:
                result = [(key, _summarize_callgraph(cg))
                          for key, cg in query_result]
            elif aggregate:
                result = combine_call_graphs(cg for key, cg in query_result)
            else:
                result = list(query_result)
            action.add_success_fields(results=len(result))
            return result

    @responder
    def data(environ, start_response):
        method = environ[REQUEST_METHOD]
        if method == 'GET':
            if peek_path_info(environ):
                return get_data
            else:
                return search_data
        elif method == 'POST':
            return insert_data
        else:
            return Response('Method {} Not Allowed'.format(method),
                            '405 Method Not Allowed')

    @returns_json
    def attrib_names(environ, start_response):
        with eliot.start_action(action_type='api:get-attrib-names') as action:
            return db.attrib_names()

    @returns_json
    def attrib_values(environ, start_response):
        key = pop_path_info(environ)
        with eliot.start_action(action_type='api:get-attrib-values',
                                key=key) as action:
            return db.attrib_values(key)

    @responder
    def attribs(environ, start_response):
        method = environ[REQUEST_METHOD]
        if method == 'GET':
            if peek_path_info(environ):
                return attrib_values
            else:
                return attrib_names
        else:
            return Response('Method {} Not Allowed'.format(method),
                            '405 Method Not Allowed')

    return PathInfoDispatcher({"/data": data, "/attribs": attribs})
Esempio n. 28
0
    'SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{working_dir}/data/web_interface.db"
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login = LoginManager()
login.init_app(app)


@app.before_first_request
def init_db():
    db.create_all()


import_module('pagermaid.interface.views')
import_module('pagermaid.interface.modals')

dispatcher = PathInfoDispatcher({'/': app})
server = WSGIServer(
    (config['web_interface']['host'], int(config['web_interface']['port'])),
    dispatcher)


def start():
    if strtobool(config['web_interface']['enable']):
        logs.info(
            f"已经启动Web界面 {config['web_interface']['host']}:{config['web_interface']['port']}"
        )
        app.logger.removeHandler(default_handler)
        app.logger.addHandler(logging_handler)
        try:
            server.start()
        except OSError:
Esempio n. 29
0
 def run(self):
     self._configure_flask_app()
     dispatcher = PathInfoDispatcher({"/": app})
     self.server = WSGIServer((self.host, self.port), dispatcher)
     self.server.start()
Esempio n. 30
0
    def _run(self) -> None:
        # Server and end points
        app = Flask(__name__)

        def _with_state_lock(
                req: Request, callback: Callable[[Request],
                                                 Response]) -> Response:

            if self.processing:
                return Response("Processing contribution. Retry later.", 503)

            self.state_lock.acquire()
            try:
                return callback(req)
            except Exception as ex:
                warning(f"error in request: {ex}")
                print(f"error in request: {ex}")
                return Response("error: {ex}", 400)
            finally:
                self.state_lock.release()

        @app.route('/contributors', methods=['GET'])
        def contributors() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._contributors)

        @app.route('/state', methods=['GET'])
        def state() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._state)

        @app.route('/challenge', methods=['GET'])
        def challenge() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._challenge)

        @app.route('/contribute', methods=['POST'])
        def contribute() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._contribute)

        def _tick() -> None:
            self.state_lock.acquire()
            try:
                self._update_state(time.time())
            finally:
                self.state_lock.release()

        interval = Interval(60.0, _tick)
        try:
            if not exists(self.config.tls_certificate):
                raise Exception(f"no cert file {self.config.tls_certificate}")
            if not exists(self.config.tls_key):
                raise Exception(f"no key file {self.config.tls_key}")

            listen_addr = ('0.0.0.0', self.config.port)
            self.server = WSGIServer(listen_addr,
                                     PathInfoDispatcher({'/': app}),
                                     numthreads=1)
            self.server.ssl_adapter = BuiltinSSLAdapter(
                self.config.tls_certificate, self.config.tls_key)
            print(f"Listening on {listen_addr} ...")
            self.server.start()
        finally:
            interval.stop()
            self.server = None