Created
March 16, 2025 10:30
-
-
Save monperrus/21151e2db4a7fdc505bff157918e61b5 to your computer and use it in GitHub Desktop.
in python 3, start an http server, when a request is received, save the GET query parameter in file code.txt and shutdown the server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from http.server import BaseHTTPRequestHandler, HTTPServer | |
| import urllib.parse | |
| class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): | |
| def do_GET(self): | |
| # Parse the query parameters from the URL | |
| parsed_path = urllib.parse.urlparse(self.path) | |
| query_params = urllib.parse.parse_qs(parsed_path.query) | |
| # Extract the 'code' parameter if it exists | |
| code = query_params.get('code', [None])[0] | |
| # Save the code to a file | |
| if code is not None: | |
| with open('code.txt', 'w') as f: | |
| f.write(code) | |
| # Send a response back to the client | |
| self.send_response(200) | |
| self.send_header('Content-type', 'text/html') | |
| self.end_headers() | |
| self.wfile.write(b'Code received and saved. Shutting down the server.') | |
| # Shut down the server | |
| self.server.shutdown() | |
| return | |
| def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8080): | |
| server_address = ('', port) | |
| httpd = server_class(server_address, handler_class) | |
| print(f'Starting httpd on port {port}...') | |
| httpd.serve_forever() | |
| if __name__ == "__main__": | |
| run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment