Created
March 18, 2010 23:22
-
-
Save clemesha/337043 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
# use this: http://codysoyland.com/2009/sep/6/introduction-surlex/ for URL->Regex mapping | |
# interesting: http://github.com/simonw/djangode | |
import copy | |
from twisted.web.server import Site | |
from twisted.web.resource import Resource | |
from twisted.internet import reactor | |
class ViewResource(Resource): | |
"""Associate a 'view' function with a | |
twisted.web.resource.Resource instance. | |
""" | |
def __init__(self, view): | |
Resource.__init__(self) | |
self.view = view or self._fourOfour | |
def _fourOfour(self, request): | |
return "404 Not Found" | |
def render(self, request): | |
return self.view(request) | |
class UrlDispatchSite(Site): | |
def __init__(self, urlpatterns, **kwargs): | |
Site.__init__(self, kwargs.get("resource"), logPath=kwargs.get("logPath"), timeout=kwargs.get("timeout", 60*60*12)) | |
self.urlpatterns = urlpatterns | |
def _view_for_uri(self, uri): | |
view = None | |
for (path, viewforpath) in self.urlpatterns: | |
if uri == path: #TODO replace with intelligent regex matching. | |
view = viewforpath | |
break #keep the first match | |
return view | |
def getResourceFor(self, request): | |
"""Get a resource for a request. | |
""" | |
request.site = self | |
request.sitepath = copy.copy(request.prepath) | |
view = self._view_for_uri(request.uri) | |
return ViewResource(view) | |
# | |
# example 'views' | |
# | |
def data(request): | |
if request.method == "POST": | |
print "data - POST" | |
print "data - request => ", request | |
return "data" | |
def info(request): | |
if request.method == "POST": | |
print "info - POST" | |
print "info - request => ", request | |
return "info" | |
urlpatterns = ( | |
("/data/foo", data), | |
("/info", info), | |
) | |
factory = UrlDispatchSite(urlpatterns) | |
reactor.listenTCP(8880, factory) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment