def __render(self, template, context, debug=False): """ render the template string with the given context and returned it. -debug the context, if debug is on. """ html = render_string_template(template, context) if debug: self.response.write("<fieldset><legend>template debug:</legend>") self.response.write("<legend>context:</legend>") self.response.write("<pre>") self.response.write(escape(pprint.pformat(context))) self.response.write("</pre>") self.response.write("<legend>template:</legend>") self.response.write("<pre>") self.response.write(escape(template)) self.response.write("</pre>") if debug>1: self.response.write("<legend>result html code:</legend>") self.response.write("<pre>") self.response.write(escape(html)) self.response.write("</pre>") self.response.write("</fieldset>") return html
def handle_command(request, page_id, module_name, method_name, url_args): """ handle a _command request """ current_page_obj = _get_page(request, page_id) context = _get_context(request, current_page_obj) local_response = SimpleStringIO() if url_args == "": url_args = () else: url_args = (url_args,) try: output = plugin_manager.handle_command( context, local_response, module_name, method_name, url_args ) except AccessDenied: if request.debug: # don't use errorhandling -> raise the prior error raise page_content = "[Permission Denied!]" else: if output == None: # Plugin/Module has retuned the locale StringIO response object page_content = local_response.getvalue() elif isinstance(output, basestring): page_content = output elif isinstance(output, HttpResponse): # e.g. send a file directly back to the client return output else: msg = ( "Error: Wrong output from Plugin!" " - It should be write into the response object" " or return a String/HttpResponse object!" " - But %s.%s has returned: %s (%s)" ) % ( module_name, method_name, escape(repr(output)), escape(str(type(output))) ) raise AssertionError(msg) # print module_name, method_name # print page_content # print "---" if page_content: # Add the CSS Info, but only if the plugin has returned content and # not when the normal cms page rendered. page_content = add_css_tag( context, page_content, module_name, method_name ) return _render_cms_page(request, context, page_content)
def _delete_page(self, id): """ Delete one page with the given >id<. Error, if... ...this is the default page. ...this page has sub pages. """ skip_data = self.get_delete_skip_data() # The skip_data contains the default- and the current page. if id in skip_data: msg = _( "Can't delete the page with ID:%(id)s," " because %(reason)s!" ) % {"id":id, "reason":skip_data[id]} raise DeletePageError(msg) # Check if the page has subpages sub_pages_count = Page.objects.filter(parent=id).count() if sub_pages_count != 0: msg = _( "Can't delete the page with ID:%s," " because it has %s sub pages!" ) % (id, sub_pages_count) raise DeletePageError(msg) # Delete the page: try: page = Page.objects.get(id=id) page.delete() except Exception, msg: msg = _("Can't delete the page with ID:%s: %s") % ( id, escape(str(msg)) ) raise DeletePageError(msg)
def escape_area(self, block): if self.escape_area_first_line == True: block = block.strip() self.escape_area_first_line = False block = block.splitlines() block = "".join(["%s<br />\n" % escape(line) for line in block]) self.out.write(block)
def encode_and_prepare(self, txt): """ Pass "safe" strings, all other would be escaped. """ if isinstance(txt, SafeData): return txt if not isinstance(txt, unicode): txt = force_unicode(txt) return escape(txt)
def settings_info(self): """ display current used 'settings.py' """ context = [] safe_settings = get_safe_settings() for key, value in safe_settings.iteritems(): value = pprint.pformat(value) value = escape(value) context.append({"attrname": key, "value": value}) context.sort() return context
def _process_delete_pages(self): """ process a sended "delete pages" dialog. """ if self.request.method != 'POST': # No form sended via POST return # create a list of the sended page IDs: id_list = self.request.POST.getlist("pages") try: # Convert the string list to a interger list id_list = [int(i) for i in id_list] except ValueError, msg: self.page_msg.red(_("Wrong data: %s") % escape(str(msg))) return
def download(self, filename): """ Generate the XML file and send it to the client. Info: the method ignored the filename """ content = self._get_feed() if debug: self.response.write("<h2>Debug:</h2><pre>") self.response.write(escape(content)) self.response.write("</pre>") return # send the XML file to the client response = HttpResponse() response['Content-Type'] = 'application/xml; charset=utf-8' response.write(content) return response
def pygmentize(sourcecode, source_type): """ returned html-code and the lexer_name """ if not PYGMENTS_AVAILABLE: lexer_name = escape(source_type) html = no_hightlight(sourcecode) return html, lexer_name ext = source_type.lower().lstrip(".").strip("'\"") try: if ext == "": lexer = lexers.guess_lexer(sourcecode) else: lexer = lexers.get_lexer_by_name(ext) except lexers.ClassNotFound, err: info = _("unknown type") lexer_name = u'<small title="%s">%s</small>' % (err, info) html = no_hightlight(sourcecode) return html, lexer_name
def _debug(self, url, feed): from pprint import pformat self.response.write("<h2>RSS debug for '%s':</h2>\n" % url) self.response.write("<pre>\n") self.response.write(escape(pformat(feed))) self.response.write("</pre>\n")
def no_hightlight(code): html = u'\n<pre><code>%s</code></pre>\n' % escape(code) return html
title = "%s - %s" % (self.preferences["blog_title"], title) # Get the items limit = self._get_max_count() items = entries.filter(is_public=True).all()[:limit] feed = self._get_feed(FeedGenerator, items, title, feed_name) feed_content = feed.writeString('utf8') content_type = "%s; charset=utf-8" % feed.mime_type if FEED_DEBUG: self.response.write("<h2>Debug:</h2>") self.response.write("content type: %s" % content_type) self.response.write("<pre>") self.response.write(escape(feed_content)) self.response.write("</pre>") return # send the feed as a file to the client response = HttpResponse(content_type=content_type) response.write(feed_content) return response def _get_feed(self, FeedGenerator, items, title, feed_name): """ returns the generated feed. """ feed = FeedGenerator( title = title,
def do(self, find_string, replace_string, type, simulate): """ Do the find/replace action. Returns a result list with diff information. """ def nothing_found(): # We used this two times self.page_msg( "No %s contains the string '%s'" % (type, find_string) ) return None, None if type == "pages": model_object = Page elif type == "templates": model_object = Template elif type == "stylesheets": model_object = Style else: self.page_msg.red("Wrong type!") return None, None items = model_object.objects.all().filter( content__contains=find_string ) if len(items) == 0: return nothing_found() total_changes = 0 results = [] changed_items = [] for item in items: old_content = item.content changes = old_content.count(find_string) if changes == 0: # SQlite work-a-round for the continue total_changes += changes new_content = old_content.replace(find_string, replace_string) if not simulate: # Save the find/replace result item.content = new_content item.save() changed_items.append(item.name) diff = diff_lines(old_content, new_content) diff = escape(diff) diff = mark_safe(diff) results.append({ "item": item, "changes": changes, "diff": diff, }) if total_changes == 0: # SQLite work-a-round return nothing_found() if not simulate: self.page_msg.green("Changed %s:" % type) self.page_msg.green(", ".join(changed_items)) return results, total_changes
def escaping(self, matchobj): return escape(matchobj.group(1))
def debug_response(response, one_browser_traceback=True, msg="", \ display_tb=True): """ Display the response content with a error reaceback in a webbrowser. TODO: We should delete the temp files after viewing! """ if one_browser_traceback: # Only one traceback should be opend in the browser. global ONE_DEBUG_DISPLAYED if ONE_DEBUG_DISPLAYED: # One browser instance started in the past, skip this error return else: # Save for the next traceback ONE_DEBUG_DISPLAYED = True content = response.content url = response.request["PATH_INFO"] stack = traceback.format_stack(limit=3)[:-1] stack.append(escape(msg)) if display_tb: print print "debug_response:" print "-"*80 print "\n".join(stack) print "-"*80 stack_info = "".join(stack) response_info = "<dl>\n" for attr in RESPONSE_INFO_ATTR: # FIXME: There must be exist a easier way to display the info response_info += "\t<dt>%s</dt>\n" % attr value = getattr(response, attr, "---") value = pformat(value) value = escape(value) response_info += "\t<dd><pre>%s</pre></dd>\n" % value response_info += "</dl>\n" if "</body>" in content: info = ( "\n<br /><hr />\n" "<h3>Unittest info</h3>\n" "<dl>\n" "<dt>url:</dt><dd>%s</dd>\n" "<dt>traceback:</dt><dd><pre>%s</pre></dd>\n" "<dt>response info:</dt>%s\n" "</dl>\n" "</body>" ) % (url, stack_info, response_info) content = content.replace("</body>", info) else: # Not a html page? content += "\n<pre>\n" content += "-" * 79 content += ( "\nUnittest info\n" "=============\n" "url: %s\n" "traceback:\n%s\n</pre>" "response info:\n%s\n" ) % (url, stack_info, response_info) fd, file_path = tempfile.mkstemp(prefix="PyLucid_unittest_", suffix=".html") os.write(fd, content) os.close(fd) url = "file://%s" % file_path print "\nDEBUG html page in Browser! (url: %s)" % url try: webbrowser.open(url) except: pass