Skip to content

Instantly share code, notes, and snippets.

@jrmoserbaltimore
Created March 20, 2013 21:19
Show Gist options
  • Save jrmoserbaltimore/5208554 to your computer and use it in GitHub Desktop.
Save jrmoserbaltimore/5208554 to your computer and use it in GitHub Desktop.
#!/bin/env python
import cherrypy
import urlparse
import random
import re
class Balancer(object):
http_url = re.compile(r"""^(?P<subdomain>[-\w]+)\.(?P<domain>[-\w]+\.\w+)$""")
def __init__(self):
#cherrypy.config.update({ "environment": "embedded" })
pass
def default(self):
url = urlparse.urlparse(cherrypy.url())
r = Balancer.http_url.match(url.hostname)
if r == None:
return 'Guru Meditation: Bad Domain?'
sub = r.group('subdomain')
dom = r.group('domain')
svr = str(random.randint(1,2))
url_out = url.scheme + '://' + sub + svr + '.' + dom + url.path
if url.query:
url_out = url_out + '?' + url.query
if url.fragment:
url_out = url_out + '#' + url.fragment
return url_out
#raise cherrypy.HTTPRedirect(url_out, 302)
default.exposed = True
cherrypy.server.socket_port = 3000
cherrypy.quickstart(Balancer())
@ionrock
Copy link

ionrock commented Mar 20, 2013

I saw your question in #cherrypy.

Cherrypy can automatically parse segments for you when you use the default method and pass them as arguments to the method. For example:

class Example(object):
    @cherrypy.tools.json_out()
    def default(self, *args, **kw):
        return {
            'segments': args, 'params': kw,
        }
    default.exposed = True

cherrypy.quickstart(Example())

If you run this example you can visit http://localhost:8080/foo/bar/baz?hello=world and you should see a JSON response with {'segments': ['foo', 'bar', 'baz'], 'params': {'hello': 'world'}}.

As an aside, CherryPy also has a virtual hosts tool that might be helpful (http://tools.cherrypy.org/wiki/VirtualHosts).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment