Created
April 26, 2013 15:51
-
-
Save karlcow/5468297 to your computer and use it in GitHub Desktop.
Prototype for a [webmention](http://webmention.org/) processor 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
#!/usr/bin/python | |
import cgi | |
import os | |
method = os.environ['REQUEST_METHOD'] | |
def mimeparse(http_accept): | |
"Create a reduced list of mime type without quality factors" | |
reduced_list = [] | |
for mime in http_accept.split(","): | |
separated_mime = mime.split(";") | |
mime_only = separated_mime[0].strip() | |
if mime_only in ["application/json", "text/html", "*/*"]: | |
reduced_list.append(mime_only) | |
return reduced_list | |
def json_response(): | |
"Webmention generic JSON response" | |
print "Status: 202" | |
print "Content-type: application/json\n\n" | |
print '{"result": "WebMention was successful"}' | |
def html_response(): | |
"Webmention generic HTML response" | |
print "Status: 202" | |
print "Content-type: text/html\n\n" | |
print """<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>WebMention</title> | |
</head> | |
<body> | |
<p><a href="http://webmention.org/">WebMention</a> was successful</p> | |
</body> | |
</html>""" | |
def process_data(form): | |
"""Process the webmention form data. | |
DONE: | |
- Collect the values | |
TODO: | |
- check if the values are URL. | |
- If the URLs exist (200 OK) | |
- If the content at 'source' contains a link to 'target'""" | |
source = form["source"].value | |
target = form["target"].value | |
pass | |
# we only accept HTTP POST | |
if method != "POST": | |
print "Status: 405" | |
print "Content-type: text/plain\n\n" | |
print "Only POST method is allowed. See http://webmention.org/" | |
else: | |
# get the accept header | |
accept = mimeparse(os.environ['HTTP_ACCEPT']) | |
# get the form data | |
form = cgi.FieldStorage() | |
# Accept contains application/json | |
if "application/json" in accept: | |
process_data(form) | |
json_response() | |
# Accept contains */* | |
elif "*/*" in accept: | |
process_data(form) | |
json_response() | |
# Accept contains text/html | |
elif "text/html" in accept: | |
process_data(form) | |
html_response() | |
# None of these before and we reject the request | |
else: | |
print "Status: 406" | |
print "Content-type: text/plain\n\n" | |
print "Wrong Accept header. We can provide only text/html or application/json. See http://webmention.org/" | |
print "Accept header is %s" % accept |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment