def delegate_error_to_simplate(website, state, response, request=None, resource=None): if request is None: return # early parsing must've failed if response.code < 400: return code = str(response.code) possibles = [code + ".spt", "error.spt"] fspath = _first(website.ours_or_theirs(errpage) for errpage in possibles) if fspath is not None: request.original_resource = resource resource = resources.get(website.request_processor, fspath) state['dispatch_result'] = DispatchResult( DispatchStatus.okay , fspath , {} , 'Found.' , {} , True ) # Try to return an error that matches the type of the response the # client would have received if the error didn't occur wanted = getattr(state.get('output'), 'media_type', None) or '' # If we don't have a media type (e.g. when we're returning a 404), then # we fall back to the Accept header wanted += ',' + (state.get('accept_header') or '') # As a last resort we accept anything, with a preference for text/plain wanted += ',text/plain;q=0.2,*/*;q=0.1' state['accept_header'] = wanted.lstrip(',') render_response(state, resource, response, website.request_processor)
def delegate_error_to_simplate(website, state, response, request=None, resource=None): if request is None: return # early parsing must've failed if response.code < 400: return code = str(response.code) possibles = [code + ".spt", "error.spt"] fspath = _first(website.ours_or_theirs(errpage) for errpage in possibles) if fspath is not None: request.original_resource = resource resource = resources.get(website.request_processor, fspath) state['dispatch_result'] = DispatchResult(DispatchStatus.okay, fspath, {}, 'Found.', {}, True) # Try to return an error that matches the type of the response the # client would have received if the error didn't occur wanted = getattr(state.get('output'), 'media_type', None) or '' # If we don't have a media type (e.g. when we're returning a 404), then # we fall back to the Accept header wanted += ',' + (state.get('accept_header') or '') # As a last resort we accept anything, with a preference for text/plain wanted += ',text/plain;q=0.2,*/*;q=0.1' state['accept_header'] = wanted.lstrip(',') render_response(state, resource, response, website.request_processor)
def redirect_confirmation(website, request): from aspen import resources request.internally_redirected_from = request.fs request.fs = website.www_root + '/on/confirm.html.spt' request.resource = resources.get(request) raise request.resource.respond(request)
def handle_error_nicely(self, request): """Try to provide some nice error handling. """ try: # nice error messages tb_1 = traceback.format_exc() response = sys.exc_info()[1] if not isinstance(response, Response): aspen.log_dammit(tb_1) response = Response(500, tb_1) elif 200 <= response.code < 300: return response response.request = request self.hooks.outbound_early.run(response) fs = self.ours_or_theirs(str(response.code) + '.html') if fs is None: fs = self.ours_or_theirs('error.html') if fs is None: raise request.fs = fs request.original_resource = request.resource request.resource = resources.get(request) response = request.resource.respond(request, response) return response except Response, response: # no nice error simplate available raise
def handler(self, request): """Given an Aspen request, return an Aspen response. The default handler uses Resource subclasses to generate responses from simplates on the filesystem. See aspen/resources/__init__.py. You can monkey-patch this method to implement single-page web apps or other things in configure-aspen.py: from aspen import Response def greetings_program(website, request): return Response(200, "Greetings, program!") website.handler = greetings_program """ self.hooks.inbound_early.run(request) gauntlet.run(request) # sets request.fs request.socket = sockets.get(request) self.hooks.inbound_late.run(request) # Look for a Socket.IO socket (http://socket.io/). if isinstance(request.socket, Response): # handshake response = request.socket request.socket = None elif request.socket is None: # non-socket request.resource = resources.get(request) response = request.resource.respond(request) else: # socket response = request.socket.respond(request) return response
def handle(self, request): """Given an Aspen request, return an Aspen response. By default we use Resource subclasses to generate responses from simplates on the filesystem. See aspen/resources/__init__.py. You can monkey-patch this method to implement single-page web apps or other things in configure-aspen.py: from aspen import Response def greetings_program(website, request): return Response(200, "Greetings, program!") website.handle = greetings_program Unusual but allowed. """ # Look for a Socket.IO socket (http://socket.io/). if isinstance(request.socket, Response): # handshake response = request.socket request.socket = None elif request.socket is None: # non-socket request.resource = resources.get(request) response = request.resource.respond(request) else: # socket response = request.socket.respond(request) response.request = request return response
def handler(self, request): """Given an Aspen request, return an Aspen response. The default handler uses Resource subclasses to generate responses from simplates on the filesystem. See aspen/resources/__init__.py. You can monkey-patch this method to implement single-page web apps or other things in configure-aspen.py: from aspen import Response def greetings_program(website, request): return Response(200, "Greetings, program!") website.handler = greetings_program """ self.hooks.inbound_early.run(request) self.check_auth(request) gauntlet.run(request) # sets request.fs request.socket = sockets.get(request) self.hooks.inbound_late.run(request) # Look for a Socket.IO socket (http://socket.io/). if isinstance(request.socket, Response): # handshake response = request.socket request.socket = None elif request.socket is None: # non-socket request.resource = resources.get(request) response = request.resource.respond(request) else: # socket response = request.socket.respond(request) return response
def handle(self, request): """Given an Aspen request, return an Aspen response. Aspen uses Resource subclasses to generate responses. See aspen/resources/__init__.py. """ try: try: self.copy_configuration_to(request) request.website = self self.hooks.run('inbound_early', request) gauntlet.run(request) # sets request.fs request.socket = sockets.get(request) self.hooks.run('inbound_late', request) # Look for a Socket.IO socket (http://socket.io/). if isinstance(request.socket, Response): # handshake response = request.socket request.socket = None elif request.socket is None: # non-socket request.resource = resources.get(request) response = request.resource.respond(request) else: # socket response = request.socket.respond(request) except: response = self.handle_error_nicely(request) except Response, response: # Grab the response object in the case where it was raised. In the # case where it was returned, response is set in a try block above. pass
def handle_error_nicely(self, tb_1, request): response = sys.exc_info()[1] if not isinstance(response, Response): # We have a true Exception; convert it to a Response object. response = Response(500, tb_1) response.request = request if 200 <= response.code < 300: # The app raised a Response(2xx). Act as if nothing # happened. This is unusual but allowed. pass else: # Delegate to any error simplate. # =============================== fs = self.ours_or_theirs(str(response.code) + '.html') if fs is None: fs = self.ours_or_theirs('error.html') if fs is not None: request.fs = fs request.original_resource = request.resource request.resource = resources.get(request) response = request.resource.respond(request, response) return response
def load_simplate(self, path, request=None, return_request_too=False): """Given an URL path, return a simplate (Resource) object. """ if request is None: request = Request(uri=path) if not hasattr(request, 'website'): request.website = self self.do_inbound(request) resource = resources.get(request) if return_request_too: return resource, request else: return resource
def load_simplate(path): """Given an URL path, return resource. """ request = StubRequest(path) request.website = test_website # XXX HACK - aspen.website should be refactored from aspen import gauntlet, sockets test_website.hooks.inbound_early.run(request) gauntlet.run(request) # sets request.fs request.socket = sockets.get(request) test_website.hooks.inbound_late.run(request) return resources.get(request)
def __init__(self, request, channel): """Takes the handshake request and the socket's channel. """ self.sid = uuid.uuid4().hex self.endpoint = request.line.uri.path.decoded self.resource = resources.get(request) self.website = request.website self.loop = request.website.network_engine.Loop(self) self.incoming = request.website.network_engine.Buffer('incoming', self) self.outgoing = request.website.network_engine.Buffer('outgoing', self) self.channel = channel self.channel.add(self) self.context = self.resource.exec_second(self, request)
def load_simplate(path): """Given an URL path, return resource. """ request = StubRequest(path) request.website = test_website # XXX HACK - aspen.website should be refactored from aspen import dispatcher, sockets test_website.hooks.run('inbound_early', request) dispatcher.dispatch(request) # sets request.fs request.socket = sockets.get(request) test_website.hooks.run('inbound_late', request) return resources.get(request)
def delegate_error_to_simplate(website, request, response): if response.code < 400: return code = str(response.code) possibles = [code + ".html", code + ".html.spt", "error.html", "error.html.spt"] fs = _first(website.ours_or_theirs(errpage) for errpage in possibles) if fs is not None: request.fs = fs request.original_resource = request.resource resource = resources.get(request) response = resource.respond(request, response) return {'response': response, 'exception': None}
def __init__(self, request, channel): """Takes the handshake request and the socket's channel. """ self.sid = uuid.uuid4().hex self.endpoint = request.path.raw self.resource = resources.get(request) request.website.copy_configuration_to(self) request.website.copy_configuration_to(channel) self.loop = request.engine.Loop(self) self.incoming = request.engine.Buffer('incoming', self) self.outgoing = request.engine.Buffer('outgoing', self) self.channel = channel self.channel.add(self) self.namespace = self.resource.exec_second(self, request)
def compile_assets(website): cleanup = [] for spt in find_files(website.www_root+'/assets/', '*.spt'): filepath = spt[:-4] # /path/to/www/assets/foo.css if not os.path.exists(filepath): cleanup.append(filepath) dispatch_result = DispatchResult(DispatchStatus.okay, spt, {}, "Found.", {}, True) state = dict(dispatch_result=dispatch_result, response=Response()) state['state'] = state content = resources.get(website, spt).respond(state).body if not isinstance(content, bytes): content = content.encode('utf8') tmpfd, tmpfpath = mkstemp(dir='.') os.write(tmpfd, content) os.close(tmpfd) os.rename(tmpfpath, filepath) atexit.register(lambda: rm_f(*cleanup))
def compile_assets(website): cleanup = [] for spt in find_files(website.www_root+'/assets/', '*.spt'): filepath = spt[:-4] # /path/to/www/assets/foo.css if not os.path.exists(filepath): cleanup.append(filepath) dispatch_result = DispatchResult(DispatchStatus.okay, spt, {}, "Found.", {}, True) state = dict(dispatch_result=dispatch_result, response=Response()) state['state'] = state content = resources.get(website.request_processor, spt).render(state).body if not isinstance(content, bytes): content = content.encode('utf8') tmpfd, tmpfpath = mkstemp(dir='.') os.write(tmpfd, content) os.close(tmpfd) os.rename(tmpfpath, filepath) if website.env.clean_assets: atexit.register(lambda: rm_f(*cleanup))
def handle_error_nicely(self, tb_1, request): response = sys.exc_info()[1] if not isinstance(response, Response): # We have a true Exception; convert it to a Response object. response = Response(500, tb_1) response.request = request if 500 <= response.code < 600: # Log tracebacks for Reponse(5xx). aspen.log_dammit(tb_1) # TODO Switch to the logging module and use something like this: # log_level = [DEBUG,INFO,WARNING,ERROR][(response.code/100)-2] # logging.log(log_level, tb_1) if 200 <= response.code < 300 or response.code == 304: # The app raised a Response(2xx) or Response(304). # Act as if nothing happened. This is unusual but allowed. pass else: # Delegate to any error simplate. # =============================== rc = str(response.code) possibles = [ rc + ".html", rc + ".html.spt", "error.html", "error.html.spt" ] fs = first( self.ours_or_theirs(errpage) for errpage in possibles ) if fs is not None: request.fs = fs request.original_resource = request.resource request.resource = resources.get(request) response = request.resource.respond(request, response) return response
def delegate_error_to_simplate(website, request, response, resource=None): if response.code < 400: return code = str(response.code) possibles = [code + ".spt", "error.spt"] fs = _first(website.ours_or_theirs(errpage) for errpage in possibles) if fs is not None: request.fs = fs request.original_resource = resource if resource is not None: # Try to return an error that matches the type of the original resource. request.headers['Accept'] = resource.media_type + ', text/plain; q=0.1' resource = resources.get(request) try: response = resource.respond(request, response) except Response as response: if response.code != 406: raise return {'response': response, 'exception': None}
def delegate_error_to_simplate(website, response, request=None, resource=None): if request is None: return # early parsing must've failed if response.code < 400: return code = str(response.code) possibles = [code + ".spt", "error.spt"] fspath = _first(website.ours_or_theirs(errpage) for errpage in possibles) if fspath is not None: request.original_resource = resource if resource is not None: # Try to return an error that matches the type of the original resource. request.headers['Accept'] = resource.media_type + ', text/plain; q=0.1' resource = resources.get(website, fspath) dispatch_result = DispatchResult(DispatchStatus.okay, fspath, {}, 'Found.', {}, True) try: response = resource.respond(request, dispatch_result, response) except Response as response: if response.code != 406: raise return {'response': response, 'exception': None}
def load_simplate(path): """Given an URL path, return resource. """ request = load_request(path) return resources.get(request)
def get_resource_for_request(request): return {"resource": resources.get(request)}
def get_simplate_context(website, fs): resource = resources.get(website, fs) return {} if isinstance(resource, StaticResource) else resource.pages[0]
def get_resource_for_request(website, request, dispatch_result): return {'resource': resources.get(website, dispatch_result.match)}
def get_simplate_context(website, fs): request = Request() request.fs = fs request.website = website resource = resources.get(request) return {} if isinstance(resource, StaticResource) else resource.pages[0]
def get_simplate_context(website, fs): resource = resources.get(website, fs) return {} if isinstance(resource, Static) else resource.pages[0]
def get_resource_for_request(request, response): if response is None: return {'resource': resources.get(request)}