コード例 #1
0
ファイル: td.py プロジェクト: mgalgs/thetactl
    def get_new_refresh_token(self):
        server = threading.Thread(target=self._start_server)
        server.setDaemon(True)
        server.start()

        redirect_uri = urllib.parse.quote(REDIRECT_URL)
        consumer_key = urllib.parse.quote(self._consumer_key)
        url = ("https://auth.tdameritrade.com/auth?"
               "response_type=code&"
               f"redirect_uri={redirect_uri}&"
               f"client_id={consumer_key}%40AMER.OAUTHAP"
               "&scope=AccountAccess")
        print(f"Opening {url}")
        print("Please authorize the app from your web browser.")
        print("You may see a warning about using a self-signed certificate.")
        print("If you're using chrome you might need to bypass certificate")
        print("errors for localhost by enabling the option here:")
        print("  chrome://flags/#allow-insecure-localhost")
        webbrowser.open(url)
        server.join()
        data = {
            'grant_type': 'authorization_code',
            'refresh_token': None,
            'access_type': 'offline',
            'code': self._returned_code,
            'client_id': self._consumer_key,
            'redirect_uri': REDIRECT_URL,
        }
        rsp = requests.post(TdAuth.TOKEN_URL, data=data)
        rdata = rsp.json()
        return rdata['refresh_token'], rdata['refresh_token_expires_in']
コード例 #2
0
def setup_observer(builder_instance, port):
    """Setup and start the watchdog observer for the --watch command."""
    handler = UpdateHandler(builder_instance)
    observer = Observer()
    observer.schedule(handler,
                      path=builder_instance.searchpath,
                      recursive=True)
    observer.schedule(handler, path=settings.ASSETS, recursive=True)
    observer.schedule(handler,
                      path=settings.MEDIA_URL.strip('/'),
                      recursive=True)
    observer.daemon = True
    observer.start()
    print(
        "Updating website when templates, CSS, or JS are modified. Press Ctrl-C to end."
    )
    server = setup_httpd(port, builder_instance.renderpath)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Shutting down watcher and server...")
        server.terminate()
        server.join()
        observer.stop()
        observer.join()
コード例 #3
0
ファイル: __init__.py プロジェクト: wwt1990/Maps
def load_visualization(url, base_url='http://localhost:8000/visualize/'):
    """Load the visualization located at URL."""
    server = start_threaded_server()
    webbrowser.open_new(base_url + url)
    try:
        server.join()
    except KeyboardInterrupt:
        print('\nKeyboard interrupt received, exiting.')
コード例 #4
0
def run_server(port):
    server = threading.Thread(target=server_start, args=(port, ))
    file_watcher = threading.Thread(target=file_watching, args=())

    file_watcher.start()
    server.start()
    file_watcher.join()
    server.join()
コード例 #5
0
ファイル: __init__.py プロジェクト: XiaoqianZhu1997/cs61a
def load_visualization(url):
    """Load the visualization located at URL."""
    if not check_port():
        print('Address already in use! Check if recommend.py is running in a separate terminal.')
        return
    server = start_threaded_server()
    webbrowser.open_new(base_url + url)
    try:
        server.join()
    except KeyboardInterrupt:
        print('\nKeyboard interrupt received, exiting.')
コード例 #6
0
def load_visualization(url):
    """Load the visualization located at URL."""
    if not check_port():
        print("Address already in use! Check if recommend.py is running in a separate terminal.")
        return
    server = start_threaded_server()
    webbrowser.open_new(base_url + url)
    try:
        server.join()
    except KeyboardInterrupt:
        print("\nKeyboard interrupt received, exiting.")
コード例 #7
0
def main(headless):
    port = STATE.get("PREFERRED_PORT")
    if not port:
        port = 8000

    httpd = http.server.HTTPServer(
        ("", port),
        CohortManagerRequestHandler
    )

    if STATE["DEBUG"] or headless:
        print("Server listening on port {}.".format(port))

    # Launch the server thread.
    server = threading.Thread(target=httpd.serve_forever, daemon=False)
    server.start()

    if headless:
        # In headless mode, the only thing that the main thread will do is
        # to wait for interrupt.
        try:
            while server.is_alive():
                pass
        except:
            httpd.shutdown()
            return

    else:
        try:
            client(port)
        except EOFError:
            print("YO")
            httpd.shutdown()
        except KeyboardInterrupt:
            print("Ya")

        httpd.shutdown()
        server.join()
コード例 #8
0
# Parse command line arguments
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-r", "--remote-ip", default="192.168.0.1", help="Router IP address")
parser.add_argument("-l", "--local-ip", default="192.168.0.2", help="This computers IP address")
parser.add_argument("-p", "--port", type=int, default=8000, help="Port local server serving file is using")
parser.add_argument("-f", "--file", required=True, help="File to upload")
parser.add_argument("-n", "--name", default="upload", help="Filename after upload")
parser.add_argument("-e", "--executable", action="store_true", default=False, help="Should file be marked as executable after upload")
parser.add_argument("-x", "--run", action="store_true", default=False, help="Should file be run after upload")
args = parser.parse_args()

# Start webserver serving the files in the current dictionary
server = Server(args.port)
server.start()

# Run command on router to download file from webserver
run_command("wget -O /tmp/{} http://{}:{}/{}".format(args.name, args.local_ip, args.port, args.file))

if args.executable:
    # Mark downloaded file executable
    run_command("chmod +x /tmp/{}".format(args.name))

if args.run:
    # Execute downloaded file
    run_command("./tmp/{}".format(args.name))

# Stop webserver
server.stop()
server.join()
コード例 #9
0
ファイル: muneage.py プロジェクト: aoirint/miyadaiku
def _main() -> None:
    args = parser.parse_args()

    props = {}
    for s in args.define or ():
        d = [p.strip() for p in s.split("=", 1)]
        if len(d) != 2:
            print(f"Invalid property: {s!r}", file=sys.stderr)
            sys.exit(1)
        props[d[0]] = d[1]

    d = Path(args.directory)

    if not d.exists() or not d.is_dir():
        print(f"'{d}' is not a valid directory", file=sys.stderr)
        sys.exit(1)

    mp_log.init_logging()

    if args.output:
        outputs = Path(args.output)
    else:
        outputs = d / OUTPUTS_DIR

    if not outputs.is_dir():
        outputs.mkdir()

    if args.server:
        server = multiprocessing.Process(
            target=exec_server,
            kwargs=dict(dir=str(outputs), port=args.port, bind=args.bind),
            daemon=True,
        )

        server.start()

    try:
        if not args.watch:
            err = build(d, outputs, props, args)
            if args.server:
                server.join()
            return 1 if err else 0
        else:
            print(f"Watching {d.resolve()} ...")

            ev = threading.Event()

            obsrv = observer.create_observer(d, ev)
            obsrv.start()

            ev.set()  # run once at least
            while True:
                ev.wait()
                time.sleep(0.1)
                ev.clear()

                build(d, outputs, props, args)

        if args.server:
            server.join()
    finally:
        if args.server:
            server.terminate()

    return
コード例 #10
0
ファイル: badapp.py プロジェクト: Super-Rad/wpull
        self.http_server.start()
        self.http_server.started_event.wait(timeout=5.0)
        self._port = self.http_server.port

    def get_http_port(self):
        return self._port

    def get_protocol(self):
        return 'http'

    def get_url(self, path):
        # from tornado.testing
        return '%s://localhost:%s%s' % (self.get_protocol(),
                                        self.get_http_port(), path)

    def tearDown(self):
        self.http_server.stop()
        self.http_server.join(timeout=5)
        AsyncTestCase.tearDown(self)
        TornadoAsyncTestCase.tearDown(self)


class SSLBadAppTestCase(BadAppTestCase):
    def get_protocol(self):
        return 'https'

if __name__ == '__main__':
    server = Server(8888)
    server.start()
    server.join()