Skip to content

Instantly share code, notes, and snippets.

@brianm
Created January 5, 2009 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianm/43473 to your computer and use it in GitHub Desktop.
Save brianm/43473 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import cgi
import cgitb; cgitb.enable()
import simplejson
import fcntl
import os
import re
import datetime
form = cgi.FieldStorage()
if form.has_key("debug"):
cgi.test()
exit()
doc_root = os.environ['DOCUMENT_ROOT']
method = os.environ['REQUEST_METHOD']
post = form.getfirst("post")
comment_root = doc_root + "/_comments"
def validate(doc_root, post):
if not post.startswith("/"): return False
if re.compile("\.\.").search(post): return False
if not os.path.isfile(doc_root + post + ".html"): return False
return True
if not validate(doc_root, post):
print("Status: 400")
print("Content-type: text/plain")
print("")
print("cheaterbad request")
exit(0)
def build_comment(author, body, source_ip):
comment = { 'author': author, 'content': body, 'source_ip': source_ip }
comment['date'] = datetime.datetime.today().isoformat()
return comment
def save_comment(filename, comment):
if os.path.isfile(filename):
# file exists
f = open(filename, 'r+')
fcntl.flock(f, fcntl.LOCK_EX)
cs = simplejson.loads(f.read())
cs.append(comment)
f.seek(0)
f.truncate()
s = simplejson.dumps(cs, indent=2)
f.write(s)
fcntl.flock(f, fcntl.LOCK_UN)
return s
else:
s = simplejson.dumps([comment], indent=2)
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
f = open(filename, 'w')
fcntl.flock(f, fcntl.LOCK_EX)
f.write(s)
fcntl.flock(f, fcntl.LOCK_UN)
return s
def do_stuff(form, doc_root, post):
remote = os.environ['REMOTE_ADDR']
comment = build_comment(form.getfirst("author", "anonymous"),
form.getfirst("content", ""),
remote)
return save_comment(comment_root + post + "-comments.json", comment)
if "GET" == method:
rs = do_stuff(form, doc_root, post)
print("Status: 200");
print("Content-Type: text/plain")
print("")
print(rs)
elif "POST" == method:
rs = do_stuff(form, doc_root, post)
print("Status: 200");
print("Content-Type: text/plain")
print("")
print(rs)
else:
print("Status: 405")
print("Content-Type: text/plain")
print("")
print("wtf? is " + method)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment