Created
March 29, 2014 09:17
-
-
Save martastain/9851245 to your computer and use it in GitHub Desktop.
Poor man's HTTP Push notifications
This file contains 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from urllib.parse import urlencode | |
from urllib.request import urlopen | |
url = "http://localhost:10000/" | |
try: | |
with urlopen(url, timeout=3) as feed: | |
while True: | |
line = feed.readline() | |
if not line: | |
break | |
print(line) | |
except ConnectionResetError: | |
print("Connection reset") |
This file contains 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import time | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
class AdminHandler(BaseHTTPRequestHandler): | |
def log_request(self, code='-', size='-'): | |
pass | |
def _do_headers(self,mime="application/json",response=200,headers=[]): | |
self.send_response(response) | |
self.send_header("Access-Control-Allow-Origin", "*") | |
self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") | |
for h in headers: | |
handler.send_header(h[0],h[1]) | |
self.send_header('Content-type', mime) | |
self.end_headers() | |
def _echo(self,istring): | |
self.wfile.write(istring.encode("utf-8")) | |
def do_GET(self): | |
print("Client connected") | |
self._do_headers(mime="text/txt", response=200) | |
try: | |
while True: | |
self._echo("{}\n".format(time.time())) | |
time.sleep(.5) | |
except (ConnectionAbortedError, ConnectionResetError): | |
print ("Client disconnected") | |
if __name__ == "__main__": | |
server = HTTPServer(('',10000), AdminHandler) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment