Skip to content

Instantly share code, notes, and snippets.

@Lekensteyn
Created April 7, 2014 14:29
Show Gist options
  • Save Lekensteyn/10021344 to your computer and use it in GitHub Desktop.
Save Lekensteyn/10021344 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# Attempt to find the cause for http://meta.stackoverflow.com/q/228587/150311
# (“Hot Network Questions” change when I hit Back button in my browser)
try:
from http.server import *
except:
from BaseHTTPServer import *
from datetime import datetime
import time
import gzip
try:
from io import BytesIO
except:
import BytesIO
class DemoHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_stuff()
def do_HEAD(self):
self.send_stuff(True)
def send_stuff(self, is_HEAD=False):
stamp = time.time()
body = '<pre><a href="a">aaaa</a>\n'
body += '<a href="b">bbbb</a>\n'
body += self.date_time_string(stamp) + '\n'
# Maybe the cache breaks on large documents? Nope.
body += '<!-- '
for i in range(0, 10240):
body += 'Fill to make document larger ' + str(i)
body += ' -->'
if self.headers.get('Accept-Encoding'):
body += 'Compressed\n'
out = BytesIO()
with gzip.GzipFile(fileobj=out, mode='w') as gzf:
gzf.write(body.encode('UTF_8'))
data = out.getvalue()
else:
data = body.encode('UTF-8')
self.protocol_version = 'HTTP/1.1'
try:
self.send_response_only(200)
except:
self.wfile.write('HTTP/1.1 200 OK\r\n')
# Reproduction of SO headers
hdrs = (
'Cache-Control: public, max-age=60',
'Content-Type: text/html; charset=utf-8',
'Content-Encoding: gzip',
'Expires: ' + self.date_time_string(stamp + 60),
'Last-Modified: ' + self.date_time_string(stamp),
'Vary: *',
'X-Frame-Options: SAMEORIGIN',
'Date: ' + self.date_time_string(stamp - 1),
'Content-Length: ' + str(len(data))
)
for line in hdrs:
hdr, value = line.split(': ', 2)
date = self.date_time_string(stamp + 3600 * 24 * 7)
self.send_header(hdr, value)
if not self.headers.get("Cookie"):
self.send_header("Set-Cookie", 'foo=bar; expires=' + date + '; HttpOnly')
self.end_headers()
if not is_HEAD:
self.wfile.write(data)
addr = ('', 8000)
httpd = HTTPServer(addr, DemoHandler)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment