Skip to content

Instantly share code, notes, and snippets.

@teepark
Created February 9, 2011 06:52
Show Gist options
  • Save teepark/818060 to your computer and use it in GitHub Desktop.
Save teepark/818060 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# vim: fileencoding=utf8:et:sta:ai:sw=4:ts=4:sts=4
from feather import wsgi
import greenhouse
import cgi
import logging
import tempfile
import urllib
os = greenhouse.patched("os")
urllib2 = greenhouse.patched("urllib2")
CTYPES = {
'image/jpeg': 'jpg',
'image/gif': 'gif',
'image/png': 'png',
}
IMAGE_FOLDER = '/var/www/imgs'
DOWNLOAD_PATH = 'http://teepark.net/imgs'
def wsgi_app(environ, start_response):
url = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('url')
if not url:
msg = "a 'url' argument is required"
start_response("403 Forbidden", [
('content-type', 'text/plain'),
('content-length', len(msg))])
return [msg]
response = urllib2.urlopen(url[0])
ctype = response.headers.get('content-type', '')
if ctype not in CTYPES:
msg = "invalid content-type: %r" % ctype
start_response("403 Forbidden", [
('content-type', 'text/plain'),
('content-length', len(msg))])
return [msg]
fd, tmpfile = tempfile.mkstemp()
filename = "%s%s%s.%s" % (
IMAGE_FOLDER, os.sep, os.path.split(tmpfile)[1], CTYPES[ctype])
with os.fdopen(fd, 'wb') as fp:
fp.write(response.read())
os.rename(tmpfile, filename)
os.chmod(filename, 0644)
url = "/".join((DOWNLOAD_PATH, os.path.split(filename)[1]))
url = urllib2.urlopen("http://is.gd/create.php",
urllib.urlencode({'format': 'simple', 'url': url})).read()
start_response("200 OK", [
('content-type', 'text/plain'),
('content-length', len(url))])
return [url]
if __name__ == '__main__':
logging.getLogger("feather.http").addHandler(logging.StreamHandler())
wsgi.serve(("0.0.0.0", 9000), wsgi_app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment