92 lines
2.1 KiB
Python
Executable File
92 lines
2.1 KiB
Python
Executable File
import sys
|
|
import traceback
|
|
import io
|
|
|
|
import lnwsgi
|
|
from lnwsgi.exceptions import WebException
|
|
|
|
|
|
class WSGIApplication:
|
|
|
|
def __init__(self, appName = "WSGIApplication"):
|
|
self.__root = lnwsgi.walkable.Walkable()
|
|
self.url = None
|
|
self.appName = appName
|
|
|
|
def root(self):
|
|
return self.__root
|
|
|
|
def setRoot(self, r):
|
|
self.__root = r
|
|
|
|
def setApplicationURL(self, url):
|
|
self.url = url
|
|
|
|
|
|
def authenticate(self, request):
|
|
return lnwsgi.authentication.Identity("", [])
|
|
|
|
|
|
def handle(self, request):
|
|
# try:
|
|
path = list( filter( None, request.path.split("/") ) )
|
|
|
|
response = self.__root.walk( request, path )
|
|
|
|
if isinstance(response, str):
|
|
response = ( response.encode(), )
|
|
|
|
return response
|
|
# except:
|
|
# ei = sys.exc_info()
|
|
# request.setResponseHeader("content-type","text/html")
|
|
# return ("<html><body>{0}: {1}</body></html>".format(ei[0].__name__,ei[1]).encode(),)
|
|
|
|
def handleException(self, request, exc_info = None):
|
|
if exc_info is None:
|
|
exc_info = sys.exc_info()
|
|
|
|
m = io.StringIO()
|
|
|
|
m.write("Exception: {0}\n".format(exc_info[0].__name__))
|
|
m.write("Message: {0}\n".format(exc_info[1]))
|
|
m.write("Traceback: {0}\n".format(
|
|
"\n ".join( traceback.extract_tb(exc_info[2]).format() )
|
|
))
|
|
|
|
if isinstance(exc_info[1], WebException ):
|
|
status = exc_info[1].status
|
|
else:
|
|
status = 500
|
|
|
|
if status == 401:
|
|
request.setResponseHeader("WWW-Authenticate","Basic realm=\"{0}\", charset=\"UTF-8\"".format(self.appName))
|
|
|
|
request.setResponseHeader("content-type","text/plain")
|
|
request.status(status)
|
|
|
|
return (m.getvalue().encode(),)
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
request = lnwsgi.WSGIRequest( self, environ )
|
|
print("R: {0:16} {1}".format( str(request.identity()), request ))
|
|
|
|
try:
|
|
request.identity().authorize( request )
|
|
response = self.handle( request )
|
|
except:
|
|
response = self.handleException( request, sys.exc_info() )
|
|
|
|
|
|
start_response(
|
|
lnwsgi.status.getStatusMessage(request.status()),
|
|
request.listResponseHeaders()
|
|
)
|
|
|
|
return response
|
|
|
|
|
|
|
|
|