【问题标题】:How to avoid escaping html characters in bottle python web framework?如何避免在bottle python web框架中转义html字符?
【发布时间】:2013-06-19 09:17:51
【问题描述】:

问题

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

背景

我正在Bottle(python)中制作歌词webapp,并且在将其插入数据库之前测试所有数据是否正确,所以,现在,我基本上有一个带有“歌曲名称”的表单,“艺术家”,“歌词”(在文本区域中),仅此而已。

当表单提交时,它会加载一个包含上述三个输入值(歌曲、艺术家和歌词)的页面,一切都按预期工作,但歌词的 html 被转义(在将歌词发送到模板之前,我替换了所有\n 和 <br>)。

所以我从this tutorial from bottlepy.org 进行了研究,发现 Bottle 转义了 html 标签以防止 XSS 攻击,您可以通过添加“!”来禁用它。在变量名之前,太棒了!我找到了解决方案,但是......当我尝试使用它时,它抛出了一个错误:

错误 - Screenshot of Error on computer

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

index.py - gist on github

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)

HTML 模板 - gist on github

<h1>Letra de {{ letra['titulo'] }}</h1>
<h2>Por: {{ letra['artista'] }}</h2>
<div>Fecha: {{ letra['Fecha_envio'] }}</div>
<div>Letra: {{ !letra['letra'] }}</div>

如果我让 Bottle 转义我的歌词 html,它的工作原理/外观如下(注意 &lt;br&gt; 是如何显示为纯文本的):

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

最后,这就是它应该看起来的样子

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

【问题讨论】:

  • 请将您的代码发布在此处,而不是在外部网站上。我们希望问题对现在和将来的每个人都有用。
  • 您的错误信息是文字,请也复制粘贴到这里。
  • 一般来说,你在模板中做换行到换行的转换;尽可能晚。
  • 我试过了,但只有整个代码的第一行被检测为代码,所以我不得不缩进代码的每一行以使其正确显示:/这就是我决定使用的原因我的代码的外部站点。
  • 我们可以帮你格式化;请参阅How do I format my code blocks? 以获得更详细的帮助。帖子编辑器有一个用于缩进代码的特殊按钮,选择文本并单击{} 图标。

标签: python bottle


【解决方案1】:

你需要在{{开头的{{后面加上感叹号让瓶子识别它:

<div>Letra: {{! letra['letra'] }}</div>

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

<div>Letra: {{!letra['letra']}}</div>

【讨论】:

  • 哇,你真快。我自己也得出了这个结论,但我刚刚完成了对 bottle.py 代码的研究以证明这一点。
  • 哇,我不敢相信它这么容易!有时我们花了很多时间过度思考问题,结果它们变得非常愚蠢:P,这就是问题所在,我删除了所有空格,现在它按预期工作了,谢谢你为我节省了更多的思考时间,我现在可以愉快地睡觉了,已经快凌晨5点了。再次感谢!!!顺便说一句,我现在对 XSS 攻击持开放态度,但我将制作一个自定义转义函数以仅允许字母数字,!,。和
    标签,其余的将被删除!
猜你喜欢
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多