def serve(synamic, port): server = SynamicServer(synamic, ('localhost', port), SynamicDevServerRequestHandler) _addr = server.server_address[0] + ":" + str(server.server_address[1]) print("SERVE(): Server starting on %s" % _addr) observer = Observer() observer.schedule(MyHandler(server), path=synamic.site_root, recursive=True) observer.start() while server.signaled_stop is False and server.signaled_reload is False: try: server.handle_request() except: print("Shutdown exception?") break print("Stopping observer") observer.stop() print("joining...") observer.join() print('join exit...') # sys.stderr.flush() # sys.stdout.flush() if server.signaled_stop: return False elif server.signaled_reload: return True else: return True
def login(self): with http.server.HTTPServer(("", 0), OAuthReceiver) as server: state = str(uuid.uuid4()) query = urllib.parse.urlencode({ "client_id": self.client_id, "response_type": "code", # offline_access required to get a refresh_token "scope": "https://buildingsmartservices.onmicrosoft.com/api/read offline_access", "state": state, "redirect_uri": f"http://localhost:{server.server_address[1]}", }) webbrowser.open(f"{self.auth_endpoint}?{query}") server.timeout = 75 server.state = state server.handle_request() if server.auth_code and server.auth_state == state: self.set_tokens_from_response( requests.post( "https://buildingsmartservices.b2clogin.com/tfp/buildingsmartservices.onmicrosoft.com/b2c_1_signupsignin/oauth2/v2.0/token", params={ "grant_type": "authorization_code", "code": server.auth_code, }, ).json())
def _show_payload(payload): html = f"<!DOCTYPE html><html><head><title>{type(payload)}</title></head><body>" if isinstance(payload, Diff): for old, new in payload: if old is None: html += f'<p style="background-color:LightGreen">Added {new}</p>' elif new is None: html += f'<p style="background-color:IndianRed">Removed {old}</p>' else: html += f'<p style="background-color:Gold">Updated {old} -> {new}</p>' else: html += f"<p>{payload}<\p>" html += "</body></html>" class ReqHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html; charset=UTF-8") self.end_headers() self.wfile.write(html.encode("utf-8")) self.close_connection = True server = http.server.HTTPServer(('127.0.0.1', 0), ReqHandler) webbrowser.open_new(f"http://localhost:{server.server_address[1]}") server.handle_request() server.server_close()
def run_server(tmpdir, handler_class, stop_event, queue): # pragma: no cover """ Runs an HTTP server serving files from given tmpdir in a separate process. When it's ready, it sends a URL to the server over a queue so the main process (the HTTP client) can start making requests of it. """ class HTTPRequestHandler(handler_class): def translate_path(self, path): path = handler_class.translate_path(self, path) path = os.path.join(tmpdir, os.path.relpath(path, os.getcwd())) return path server = socketserver.TCPServer(("127.0.0.1", 0), HTTPRequestHandler) domain, port = server.server_address url = "http://{0}:{1}/".format(domain, port) # Set a reasonable timeout so that invalid requests (which may occur during # testing) do not cause the entire test suite to hang indefinitely server.timeout = 0.1 queue.put(url) # Using server.serve_forever does not work here since it ignores the # timeout value set above. Having an explicit loop also allows us to kill # the server from the parent thread. while not stop_event.isSet(): server.handle_request() server.server_close()
def authenticate(): server = http.server.HTTPServer(('', CONFIG["LOGARUN"].getint("PORT")), myHandler) URL = ("https://www.strava.com/oauth/authorize?client_id={0}&" "redirect_uri={1}&" "approval_prompt=auto&" "response_type=code&" "scope={2}").format(CONFIG["STRAVA"]["CLIENT_ID"], CONFIG["STRAVA"]["REDIRECT_URI"], CONFIG["STRAVA"]["SCOPE"]) print("Paste this URL: " + URL) server.handle_request() resp = requests.post("https://www.strava.com/oauth/token", params={ "client_id": CONFIG["STRAVA"]["CLIENT_ID"], "client_secret": CONFIG["STRAVA"]["CLIENT_SECRET"], "code": CODE, "grant_type": "authorization_code" }) json_out = resp.json() return json_out["access_token"], json_out["refresh_token"], json_out[ "expires_at"]
def run_server(tmpdir, handler_class, stop_event, queue): # pragma: no cover """ Runs an HTTP server serving files from given tmpdir in a separate process. When it's ready, it sends a URL to the server over a queue so the main process (the HTTP client) can start making requests of it. """ class HTTPRequestHandler(handler_class): def translate_path(self, path): path = handler_class.translate_path(self, path) path = os.path.join( tmpdir, os.path.relpath(path, os.getcwd())) return path server = socketserver.TCPServer(("127.0.0.1", 0), HTTPRequestHandler) domain, port = server.server_address url = "http://{0}:{1}/".format(domain, port) # Set a reasonable timeout so that invalid requests (which may occur during # testing) do not cause the entire test suite to hang indefinitely server.timeout = 0.1 queue.put(url) # Using server.serve_forever does not work here since it ignores the # timeout value set above. Having an explicit loop also allows us to kill # the server from the parent thread. while not stop_event.isSet(): server.handle_request() server.server_close()
def run(self): dummy_killer.write_pid(PID) try: while 1: sys.stdout.flush() server.handle_request() except KeyboardInterrupt: print("Interrupt") except socket.error: print("Socket closed")
def run(self): server_address = ('', self.port) server = http.server.HTTPServer(server_address, self.handler_class) server.timeout = self.timeout server.running = True end = time.time() + self.timeout while time.time() < end and server.running: server.handle_request() if not server.running: server.server_close()
def authorize(): webbrowser.open('https://connect.deezer.com/oauth/auth.php?' + urllib.parse.urlencode({ 'app_id': APPID, 'redirect_uri': 'http://127.0.0.1:{}/authfinish'.format(PORT), 'perms': 'basic_access,manage_library' })) # Start a simple, local HTTP server to listen for the authorization token... (i.e. a hack). server = _AuthorizationServer('127.0.0.1', PORT) try: while True: server.handle_request() except _Authorization as auth: get_actual_token(auth.access_token)
def runcam(): print("camera starting") with picamera.PiCamera(resolution='640x480', framerate=24) as camera: #output = StreamingOutput() #Uncomment the next line to change your Pi's Camera rotation (in degrees) #camera.rotation = 90 camera.start_recording(output, format='mjpeg') try: #server.serve_forever() for i in range(4): #refresh to end it server.handle_request() finally: camera.stop_recording() print("camera stopped")
def start_web_server(self, port): """ :rtype : string """ server = http.server.HTTPServer(('', port), ScriptCallbackWebServer) print('Started httpserver on port:', port) server.now_serving = True server.callback_code = None # Wait for incoming http requests # until a proper result is found while server.now_serving: server.handle_request() server.server_close() return server.callback_code
def authorize(app_id, secret, scope="basic_access,manage_library"): webbrowser.open('https://connect.deezer.com/oauth/auth.php?' + urllib.parse.urlencode({ 'app_id': app_id, 'redirect_uri': 'http://localhost:8080/authfinish', 'perms': scope })) # Start a simple, local HTTP server to listen for the authorization token... (i.e. a hack). server = _AuthorizationServer('localhost', 8080) try: while True: server.handle_request() except _Authorization as auth: return get_actual_token(app_id, secret, auth.access_token)
def authorize(client_id, scope): webbrowser.open('https://accounts.spotify.com/authorize?' + urllib.parse.urlencode({ 'response_type': 'token', 'client_id': client_id, 'scope': scope, 'redirect_uri': 'http://127.0.0.1:{}/redirect'.format(SpotifyAPI._SERVER_PORT) })) # Start a simple, local HTTP server to listen for the authorization token... (i.e. a hack). server = SpotifyAPI._AuthorizationServer('127.0.0.1', SpotifyAPI._SERVER_PORT) try: while True: server.handle_request() except SpotifyAPI._Authorization as auth: return SpotifyAPI(auth.access_token)
def main(): global CLIENT_ID, CLIENT_SECRET CLIENT_ID = input('Enter your client_id: ') CLIENT_SECRET = input('Enter your client_secret: ') flow = OAuth2WebServerFlow( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope='https://www.googleapis.com/auth/youtube.upload', redirect_uri='http://localhost:8915') webbrowser.open(flow.step1_get_authorize_url()) server = http.server.HTTPServer(('localhost', 8915), OAuth2Handler) server.handle_request()
def browser(cls, htmlstr): """Display html in the default web browser without creating a temp file. Instantiates a trivial http server and calls webbrowser.open with a URL to retrieve html from that server. """ class RequestHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): bufferSize = 1024*1024 for i in range(0, len(htmlstr), bufferSize): self.wfile.write(htmlstr[i:i+bufferSize]) server = http.server.HTTPServer(('127.0.0.1', 0), RequestHandler) webbrowser.open('http://127.0.0.1:%s' % server.server_port) server.handle_request()
def login(email: str): res = requests.post(API_URL + "/login", data={"email": email}) if res.status_code != 200: raise AuthenticationError("User not found.") cli.info("We sent you an email. Click the link inside to login.") # Start a localhost HTTP server to wait for the email verification token. server = http.server.HTTPServer(("", LOCAL_PORT), TokenHandler) server.handle_request() # Check for new token to see if we logged in successfully try: get_token() except AuthenticationError: raise AuthenticationError("Login Failed.")
def run( self ): handler = HTTPHandler handler.setLogger( handler, self.logger ) handler.setWriteDir( handler, self.writeDir ) server = socketserver.TCPServer( ( '', self.portIn ), handler ) self.logger.info( "HTTP listener started on %s:%s" % server.server_address ) ## Set the server to only handle_request() for this long server.timeout = 0.5 while True: server.handle_request() if not self.queue.empty(): code = self.queue.get() if code == 1: server.socket.close() break
def listen_once(*, timeout=None): json_data = None class CompetitiveCompanionHandler(http.server.BaseHTTPRequestHandler): def do_POST(self): nonlocal json_data json_data = json.load(self.rfile) with http.server.HTTPServer(('127.0.0.1', 10046), CompetitiveCompanionHandler) as server: server.timeout = timeout server.handle_request() if json_data is not None: print(f"Got data {json.dumps(json_data)}") else: print("Got no data") return json_data
def _http_python2(self, listen_ssl=False): """Listen for HTTP connections with Python 2.""" class ThreadingSimpleServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass server = ThreadingSimpleServer(self.listen_socket, DeenHTTPRequestHandler) os.chdir(self.serving_directory) message = 'Serving HTTP at port ' + str(self.listen_port) if listen_ssl: message += ' (SSL)' print(message) try: while 1: sys.stdout.flush() server.handle_request() except KeyboardInterrupt: server.socket.close()
def run_web_server(started): cwd = os.getcwd() try: os.chdir(test_data_path) server = http.server.HTTPServer(('', 64346), http.server.SimpleHTTPRequestHandler) # The web server is started and listening; let the test runner know started.acquire() try: started.notify() finally: started.release() while True: server.handle_request() finally: os.chdir(cwd)
def listen_once(*, timeout=None): json_data = None # Performing a POST request on the port 10046, To get information from Competitive Companion class CompetitiveCompanionHandler(http.server.BaseHTTPRequestHandler): def do_POST(self): nonlocal json_data json_data = json.load(self.rfile) with http.server.HTTPServer(('127.0.0.1', 10046), CompetitiveCompanionHandler) as server: server.timeout = timeout server.handle_request() # Printing out the JSON Dumps got from Competitive Companion if json_data is not None: print(f"Got data {json.dumps(json_data)}") else: print("Got no data") return json_data
def login(self): resp = requests.get(f"{self.baseurl}foundation/1.0/auth") values = resp.json() self.auth_endpoint = values["oauth2_auth_url"] self.token_endpoint = values["oauth2_token_url"] with http.server.HTTPServer(("", 8080), OAuthReceiver) as server: state = str(uuid.uuid4()) query = urllib.parse.urlencode({ "client_id": self.client_id, "response_type": "code", "state": state, "redirect_uri": f"http://localhost:{server.server_address[1]}/{self.redirect_subdir}", }) if "?" in self.auth_endpoint: webbrowser.open(f"{self.auth_endpoint}&{query}") else: webbrowser.open(f"{self.auth_endpoint}?{query}") server.timeout = 100 server.state = state server.handle_request() if server.auth_code and server.auth_state == state: data = { "grant_type": "authorization_code", "code": server.auth_code, "redirect_uri": f"http://localhost:{server.server_address[1]}/{self.redirect_subdir}", } auth_string = f"{self.client_id}:{self.client_secret}" header_string = base64.b64encode( auth_string.encode("utf-8")).decode("utf-8") headers = {"Authorization": f"Basic {header_string}"} self.set_tokens_from_response( requests.post(self.token_endpoint, data=data, headers=headers))
def auth_spot(server): url = SPOT_AUTH + "/authorize" payload = { "client_id": SPOT_ID, "response_type": "code", "redirect_uri": "http://localhost:9292", "state": uuid4().hex, "scope": "playlist-modify-public playlist-modify-private user-read-private", } s = requests.Session() r = requests.Request("GET", url, params=payload).prepare() wsopen(r.url) server.handle_request() return
def run_web_server(started, host: str = address, port: int = port, path: Path = fwd): cwd = os.getcwd() try: os.chdir(path) server = http.server.HTTPServer((host, port), http.server.SimpleHTTPRequestHandler) # The web server is started and listening; let the test runner know started.acquire() try: started.notify() finally: started.release() while True: server.handle_request() finally: os.chdir(cwd)
# -*- coding: utf-8 -*- """ Created on Fri Apr 10 23:02:45 2020 @author: Mary Liu Write an HTTP service that chooses an available high port number and serves a single copy of a memorable text to the first request that comes in. Because of firewall rules, requests to services running on hills have to come from within the college network """ import http.server import socketserver import os class Handler(http.server.SimpleHTTPRequestHandler): def do_GET(self): os.chdir("/var/tmp") if self.path == '/var/tmp': self.path = 'index.html' return http.server.SimpleHTTPRequestHandler.do_GET(self) if __name__ == '__main__': PORT = 8123 handler_object = Handler with socketserver.TCPServer(("", PORT), handler_object) as server: server.handle_request()
def httpd(handler_class=FileServerHTTPHandler, server_address = ('', 8008), ): while (1): server = http.server.HTTPServer(server_address, handler_class) server.handle_request() # serve_forever
# ブラウザ起動してBOXのIDとパスワードを入力する # 入力するとREDIRECT_URIにリダイレクトされる webbrowser.open(auth_url) # REDIRECT_URIが叩かれた時の処理 class ServerHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): global auth_code self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b"<h1>Authenticated</h1>") parsed_path = urlparse(self.path) query = parse_qs(parsed_path.query) auth_code = query['code'][0] with socketserver.TCPServer((HOST, PORT), ServerHandler) as server: print('http server start') # server.serve_forever() # Ctrl+Cが押されるなどの割り込みがあるまで処理し続ける server.handle_request() # 1回リクエストを処理したら抜ける print('http server shutdown') # auth_codeが取れたので、ここからAPIが使える ACCESS_TKN, REFRESH_TKN = oauth.authenticate(auth_code) # API実行(ユーザID取得) client = Client(oauth) me = client.user().get() print('My user ID is {0}'.format(me.id))
def start(): global server global flag flag = 1 while flag == 1: server.handle_request()
def Serve(): while not server.finished: server.handle_request()
#!/usr/bin/env python import sys import os,stat v=sys.hexversion >> 24 if v == 2: import BaseHTTPServer,SimpleHTTPServer server = BaseHTTPServer.HTTPServer( ('127.0.0.1',8080), SimpleHTTPServer.SimpleHTTPRequestHandler) else: import http.server server = http.server.HTTPServer( ('127.0.0.1',8080), http.server.SimpleHTTPRequestHandler) while 1: server.handle_request()
def process_server(responder, port): with http.server.HTTPServer(("localhost", port), responder) as server: server.handle_request() server.server_close()
def function_to_profile(nr_requests): global server for i in range(nr_requests): server.handle_request()
def run(self): print("Starting http server.") address = ('', 5000) server = StreamingServer(address, StreamingHandler) while 1: server.handle_request()
def run(): while True: server.handle_request()