Skip to content

Instantly share code, notes, and snippets.

@saga
Created October 13, 2012 01:37
Show Gist options
  • Select an option

  • Save saga/3882844 to your computer and use it in GitHub Desktop.

Select an option

Save saga/3882844 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import time
import sys
import os
import json
from flask import Flask, Request, Response
from werkzeug.routing import BaseConverter
import urllib2
application = app = Flask('wsgi')
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp
@app.route('/')
def welcome():
return 'welcome to appfog!'
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter
@app.route('/atestaaafads/<regex("[abcABC0-9]{4,6}"):uid>-<slug>/')
def example1(uid, slug):
return "uid: %s, slug: %s" % (uid, slug)
@app.route('/mp4/<regex(".*"):filename>')
def FetchM4V(filename):
response1 = urllib2.urlopen(filename)
content = response1.read()
return Response(content, content_type="video/mp4")
@app.route('/mp3/<regex(".*"):filename>')
def FetchMP3(filename):
response1 = urllib2.urlopen(filename)
content = response1.read()
return Response(content, content_type="audio/mp3")
@app.route('/htm/<regex(".*"):filename>')
def FetchHTM(filename):
response1 = urllib2.urlopen(filename)
content = response1.read()
return Response(content, content_type="text/html")
@app.route('/jpg/<regex(".*"):filename>')
def FetchJPG(filename):
response1 = urllib2.urlopen(filename)
content = response1.read()
return Response(content, content_type="image/jpeg")
@app.route('/env')
def env():
return os.environ.get("VCAP_SERVICES", "{}")
@app.route('/mongo')
def mongotest():
from pymongo import Connection
uri = mongodb_uri()
conn = Connection(uri)
coll = conn.db['ts']
coll.insert(dict(now=int(time.time())))
last_few = [str(x['now']) for x in coll.find(sort=[("_id", -1)], limit=10)]
body = "\n".join(last_few)
return Response(body, content_type="text/plain;charset=UTF-8")
def mongodb_uri():
local = os.environ.get("MONGODB", None)
if local:
return local
services = json.loads(os.environ.get("VCAP_SERVICES", "{}"))
if services:
creds = services['mongodb-1.8'][0]['credentials']
uri = "mongodb://%s:%s@%s:%d/%s" % (
creds['username'],
creds['password'],
creds['hostname'],
creds['port'],
creds['db'])
print >> sys.stderr, uri
return uri
else:
raise Exception, "No services configured"
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment