Created
November 26, 2014 01:51
-
-
Save vampjaz/474a370f7c3273403827 to your computer and use it in GitHub Desktop.
Simple xkcd-based page rendered, in python
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
import socket, threading | |
import requests | |
import time, random | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.settimeout(8) | |
sock.bind(("",7593)) | |
sock.listen(10) | |
def handler(con,addr): | |
header_in = "" | |
thischar = '' | |
while thischar != '\n': | |
try: | |
thischar = con.recv(1) | |
header_in += thischar | |
except: | |
return | |
print "\t%s" % (header_in,) | |
req,url,proto = header_in.split() | |
if req == 'GET': | |
#send http header | |
con.sendall("HTTP/1.1 200 OK\n") | |
con.sendall("Content-Type: text/html\n") | |
con.sendall("Connection: close\n") | |
con.sendall("\n") | |
#send data | |
con.sendall("<!doctype html>\n") | |
con.sendall("""<html><head><title>WebPage</title> | |
<style type='text/css'> | |
body {color:#011; background-color:#ffc; font-family:"Trebuchet MS", Helvetica, sans-serif;} | |
</style> | |
</head>\n""") | |
con.sendall("<body><center>\n") | |
#insert content here | |
uri = '' | |
try: | |
uri = int(url[1:]) | |
except: | |
pass | |
comicdata = requests.get("http://xkcd.com/%s/info.0.json"%(str(uri),)).json() | |
navbar = "<a class='button' href='/1'>|<</a> <a class='button' href='/%i'><</a> <a class='button' href='/random'>Random</a> <a class='button' href='/%i'>></a> <a class='button' href='/'>>|</a>"%(comicdata['num']-1,comicdata['num']+1) | |
con.sendall("""<h3>XKCD #%i</h3><h3>%s</h3><br/> | |
%s<br/> | |
<img src='%s' title='%s'/><br/> | |
%s<br/> | |
<p><b>Alt:<br/></b>%s</p> | |
<p align='left'><b>Transcript:<br/></b>%s</p> | |
<p><b>News:<br/></b>%s</p>""" % ( | |
comicdata['num'],comicdata['safe_title'],navbar,comicdata['img'], | |
comicdata['alt'],navbar,comicdata['alt'],comicdata['transcript'] | |
.replace('\n','<br/>').replace('[[','<i>').replace(']]','</i>') | |
.split('{{',1)[0],comicdata['news'])) | |
#end of content | |
con.sendall("<br/><br/><hr/><p>Generated on %s</p>"% (time.strftime('%A, %B %d, %Y at %I:%M:%S %p'),)) | |
con.sendall("</center></body></html>\n") | |
con.close() | |
while True: | |
try: | |
c,a = sock.accept() | |
except socket.timeout: | |
continue | |
print "Accepted a connection from %s:%s" % (a[0],a[1]) | |
hand = threading.Thread(target=handler,args=(c,a)) | |
hand.run() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment