def render(template_name, extra_vars=None, form_fill=None, form_errors={}, method='xhtml'): # Pull in extra vars if needed globs = extra_vars or {} # Second, get the globals globs.update(pylons_globals()) globs['g'] = app_globals globs['can'] = can globs['_form_errors'] = form_errors # Grab a template reference template = globs['app_globals'].genshi_loader.load(template_name) stream = template.generate(**globs) if form_fill is not None: filler = HTMLFormFiller(data=form_fill) stream = stream | filler return literal(stream.render(method=method, encoding=None))
def render(template_name, extra_vars=None, form_fill=None, form_errors={}, cache_expire=3600, cache_private=False, method='xhtml'): _setup_cache(cache_expire, cache_private) # Pull in extra vars if needed globs = extra_vars or {} # Second, get the globals globs.update(pylons_globals()) globs['g'] = app_globals globs['can'] = can globs['_form_errors'] = form_errors # Grab a template reference template = globs['app_globals'].genshi_loader.load(template_name) stream = template.generate(**globs) if form_fill is not None: filler = HTMLFormFiller(data=form_fill) stream = stream | filler for item in PluginImplementations(IGenshiStreamFilter): stream = item.filter(stream) return literal(stream.render(method=method, encoding=None))
def comment(self, id, cancel=False, **data): link = self.data.get(id) if not link: raise cherrypy.NotFound() if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/info/%s' % link.id) form = CommentForm() try: data = form.to_python(data) markup = HTML(data['content']) | HTMLSanitizer() data['content'] = markup.render('xhtml') comment = link.add_comment(**data) if not ajax.is_xhr(): raise cherrypy.HTTPRedirect('/info/%s' % link.id) return template.render('_comment.html', comment=comment, num=len(link.comments)) except Invalid as e: errors = e.unpack_errors() else: errors = {} if ajax.is_xhr(): stream = template.render('_form.html', link=link, errors=errors) else: stream = template.render(link=link, comment=None, errors=errors) return stream | HTMLFormFiller(data=data)
def config(self, **form_data): f = open('config.pkl', 'r') vboxweb_config = pickle.load(f) f.close() if cherrypy.request.method.upper() == 'POST': if form_data['password']: if form_data['password'] != form_data['password_confirm']: error_message = "Passwords don't match" tmpl = loader.load('error.html') return tmpl.generate(error_message=error_message).render( 'html', doctype='html') vboxweb_config['password'] = form_data['password'] vboxweb_config['username'] = form_data['username'] vboxweb_config['port'] = int(form_data['port']) f = open('config.pkl', 'w') pickle.dump(vboxweb_config, f, 1) f.close() raise cherrypy.HTTPRedirect('/') else: form_data = { 'username': vboxweb_config['username'], 'port': vboxweb_config['port'], } tmpl = loader.load('config.html') filler = HTMLFormFiller(data=form_data) return tmpl.generate().filter(filler).render('html', doctype='html')
def new(self, **data): if cherrypy.request.method == "POST": return self.submit_new(data) collector = cherrypy.session["collector"] return template.render(errors={}, \ collector_uuid=collector.uuid) | \ HTMLFormFiller(data=collector.__dict__)
def new(self, **data): if cherrypy.request.method == "POST": return self.submit_new(data) edit_user = User() edit_user.enabled = True cherrypy.session["edit_user"] = edit_user return template.render(errors={}) | \ HTMLFormFiller(data=edit_user.__dict__)
def login(self, **data): errors = {} if cherrypy.request.method == "POST": errors = self.submit_login(data) # if we're here, it means something has gone wrong. Render the prompt # page return template.render(url=cherrypy.url, errors=errors) | \ HTMLFormFiller(data=data)
def submit(self, cancel=False, **data): if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/') form = LinkForm() try: data = form.to_python(data) link = Link(**data) self.data[link.id] = link raise cherrypy.HTTPRedirect('/') except Invalid as e: errors = e.unpack_errors() else: errors = {} return template.render(errors=errors) | HTMLFormFiller(data=data)
def new(self, **data): if cherrypy.request.method == "POST": return self.submit_new(data) session = self.Session() try: user = cherrypy.session["user"] search = Search() cherrypy.session["search"] = search data = search.__dict__ return template.render(errors={}, query_types=self.s_query_types, \ search_type=-1) | HTMLFormFiller(data=data) finally: session.close()
def edit(self, sr_id): sr_id = int(sr_id) session = self.Session() try: user = cherrypy.session["user"] session.add(user) # note that we add in the customer id to verify the user is allowed # to edit the object sr = session.query(ServiceRequest)\ .filter(ServiceRequest.id==sr_id)\ .filter(ServiceRequest.customer_id==user.customer_id).one() cherrypy.session["sr"] = sr return template.render(errors={}) | HTMLFormFiller( data=sr.__dict__) finally: session.close()
def edit(self, user_id): user_id = int(user_id) session = self.Session() try: user = cherrypy.session["user"] session.add(user) # note that we add in the customer id to verify the user is allowed # to edit the object edit_user = session.query(User)\ .filter(User.id==user_id)\ .filter(User.customer_id==user.customer_id).one() edit_user.orig_password = edit_user.password edit_user.password = "" cherrypy.session["edit_user"] = edit_user return template.render(errors={}) | \ HTMLFormFiller(data=edit_user.__dict__) finally: session.close()
def edit(self, search_id): search_id = int(search_id) session = self.Session() try: user = cherrypy.session["user"] session.add(user) # note that we add in the customer id to verify the user is allowed # to edit the object search = session.query(Search)\ .filter(Search.id==search_id)\ .filter(Search.customer_id==user.customer_id).one() # collectors = session.query(Collector)\ # .filter(Collector.customer_id==user.customer_id) cherrypy.session["search"] = search return template.render(errors={}, query_types=self.QUERY_TYPES) | \ HTMLFormFiller(data=search.__dict__) finally: session.close()
session.commit() raise cherrypy.HTTPRedirect("/user/list") except Invalid, ex: errors = ex.error_dict except PasswordException: pass finally: session.close() # edit_user.orig_password = edit_user.password # edit_user.password = "" return template.render(errors=errors) | HTMLFormFiller(data=form_data) @cherrypy.expose @template.output("new_user.html") def edit(self, user_id): user_id = int(user_id) session = self.Session() try: user = cherrypy.session["user"] session.add(user) # note that we add in the customer id to verify the user is allowed # to edit the object edit_user = session.query(User)\ .filter(User.id==user_id)\
# see if a format has been specified yet. If so, include it in the # response if "format" in data and len(data["format"]) != 0: format_form_path = self.get_format_form_path(data["format"]) else: format_form_path = None if "log_source_type" in data: log_source_type_name = data["log_source_type"] type_form_path = self.get_type_form_path(log_source_type_name) return template.render(errors=errors, collectors=collectors, \ log_source_types=log_source_types, \ formats=self.FORMATS.values(), \ type_form_path=type_form_path, \ format_form_path=format_form_path) | HTMLFormFiller(data=data) @cherrypy.expose def delete(self, log_source_id): session = self.Session() try: log_source = session.query(LogSource)\ .filter(LogSource.id==log_source_id).one() #ensure that they own the log source user = cherrypy.session["user"] if log_source.customer_id != user.customer_id: raise Exception("Security exception") session.delete(log_source)
def index (self, **kwargs): def entries(results, offset): """ results is a list of book ids, sorted by first Author, the query lazily returns book objects """ query = session.query(Book).join( Book.authors.and_(BookAuthor.heading == 1)).join(BookAuthor.author).filter( Book.pk.in_(results)).order_by(Author.name).offset(offset).limit(PAGESIZE) for book in query: yield book os = AdvSearcher() params = cherrypy.request.params.copy() try: pageno = abs(int(params.pop("pageno", 1))) except KeyError: pageno = 1 os.pageno = pageno for key in ["submit_search", "route_name", "controller", "action"]: params.pop(key, None) terms = [key for key in params if params[key]] # Return a search result page. # no terms provided if len(terms) == 0: os.total_results = 0 os.finalize() return self.formatter.render('advresults', os) # single term, redirect if browsable if len(terms) == 1: browse_key = BROWSE_KEYS.get(terms[0], None) if browse_key: raise cherrypy.HTTPRedirect( "/browse/%s/%s" % (browse_key, params[terms[0]].lower())) # multiple terms, create a query session = cherrypy.engine.pool.Session() query = session.query(Book.pk) selections = [] resultpks = None searchterms = [] for key in terms: if key in ['author', 'title', 'subject']: for word in params[key].split(): searchterms.append((key, word)) else: searchterms.append((key, params[key])) for key, val in searchterms: if key == 'filetype': pks = query.join(File).filter(File.fk_filetypes == val).all() key = 'Filetype' elif key == 'lang': pks = query.join(Book.langs).filter(Lang.id == val).all() val = langname(val) key = 'Language' elif key == 'locc': pks = query.join(Book.loccs).filter(Locc.id == val).all() val = val.upper() key = 'LoC Class' elif key == 'category': try: val = int(val) except ValueError: continue pks = query.join(Book.categories).filter(Category.pk == val).all() val = catname(val) key = 'Category' elif key == 'author': word = "%{}%".format(val) subq = select(Author.id).join(Author.aliases).filter( Alias.alias.ilike(word)) pks = query.join(Book.authors).join(BookAuthor.author).filter(or_( Author.name.ilike(word), Author.id.in_(subq), )).all() key = 'Author' elif key == 'title': word = "%{}%".format(val) pks = query.join(Book.attributes).filter(and_( Attribute.fk_attriblist.in_([240, 245, 246, 505]), Attribute.text.ilike(word), )).all() key = 'Title' elif key == 'subject': word = "%{}%".format(val) pks = query.join(Book.subjects).filter( Subject.subject.ilike(word), ).all() key = 'Subject' pks = {row[0] for row in pks} resultpks = resultpks.intersection(pks) if resultpks is not None else pks num_rows = len(pks) selections.append((key, val, num_rows)) os.total_results = len(resultpks) os.finalize() offset = PAGESIZE * (pageno - 1) os.start_index = offset + 1 if os.total_results > MAX_RESULTS: os.entries = [] else: os.entries = entries(resultpks, offset) os.search_terms = selections instance_filter = HTMLFormFiller(data=params) rendered = self.formatter.render('advresults', os, instance_filter) session.close() return rendered
vm = self.vbox.getMachine(uuid) form_data = { 'name': vm.name, 'description': vm.description, 'memory': vm.memorySize, 'vram': vm.VRAMSize, 'hwvirtex': False, 'nestedpaging': vm.HWVirtExNestedPagingEnabled, 'pae': vm.PAEEnabled, '3daccel': vm.accelerate3DEnabled, 'acpi': vm.BIOSSettings.ACPIEnabled, 'ioapic': vm.BIOSSettings.IOAPICEnabled } if vm.HWVirtExEnabled == 1: form_data['hwvirtex'] = True filler = HTMLFormFiller(data=form_data) tmpl = loader.load('vm/modify.html') return tmpl.generate(vm=vm).filter(filler).render('html', doctype='html') @cherrypy.expose def create(self, **form_data): if cherrypy.request.method.upper() == 'POST': #TODO Some form validation might be nice, eh? new_vm = self.vbox.createMachine( form_data['name'], form_data['guest_os'], '', '00000000-0000-0000-0000-000000000000') new_vm.description = form_data['description'] new_vm.memorySize = form_data['memory'] new_vm.VRAMSize = form_data['vram'] new_vm.saveSettings()
def index(self, **params): if cherrypy.request.method != 'POST': return view.render() name = params['name'].strip() if name == "": return view.render(error='No map name given!') | HTMLFormFiller( data=params) desc = JobDescription() desc.name = name desc.mail = params['mail'] desc.resolution = 3.0 if params.has_key('highres') else 9.0 desc.compressed = True if params.has_key('compressed') else False desc.welt2000 = True if params.has_key('welt2000') else False desc.level_of_detail = int(params['level_of_detail']) selection = params['selection'] waypoint_file = params['waypoint_file'] if selection == 'waypoint' or selection == 'waypoint_bounds': if not waypoint_file.file or not waypoint_file.filename: return view.render( error='No waypoint file uploaded.') | HTMLFormFiller( data=params) try: filename = waypoint_file.filename.lower() if filename.endswith('.dat') or filename.endswith('.cup'): desc.bounds = parse_waypoint_file( waypoint_file.filename, waypoint_file.file).get_bounds() desc.waypoint_file = 'waypoints.cup' if filename.endswith( '.cup') else 'waypoints.dat' else: raise RuntimeError( 'Waypoint file {} has an unsupported format.'.format( waypoint_file.filename)) except: return view.render(error='Unsupported waypoint file ' + waypoint_file.filename) | HTMLFormFiller( data=params) if selection == 'bounds' or selection == 'waypoint_bounds': try: desc.bounds = GeoRect(float(params['left']), float(params['right']), float(params['top']), float(params['bottom'])) except: return view.render( error='Map bounds not set.') | HTMLFormFiller(data=params) if desc.bounds.height() <= 0 or desc.bounds.width() <= 0: return view.render(error='Bounds are invalid.') | HTMLFormFiller( data=params) if desc.bounds.height() * desc.bounds.width() > 1000: return view.render( error='Selected area is too large.') | HTMLFormFiller( data=params) if self.too_many_requests(): return view.render( error='You can generate only three maps per hour.' ) | HTMLFormFiller(data=params) job = Job(self.__dir_jobs, desc) if desc.waypoint_file: waypoint_file.file.seek(0) f = open(job.file_path(desc.waypoint_file), 'w') try: shutil.copyfileobj(fsrc=waypoint_file.file, fdst=f, length=1024 * 64) finally: f.close() desc.download_url = cherrypy.url('/download?uuid=' + job.uuid) job.enqueue() raise cherrypy.HTTPRedirect(cherrypy.url('/status?uuid=' + job.uuid))
def submit(self, cancel=False, **data): if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/') form = LinkForm() try: data = form.to_python(data) link = Link(**data) self.data[link.id] = link raise cherrypy.HTTPRedirect('/') except Invalid, e: errors = e.unpack_errors() else: errors = {} return template.render(errors=errors) | HTMLFormFiller(data=data) @cherrypy.expose @template.output('info.html') def info(self, id): link = self.data.get(id) if not link: raise cherrypy.NotFound() return template.render(link=link) @cherrypy.expose @template.output('comment.html') def comment(self, id, cancel=False, **data): link = self.data.get(id) if not link: raise cherrypy.NotFound()