jinja2 flask escaping jinja2-highlight - python

I need to render some code in a web page, with highlight. I'm using Flask and found that I could use jinja2-highlight. It works great, but I have some problems.
What I tried :
{% highlight 'python' %}
{{ item.text }}
{% endhighlight %}
Seems to work, I have my 40 lines of code but all special char like &#34 ... are displayed as this. So I add the |safe to the line {{ item.text }}. And now, all char are ok, but I don't see my full code, only 5 lines (the fifth line is complete).
I think I know what is the problem but don't know hw to solve it.
I have some line in my code like or and it seems that it's not escaped. Any idea why jinja2 does not escape <> ?
I'm not clear about security question with the |safe too. What does the server risks ?

item.text|safe should help. It appears that you're escaping the code twice. You may have some kind of auto-escape enabled.
You don't have to care about the server safety, as long as you don't share your actual code of your site.

Related

In PyCharm: "Unused local variable..." using multiple JavaScript template files

I'm using PyCharm for my Django project and In my file product_header_js.html:
<script>
{% include 'global_variables.js' %}
{% include 'update_scene_function.js' %}
...
// I may use variables in here or in update_scene_function.js
</script>
I would like to use variables in global_variables.js in my update_scene_function.js file and product_header_js.html file. PyCharm lets me do this, but gives me the error Unused local variable... in global_variables.js and all my variables are greyed out because PyCharm doesn't think they are being used. Is there anyway to fix PyCharm?
So what generated this question was me trying to modularize my JavaScript code, but it looks like I might have to just deal with the PyCharm warnings. Even when I add JavaScript as a template file type, PyCharm's JavaScript interpreter still gives me warnings (not Django template tag warnings) when I do something like this:
{% if something %}
var my_var = "a";
{% else %}
var my_var = "b";
{% endif %}
It'll say Duplicate declaration. And when I reference a variable not in the current template file or when I don't use a variable declared in the current template, PyCharm complains.
So in summary, you can do this, but PyCharm will complain and the CTRL + clicking to jump to declarations doesn't work.
One of my follow-up questions would be, if you can tolerate the PyCharm warnings, is including JavaScript files better performing than multiple external JavaScript files (). I would think including would perform better most of the time (except if most of your traffic is returning visitors where you could use external JavaScript files and leverage caching).

Flask Safe text rendering user generated block

Currently coding a bbs-style app, I'm wondering what are the best practices to display text that user entered safely. Which means I don't want them to type javascript or things like that. For now I'm rendering in a pre, and forbid the "<" and ">" chars. Though I guess it is not the right way to do it. Plus the lines are cut while it shouldn't.
Could you please give me some hints on how to that ?
More informations : I'm storing those posts in a sqlite db using flask-sqlalchemy. So I don't want them to contain SQL-Injection (which I highly doubt it is possible to do with sqlalchemy)
If you are using the Jinja2 templates as set up by Flask, all content is auto-escaped by default for HTML characters; see Jinja2 setup in the templating documentation:
Unless customized, Jinja2 is configured by Flask as follows:
autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml
a template has the ability to opt in/out autoescaping with the {% autoescape %} tag.
SQLAlchemy, used properly, indeed protects you from SQL injection attacks.
If you want newlines in user input to be translated to <br/> tags in the HTML output, you can use this Flask Snippet that adds a Jinja2 tag filter that does just that; translate newlines in an input variable into <br/> tags in the rendered output, while still escaping everything else. Multiple newlines are translated to <p> paragraph tags.
Add that snippet as a module to your project, make sure it is imported, then use the nl2br filter in your templates:
User text as paragraphs with line breaks:<br/>
{{ user_text | nl2br }}
Jinja's autoescape is turned on by default in Flask. Anything not explicitly marked safe will be escaped correctly.
http://flask.pocoo.org/docs/templating/#controlling-autoescaping
I use Bleach - http://bleach.readthedocs.org/ to strip HTML and only let through the tags I want to allow. It's really easy to use.

Issues with multiple languages in mezzanine

I am using multiple language in mezzanine and it is working fine with its own core templates.But I try to use it in my own templates then it is not working.
I have use all things in proper steps. I have locale folder in which django.po consists of all text which I can translate and there encoded django.mo file.
Buy when I choose other then English Lang. in my browser it does not translate my templates text but change the text of core templates.
I don't know why it does not translate my templates data Because if there are any kind of errors then it must not translate core templates but it does.
Please help me to sort out my problem , any suggestion would be appreciated.
Thanks.
Does your .po file contain the word "fuzzy"? If so, you might want to read the following article: http://blog.e-shell.org/124, as mentioned in this previous SO question: Django missing translation of some strings. Any idea why?
If that is not the cause of your issue, are you sure you are using the internationalisation template tags appropriately?
First of all, ensure you are loading the relevant template tags at the top of each of your templates:
{% load i18n %}
Then, for any text you want to make translatable:
{% trans "Insert your text here" %}
See also: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-template-code and https://docs.djangoproject.com/en/dev/topics/i18n/translation/#implementation-notes.

