109 lines
2.3 KiB
Python
Executable File
109 lines
2.3 KiB
Python
Executable File
import sys
|
|
import time
|
|
|
|
from lnwsgi.exceptions import WebException
|
|
|
|
class TypeAware:
|
|
|
|
def media(self, mimeType, request):
|
|
raise UnsupportedMediaType( mimeType )
|
|
|
|
def __call__(self, request):
|
|
for accepted in request.accepts():
|
|
try:
|
|
return self.media( accepted )
|
|
except UnsupportedMediaType:
|
|
pass
|
|
|
|
raise UnsupportedMediaType(", ".join(request.accepts()))
|
|
|
|
class Walkable:
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
def walk(self, request, path = []):
|
|
if len(path) == 0:
|
|
return self( request )
|
|
|
|
np = path.pop(0)
|
|
next = None
|
|
|
|
try:
|
|
print("___ = {0} : {1}".format(str(self),np))
|
|
next = getattr( self, np )
|
|
except AttributeError:
|
|
if len(path) == 0 and request.method == "PUT":
|
|
return self.PUT( request, np )
|
|
raise WebException("Not Found", status = 404)
|
|
|
|
if not isinstance( next, Walkable ):
|
|
raise TypeError("Walkable needed")
|
|
|
|
return next.walk( request, path )
|
|
|
|
def GET(self, request):
|
|
return ("No Implementation here.".encode(),)
|
|
|
|
def PUT(self, request, name):
|
|
raise WebException("Object already exists!")
|
|
|
|
POST = GET
|
|
PUT = GET
|
|
HEAD = GET
|
|
DELETE = None
|
|
|
|
def __call__(self, request):
|
|
method = getattr(self, request.method)
|
|
return method( request )
|
|
|
|
class CachedWalkable(Walkable):
|
|
|
|
def __init__(self):
|
|
Walkable.__init__(self)
|
|
|
|
self.__cache_size = 16 # Maximum number of entries within cache
|
|
self.__cache = {} # key -> value table
|
|
self.__cache_names = [] # List of all cached names (youngest accessed #0)
|
|
|
|
def _touchCache(self, name):
|
|
if name in self.__cache_names:
|
|
self.__cache_names.remove( name )
|
|
self.__cache_names.insert(0, name)
|
|
if len(self.__cache_names) > self.__cache_size:
|
|
self._rmCachedObject( self.__cache_names[-1] )
|
|
|
|
def _addCachedObject(self, name, value):
|
|
self.__cache[ name ] = value
|
|
self._touchCache( name )
|
|
|
|
def _rmCachedObject(self, name):
|
|
del self.__cache[ name ]
|
|
self.__cache_names.remove( name )
|
|
|
|
|
|
|
|
def lookup(self,name):
|
|
raise AttributeError(name)
|
|
|
|
def __getattr__(self,name):
|
|
if name in self.__cache_names:
|
|
self._touchCache( name )
|
|
return self.__cache[ name ]
|
|
|
|
o = self.lookup(name)
|
|
self._addCachedObject( name, o )
|
|
return o
|
|
|
|
|
|
class Callable(Walkable):
|
|
|
|
def __init__(self, m):
|
|
self.__method = m
|
|
|
|
def __call__(self, s, request):
|
|
return self.__method( s, request )
|
|
|
|
|
|
|