如何避免在瓶子python Web框架中转义html字符?

kus*_*rtr 8 python bottle

如何在Bottle-Python Web Framework中防止转义字符?

背景

我正在用瓶子(python)制作歌词webapp,我在将它插入数据库之前测试所有数据是正确的,所以,现在,我基本上有一个有"歌名","艺术家"的表格","歌词"(在textarea中)就是这样.

当表单提交它加载包含上述三种输入值(歌曲,歌手及歌词)的网页,一切工作正常,但歌词HTML被转义(发送歌词到模板之前,我全部换成了\n<br>) .

所以我做了我的研究,并从bottlepy.org的本教程中 发现,瓶子逃脱了html标签以防止XSS攻击,你可以通过设置"!"来禁用它.在变量名之前,太棒了!我找到了解决方案,但是......当我尝试使用它时,它抛出了一个错误:

错误 - 计算机上的错误的屏幕截图

Exception:

SyntaxError('invalid syntax', ('H:\\Server\\htdocs\\letras\\prueba.tpl', 4, 27, "u'<div>Letra: ', _escape( !letra['letra'] ), u'</div>'])\n"))

Traceback (most recent call last):
    File "H:\Server\htdocs\letras\bottle.py", line 764, in _handle
      return route.call(**args)
    File "H:\Server\htdocs\letras\bottle.py", line 1575, in wrapper
      rv = callback(*a, **ka)
    File "index.py", line 41, in guardar_letra
      return template('prueba.tpl', letra = data)
    File "H:\Server\htdocs\letras\bottle.py", line 3117, in template
      return TEMPLATES[tplid].render(kwargs)
    File "H:\Server\htdocs\letras\bottle.py", line 3090, in render
      self.execute(stdout, kwargs)
    File "H:\Server\htdocs\letras\bottle.py", line 3078, in execute
      eval(self.co, env)
    File "H:\Server\htdocs\letras\bottle.py", line 185, in __get__
      value = obj.__dict__[self.func.__name__] = self.func(obj)
    File "H:\Server\htdocs\letras\bottle.py", line 2977, in co
      return compile(self.code, self.filename or '<string>', 'exec')
    File "H:\Server\htdocs\letras\prueba.tpl", line 4
      u'<div>Letra: ', _escape( !letra['letra'] ), u'</div>'])
                                ^
  SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

index.py - github上的 gist

from bottle import Bottle, route, run, template, static_file, get, post, request, response
from passlib.hash import sha256_crypt
import MySQLdb as mdb
import time
import re

@get('/enviar')
def enviar_letra():
    return template('enviar_letra.tpl')

@post('/enviar')
def guardar_letra():
    titulo = request.forms.get('titulo').capitalize() # Gets the song title from the form
    artista = request.forms.get('artista') # Gets the artist
    letra = request.forms.get('letra') # Gets the lyrics
    fecha_envio = time.strftime('%Y-%m-%d %H:%M:%S') # Date the lyrics were sent
    titulo = re.sub('[^\w|!|\s|\.|,]', '', titulo) # I delete every character except: words, exclamation, spaces, dots, commas
    url = titulo + "-" + artista # concatenate the song's title and the artist name to make a nice url
    url = re.sub('\W+|_', '-', url).lower() # lower all the characters from the url
    url = url.strip("-") # strips "-" at the beginning and the end
    letra = letra.replace("\n", "<br>") # replaces \n from the lyrics text area with <br>
    data = { "titulo": titulo, "artista": artista, "letra": letra, "url": url, "Fecha_envio": fecha_envio } # song dictionary
    return template('prueba.tpl', letra = data) # loads prueba.tpl template and send "data" dictionary as "letra" (letra is lyric in spanish)

run(host='localhost', port=8080, debug=True)
Run Code Online (Sandbox Code Playgroud)

HTML模板 - github上的要点

<h1>Letra de {{ letra['titulo'] }}</h1>
<h2>Por: {{ letra['artista'] }}</h2>
<div>Fecha: {{ letra['Fecha_envio'] }}</div>
<div>Letra: {{ !letra['letra'] }}</div>
Run Code Online (Sandbox Code Playgroud)

如果我让Bottle转义我的歌词html(请注意如何<br>显示为纯文本),这是它的工作原理/外观:

http://i.stack.imgur.com/fxz7o.png

最后,这就是ITS支持的样子

http://i.stack.imgur.com/6b58J.png

Mar*_*ers 12

你需要在瓶子开口放置感叹号{{才能识别它:

<div>Letra: {{! letra['letra'] }}</div>
Run Code Online (Sandbox Code Playgroud)

为了安全起见,您最好省略那里的空格:

<div>Letra: {{!letra['letra']}}</div>
Run Code Online (Sandbox Code Playgroud)