Python - Developing Web Application [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am trying to self-learn developing Web applications using Python as backend. Since I am from C++ background I find difficulty in building web pages (design / implementation) and backend code associated to it – creation of CSS, HTML code, including Images, tables etc. I read about http://webpy.org/ framework but have not yet used it. In actual I am a bit confused how to develop a great UI page using Python – something like page having multiple tabs, color scheme, drop box, list, graphs and other UI component / widgets - and ofcouse backend code associated to it.
Can anyone please let me know what path we should take so that the same can be made easy? I read about JQuery and believe that in computing world there are a lot of tools like that available but which combinations stands the best and .. easy to work with.
You can't run python in the browser. So, for web development it's used exclusively on the server side. And really it's whole purpose is to enforce your business logic and generate the markup for your site. Then the client side technologies (HTML5+Browser, Javascript and CSS) take over.
On the server-side, Django is really popular right now. It is quite robust and has a very active community behind it. I would recommend that you look at the Django tutorial. For the client side, jQuery is very popular and has a HUGE community behind it. There are many, many tutorials out there - just google "jQuery tutorial".
If you are not very good with CSS (and it sounds like you might not be), then I would personally recommend one of the grid-based CSS frameworks. They make it a lot easier to get a professional looking site. And with the responsive frameworks, then you have the added benefit of being quasi-mobile enabled. There are a bunch of them. Including one of the originals Grid 960, but again there are many. Here's a pretty good blog post on 16 of them.
As for controls/widgets, there are several to choose from. jQueryUI is very good and popular. While not as popular, Dojo is still a good option to check out. ExtJS is good, but not free. And the list goes on... YUI, etc. You will probably just want to pick one with a good community behind it and learn it.
I think this contributes to the discussion as it helped me a bit in making Python great for the web.
Metalfan, I saw you asking on the chat:
Are there any libraries which makes Python work like PHP. I mean embed
into HTML something like
You're asking about a templating library to build html, css, javascript, sql or anything else. I've searched for a tool to do that, and found Cog, Cheetah and most of what else Google throws at you. I was inspired by what I was in Django, which gives the template processing access to objects and basically the whole language, instead of only doing macro-expansion.
Web2py has a module that does just that, and I've found it very easy to modify or use stand-alone. I can't remember if I've made any modifications to the original, so I've uploaded the version I'm using, so it should work out of the box.
To generate code from a template, you include the template module, and call the render function with a template (string) and a context (dict containing local environment). Like this:
from template import render
import urllib2
environment = dict(
elements=[1, 2, 3],
username="mortn",
session_id="xyz",
lam=lambda x=0: urllib2.urlopen("http://google.com").read(),
f=f,
)
print render(content=html_template, context=environment)
The template would then look like this:
<html>
<h1>Hello {{= username }}</h1><br/>
{{ if session_id=="xyz": }}
{{ # indentation doesn't matter.. }}
this isn't printed unless if-statement matches
{{ else: }}
instead this would be shown
{{ pass # each if/for/while statements (that would
{{ # "indent your code"), must end with pass }}
{{ for e in elements: }} - {{=e}}
{{ pass }}
{{ # demo of looping }}
{{ if 1: }}
{{ for i in xrange(10): }}<br/>{{ pass }}
{{ pass }}
{{ # imported function }}
100 chars of google html get:
{{ =lam()[:100] }}
{{ # you can access the whole language with this }}
{{ =f()}}
.... and it gives THIS output:
<html>
<h1>Hello mortn</h1><br/>
this isn't printed unless if-statement matches
- 1
- 2
- 3
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
100 chars of google html get:
<!doctype html><html itemscope="itemscope"itemtype="http://schema.org/WebPage"><head><meta itemprop
you can do whatever
It messes a bit with the white spacing as you'll see, I've shortened the output down as each {{ block generates a newline. It can be edited in the template.py module as it has VERY readable code that adheres to PEP8.
TL;DR:
Here's the link for the sample code in a single file:
http://pastie.org/4776120
and the template.py module: http://pastie.org/4775988
First, check [w3schools.com][1] out,
Read on about 1)HTML, 2) CSS, 3) JavaScript 4) PHP
If you really want to build web apps fast, i'd recommend you to choose php over python, because php especially designed to build dynamic web apps.

limit Markdown in Django

I am using markdown on the comments system in my blog developed using django
I want to limit the possible format to accept just a basic one (with bold, italic, link and code)
How do I set Markdown to do this ?
if this is not possible using markdown so any alternatives ?
PS : i am using the default django app 'django.contrib.markup'
here is the actual code i am using on my template:
<div class="comment-content>
<p>
{% load markup %}
{{ comment.comment|markdown:"safe" }}
</p>
</div>
It would depend on which markdown plugin you're using there are many out there from a quick google search.
You'll have to either find documentation online for the specific one you are using, or perhaps look through the source and if it's open source modify it if you have to.
Or just find another one that allows that functionality.
edit:
Seems that django uses python-markdown(http://www.freewisdom.org/projects/python-markdown/), from a quick look it doesn't seem to support specifying only specific formatting options. However it seems to be easily extensible, so if you write an extension you can use it in django like this:
{{ string|markdown:"extension_name,extension2,etc..." }}
You could use Bleach and write a template tag to strip out the tags you don't want.
For example, to allow only bold and italic:
#register.filter
def limit_markdown(comment):
comment = bleach.clean(comment, tags=['b', 'i', 'em'], strip=True)
return comment
Then in your template, you could use it as:
{{ comment.comment|markdown|limit_markdown|safe }}

Categories

Resources