【问题标题】:IndentationError: unexpected indent when returning a variable after form submissionIndentationError:表单提交后返回变量时出现意外缩进
【发布时间】:2014-10-24 12:03:07
【问题描述】:

我是 Flask 的新手,开始探索简单的功能。这个想法是有一个只有一个字段的表单并读取此表单数据并将其传递给另一个函数以执行其他操作。所以现在,我能够正确设置 Flask 并运行。

当用户提交表单时,如果我返回一些文本,例如“提交的表单”,我就能看到该值。但是当我执行此操作时出现错误。

我做了什么:当用户提交时,我应该返回网站的 HTML 源代码,而不是返回硬编码文本。为此,我使用 urllib2 作为传递 google.com URL 的示例。但我得到了一些 IndentationError。

这是我的代码:

from flask import render_template, flash, redirect
from app import app
from forms import LoginForm
import urllib2
# index view function suppressed for brevity
@app.route('/login', methods = ['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for OpenID="' + form.openid.data + '", remember_me=' + str(form.remember_me.data))
        #return "form submitted" #This is working properly
        response = urllib2.urlopen("http://www.google.com") # Here is the problem, I'm consistent in using spaces if I comment this and below line and uncomment above hard coded one, it works perfectly 
        return response


    return render_template('login.html', 
        title = 'Sign In',
        form = form)

回溯供您参考。

Traceback (most recent call last):
  File "run.py", line 2, in <module>
    from app import app
  File "C:\Python27\projects\pnr-project\app\__init__.py", line 6, in <module>
    from app import views
  File "C:\Python27\projects\pnr-project\app\views.py", line 12
    response = urllib2.urlopen("http://google.com")
    ^
IndentationError: unexpected indent

我在这里缺少什么?请告诉我。

【问题讨论】:

  • 似乎您的缩进可能会混合使用制表符和空格。
  • @NickBastin 感谢您的回复,我刚刚在我的代码中添加了一些 cmets。正如我提到的那样,我只有那条线的问题。
  • 使用您的代码编辑器功能:显示空格、将制表符转换为空格,以及 PEP8 插件。这些应该会对您有所帮助。
  • @viktor.likin 我不确定这是否是空格问题。 urllib2 在网络服务器中工作?我的意思是在本地烧瓶中。
  • 我收到了这样的问题:) 我猜你在 if 之后有缩进问题。因为提交表单时调用了一个错误。错误跟踪表明您在单词 - response 之前遇到了问题。

标签: python forms flask flask-wtforms


【解决方案1】:

终于成功了。我尝试逐行调试,下面的修改成功了!

response = urllib2.urlopen('http://google.com')
        html = response.read()
        return html

【讨论】:

  • 那是IndentationError 出类拔萃的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2018-02-04
  • 2022-08-20
  • 2011-04-24
  • 1970-01-01
相关资源
最近更新 更多