def __call__(self): # Check that request method type is allowed. if hasattr(self.req, "allow_methods"): self.req.allow_methods(self.allowed_methods) if self.req.method not in self.allowed_methods: raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED # Load in specified configuration file. if self.config_file: self.config = vampire.loadConfig(self.req, self.config_file) # Load the appropriate page template file. self.loadTemplate() # Call the derived class method for processing of # request and filling out of page template content. # Because "vampire.executeHandler()" is used to call # the class method, a derived class method may # define arguments which correspond to any form # parameters which may have been supplied with the # request. vampire.executeHandler(self.req, self.renderTemplate) # Deliver up the response to the request. self.__deliverResponse()
def logout(self, req): # Invalidate the active session object, thereby # effectively logging out the user. req.session.invalidate() # Redirect the client back to the login page. config = vampire.loadConfig(req, ".vampire") util.redirect(req, config.get("Access", "login_page"))
def renderTemplate(self, file=".vampire", raw=None): config = vampire.loadConfig(self.req, file) # Render PythonOptions. options = self.req.get_options() def renderOption(node, key): node.key.content = key node.value.content = options[key] keys = options.keys() keys.sort() self.template.htaccess.item.repeat(renderOption, keys) # Render config file defaults. defaults = config.defaults() def renderDefault(node, key): node.key.content = key node.value.content = defaults[key] keys = defaults.keys() keys.sort() self.template.context.name.content = file self.template.context.item.repeat(renderDefault, keys) # Render config file sections. def renderConfig(node, key, section): node.key.content = key node.value.content = config.get(section, key, raw=raw) def renderSection(node, section): node.name.content = section keys = config.options(section) keys.sort() node.item.repeat(renderConfig, keys, section) sections = config.sections() sections.sort() self.template.section.repeat(renderSection, sections)
def login(self, req, username=None, password=None): # Grab the configuration file containing information # about location of the site login and index pages. config = vampire.loadConfig(req, ".vampire") # Validate that the user has access and if they do not # redirect them back to the login page. profile = self.__database.validate(username, password) if not profile: util.redirect(req, config.get("Access", "login_page")) # Save the username in the session object. This is # the trigger for knowing that login was successful # in subsequent requests. Also cache the user profile # in the session object. req.session["username"] = username req.session["profile"] = profile # If no "next" attribute defined in session, assume # that location of this method was entered explicitly. if not req.session.has_key("next"): # Redirect the user to the site index page. req.session.save() util.redirect(req, config.get("Access", "index_page")) # Retrieve page that user was originally wanting. next = req.session.pop("next") # Redirect to the original page. req.session.save() util.redirect(req, next)
def handler_html(req, **kwargs): # Check for existance of ZPT source file. path = os.path.splitext(req.filename)[0] + ".zpt" if os.path.exists(path): layout_file = os.path.join(os.path.dirname(__file__), "_layout.zpt") layout = PageTemplate() layout.write(open(layout_file, "r").read()) config = vampire.loadConfig(req, ".vampire") settings = {} for key, value in config.items("Settings"): settings[key] = value settings["request"] = req settings["form"] = kwargs page = PageTemplate() page.write(open(path, "r").read()) settings["here"] = {"layout": layout} content = page.pt_render(extra_context=settings) req.content_type = page.content_type req.send_http_header() req.write(content) return apache.OK return apache.DECLINED
import vampire import sys config = vampire.loadConfig(__req__, ".vampire") layouts = config.get("Handlers", "layouts_root") layout = vampire.importModule("basic", layouts, __req__) class Template(layout.Template): no_cache = True def renderTemplate(self): def renderModule(node, label): node.label.content = label if hasattr(sys.modules[label], "__file__"): node.path.content = sys.modules[label].__file__ keys = sys.modules.keys() keys.sort() self.template.module.repeat(renderModule, keys) handler_html = vampire.Instance(Template)
def __call__(self, req): # Determine if the URL which is the target of the # request should be managed at all. If it is deemed # as unmanaged, then no session object is created at # all and consequently there is no requirement for a # user to be logged in either. if self._unmanagedRequest(req): return apache.OK # Load the session and store it in the request object. req.session = Session.Session(req) # Determine if the URL which is the target of the # request requires a user to be logged in. Note that # even if login is not required, a session object # has still been created and it can be queried or # updated by a request handler. if self._noLoginRequired(req): return apache.OK # Grab available configuration information. config = vampire.loadConfig(req, ".vampire") # See if the requested URL matches that of the login # page. If it is, let the request through without # any additional checks as to whether the user is # already logged in. This ensures that they can # access the login page when they haven't yet logged # in. The session object is still created however, # so that the page could check the logged in status # and thus avoid presenting the login form if they # were already logged in and instead refer them to # an alternate page. page = config.get("Access", "login_page") if not os.path.isabs(page): page = os.path.join(os.path.dirname(req.uri), page) page = os.path.normpath(os.path.join(page)) if req.uri == page: return apache.OK # If no "username" attribute contained within the # session object, means that the user has not yet # logged in. if not req.session.get("username", None): # Remember original target of request. req.session["next"] = req.uri # Redirect to the login page. req.session.save() util.redirect(req, config.get("Access", "login_page")) # Turn off caching of all pages accessed from within # the private area which required the user to login. # This ensures that browser doesn't keep hold of # them or any intermediate proxy cache. Lets hope # this doesn't trigger the Internet Exploder caching # problem with PDFs. :-( req.headers_out['Pragma'] = 'no-cache' req.headers_out['Cache-Control'] = 'no-cache' req.headers_out['Expires'] = '-1'
def handler(req, **fields): # We only want to treat request as being a possible # request for a Cheetah generated template file if # there exists both a ".tmpl" and ".py" file. target = os.path.splitext(req.filename)[0] target_tmpl = target + ".tmpl" target_py = target + ".py" if not os.path.exists(target_tmpl) and not os.path.exists(target_py): return apache.DECLINED # Grab the module name to look for from the last part # of the path. This means that pages can be spread # across subdirectories as well. directory, module_name = os.path.split(target) # Import the module. Any coding error in the module # being imported is thrown back to the user. Error # also results if by chance the target just vanished. module = vampire.importModule(module_name, directory, req) # Ensure that there is a class defined in the module # of the appropriate name. if not hasattr(module, module_name): return apache.DECLINED # Create instance of the class. tmpl = getattr(module, module_name)() # Cache any decoded form parameters in an obvious # place so they are available. Note that the actual # mod_python form object is also cached as "req.form" # but the decoded form parameters would preferably be # used. By default decoded form parameters follow # structured naming convention supported by Vampire. # If this naming convention isn't wanted, it would # need to be disabled in the Apache configuration. req.fields = fields # Cache the Vampire configuration object in an obvious # place as well. Use the same one as defined the # default handlers which would have triggered use of # this handler in the first place. options = req.get_options() file = ".vampire" if options.has_key("VampireHandlersConfig"): file = options["VampireHandlersConfig"] config = vampire.loadConfig(req, file) req.config = config # Make request object available within the template. tmpl.req = req # Set type of content being returned if not set. if not req._content_type_set: req.content_type = "text/html" # Now generate the actual content and return it. req.send_http_header() req.write(tmpl.respond()) return apache.OK
def run(self, vars={}): code, req = self.code, self.req # Check whether the code is trying to make use of # session object. If it is, first look for session # created externally and stored in the req object. # If this doesn't exist only then create a session # object. session = None if "session" in code.co_names: if not hasattr(req, "session"): req.session = Session.Session(req) session = req.session # Check whether the code is trying to make use of # the form object or the fields object. If either is # used, ensure that form object has been created and # cache the form fields. The fields object is an # addition to that which the original PSP provided # and gives access to the structured form fields # which are generated by Vampire. form = None fields = {} if "form" in code.co_names or "fields" in code.co_names: fields = vampire.processForm(req) form = req.form # Create the PSP interface object. interface = psp.PSPInterface(req, self.filename, form) # Build up the execution environment to be used. # Defaults from Vampire configuration are also # pushed into the environment so that these can be # used. If user defined settings are placed into the # "DEFAULT" section of configuration file, these # will also be available. Note that only populate # environment with just methods and classes that are # documented as being available within PSP page or # which make sense to be made available. environ = {} environ["__builtins__"] = __builtins__ environ["PSP"] = PSP environ["parse"] = psp.parse environ["parsestring"] = psp.parsestring config = vampire.loadConfig(req, ".vampire") environ.update(config.defaults()) environ["__req__"] = req if self.filename: environ["__file__"] = self.filename environ["req"] = req environ["form"] = form environ["fields"] = fields environ["psp"] = interface environ["session"] = session environ.update(self.vars) environ.update(vars) # Now execute the actual page to handle the request. try: exec code in environ req.flush() # Always ensure that session object is saved. if session is not None: session.save() except: et, ev, etb = sys.exc_info() # Use error page to display details of error if # an actual error page was supplied. if interface.error_page: interface.error_page.run({"exception": (et, ev, etb)}) else: raise et, ev, etb