Created
March 20, 2013 21:19
-
-
Save jrmoserbaltimore/5208554 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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).