Advertisement
here2share

# get_data_from_localhost.py

Nov 14th, 2023
1,663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # get_data_from_localhost.py
  2. # kept hearing a whole lot of people swear this the builtin attempt is an impossible feat, even warned by ChatGPT, but... it seems to work perfectly fine
  3.  
  4. import http.server
  5. import socketserver
  6. import webbrowser
  7. import json
  8. import urllib.parse
  9.  
  10. html_content = """
  11. <html>
  12. <head>
  13. <script>
  14. function multiplyNumbers() {
  15.     var numbers = [1, 2, 3, 4, 5];
  16.     var multipliedNumbers = [];
  17.  
  18.     for (var i = 0; i < numbers.length; i++) {
  19.         multipliedNumbers.push(numbers[i] * 9);
  20.     }
  21.  
  22.     var data = JSON.stringify(multipliedNumbers);
  23.     var url = 'http://localhost:8080?data=' + encodeURIComponent(data);
  24.  
  25.     var xhr = new XMLHttpRequest();
  26.     xhr.open('GET', url, true);
  27.     xhr.onreadystatechange = function () {
  28.         if (xhr.readyState === 4 && xhr.status === 200) {
  29.             document.write(xhr.responseText);
  30.         }
  31.     };
  32.     xhr.send();
  33.  
  34.     return multipliedNumbers;
  35. }
  36.  
  37. document.write(multiplyNumbers());
  38. </script>
  39. </head>
  40. <body></body>
  41. </html>
  42. """
  43.  
  44. def http_server():
  45.     class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
  46.         def do_GET(self):
  47.             if self.path == '/':
  48.                 self.send_response(200)
  49.                 self.send_header("Content-type", "text/html")
  50.                 self.end_headers()
  51.                 self.wfile.write(html_content.encode())
  52.            
  53.             query_components = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
  54.             if 'data' in query_components:
  55.                 data = query_components['data'][0]
  56.                 print(data)
  57.  
  58.     with socketserver.TCPServer(('localhost', 8080), MyHttpRequestHandler) as httpd:
  59.         webbrowser.open('http://localhost:8080')
  60.         httpd.serve_forever()
  61.  
  62. http_server()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement