缩进错误:提交表单后返回变量时意外缩进

-1 投票
1 回答
1982 浏览
提问于 2025-04-19 00:18

我刚开始学习Flask,正在尝试一些简单的功能。我的想法是创建一个只有一个输入框的表单,然后读取这个表单的数据,把它传递给另一个函数去做其他事情。目前,我已经成功设置并运行了Flask。

当用户提交表单时,我能看到提交的值,如果我返回一些文本,比如“表单已提交”,这没问题。但这样做的时候我遇到了一个错误。

我做的事情是:当用户提交表单时,我想返回一个网站的HTML源代码,而不是返回固定的文本。为此,我使用了urllib2,并且作为示例传递了google.com的URL。但是我遇到了一个缩进错误。

这是我的代码:

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

我在这里漏掉了什么呢?请告诉我。

1 个回答

-2

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

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

撰写回答