【问题标题】:Python on appengine: error with eval()appengine 上的 Python:eval() 出错
【发布时间】:2011-07-18 15:03:33
【问题描述】:

我正在使用 App Engine 的网络应用程序。此请求处理程序输出带有文本字段的表单。提交时,它将获取文本并将<h1> 标签添加到以# 开头的行。我使用repr() 能够将文本拆分为行列表,并使用eval() 分析每一行中的文本,而repr() 的字符串开头没有u'

class Test(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<form method=\'post\' action=\'\'>')
        self.response.out.write('<textarea name=\'text\'></textarea>')
        self.response.out.write('<input type=\'submit\' value=\'Submit\'/>')
        self.response.out.write('</form>')
    def post(self):
        output = []
        for line in repr(self.request.get('text')).split('\\n'):
            if eval(line)[0] == '#':
                output.append('<h1>'+line+'</h1>')
            else:
                output.append(line)
        self.response.out.write('\\n'.join(output))

代码现在的样子,它给了我这个错误:

File "<string>", line 1
    u'#somestring\r
                  ^
SyntaxError: EOL while scanning string literal

如果我只使用line[0] 而不是eval(line)[0],则一切正常,只是它不适用于第一行。即使第一行以# 开头,条件也将用于else,因为第一个字符将是u' 而不是#。尝试使用eval() 解决这个问题给了我这个错误。我该如何解决这个问题?

【问题讨论】:

  • 如果我没看错的话,您在从网络表单接收的输入中使用eval()?这是一个等待发生的安全问题。 eval 实际上将字符串作为 Python 代码执行。
  • 是的,现在我意识到这是个坏主意。我只是不知道splitlines(),所以这是我能想到的唯一方法。

标签: google-app-engine web-applications eval repr


【解决方案1】:

为了分割文本,字符串有一个内置的splitlines 方法:

for line in self.request.get('text').splitlines():
    ... do whatever ...

然后查看特定行是否以# 开头,试试这个:

if line.strip()[0]=='#':
    ... do whatever ...

放在一起:

for line in self.request.get('text').splitlines():
    if line.strip()[0] == '#':
        ... do whatever ...

【讨论】:

  • 没问题,很高兴我能帮上忙 :)
猜你喜欢
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2013-10-28
相关资源
最近更新 更多