【问题标题】:Flask: Redirection not working烧瓶:重定向不起作用
【发布时间】:2017-06-10 15:01:43
【问题描述】:

下面是我的烧瓶代码

from datetime import datetime
from logging import DEBUG
from flask import Flask , render_template , url_for , request , redirect

app = Flask ( __name__ )
app.logger.setLevel ( DEBUG )

bookmarks = [ ]


def store_bookmarks (url):
 bookmarks.append ( dict (
    url=url ,
    user="rgen" ,
    date=datetime.utcnow ()

) )


@app.route ( '/' )
@app.route ( '/index' )
def index ( ):
# return "Hello World!"
 return render_template ( 'index.html' )


@app.route('/add', methods=['GET', 'POST'])
def add():
 if request.method=="POST":
    url=request.form['url']
    store_bookmarks(url)
    return redirect(url_for('index'))
return render_template('add.html')


if __name__ == '__main__':
 app.run ()

base.html

 <!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>{% block title %}{% endblock %}</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="{{ url_for('static', filename='css/normalize.min.css') }}">
        <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}" >

        <script src="../statoc/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
    </head>
    <body>
        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

        <div class="header-container">
            <header class="wrapper clearfix">
                <!-- <h1 class="title">Welcome </h1> -->
                <a href="{{ url_for('index') }}"><h1 class="title">Thermos</h1></a>
                <nav>
                    <ul>
                        <li><a href="#">Login</a></li>
                        <li><a href="#">Sign Up</a></li>
                        <li><a href="{{ url_for('add') }}">Add URL</a></li>
                    </ul>
                </nav>
            </header>
        </div>

        <div class="main-container">
            <div class="main wrapper clearfix">
              {% block content %}
                {% endblock %}

                {% block sender %}
                <aside>
                    <h3>aside</h3>
                    <p>blach blag blah</p>
                </aside>

                    {% endblock %}

            </div> <!-- #main -->
        </div> <!-- #main-container -->

        <div class="footer-container">
            <footer class="wrapper">
                <h3>A Bookmark Project by Raja Genupula</h3>
            </footer>
        </div>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="../static/js/vendor/jquery-1.11.2.min.js"><\/script>')</script>

        <script src="js/main.js"></script>
    </body>
</html>

添加.html

{% extends "base.html" %}

{% block title %}
Thermos -- Add a URL
{% endblock %}

{% block content %}
    <section>
        <h1>Add a new URL</h1>
        <form action="" method="post">
        <article>
            <p>
                Plase enter your bookmark here: <input type="text" name="url"></input>
            </p>
            <p>
                <button type="submit">Submit</button>
            </p>
        </article>
        </form>
    </section>
{% endblock %}

{% block sender %}
{% endblock %}

index.html

{% extends "base.html" %}
{% block title %}
Thermos -- Welcome
{% endblock %}
{% block content %}
                <article>
                    <header>
                        <h1>Welcome</h1>
                        <p>A Flask Project by Raja Genupula</p>
                    </header>
                    <section>
                        <h2>Title: {{ title }}</h2>
                        <p>Text: {{ text }}</p>
                    </section>
                    <section>
                        <h2>article section h2</h2>
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra.</p>
                    </section>
                </article>

{% endblock %}

我正在尝试使用“添加”功能添加 URL,一旦收到输入,我想重定向回索引页面,但单击“提交”按钮后,我收到 HTTP 400 错误消息并且调试显示语法错误或数据无效如下

HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
POST - http://127.0.0.1:5000/add

不知道我在这里缺少什么。

请帮忙。

谢谢。

【问题讨论】:

  • @Ten-Coin 你试过用return True, redirect(url_for('index'))return redirect(url_for('index'))代替吗?
  • @Nurzhan,请检查我的编辑,是的,即使我仍然面临同样的问题。顺便说一句,我正在使用 Python3。
  • @Ten-Coin 我在您当前代码中看到的唯一语法错误是 add 函数中的错误缩进。你的代码是这样写的吗?
  • @Nurzhan 代码很好,只是格式错误。
  • @Ten-Coin 那么问题可能出在store_bookmarks(url)。您没有提供足够的信息来帮助您。

标签: python url flask


【解决方案1】:

我运行了你的代码。修复代码格式后,它按预期工作。正确的缩进对于 python 来说非常重要。您的 html 模板看起来不错,至少我没有收到任何错误。但是,您的 app.py 应该如下所示:

from datetime import datetime
from logging import DEBUG
from flask import Flask, render_template, url_for, request, redirect

app = Flask(__name__)
app.logger.setLevel(DEBUG)

bookmarks = []


def store_bookmarks(url):
    bookmarks.append(dict(
        url=url,
        user="rgen",
        date=datetime.utcnow()
    ))
    print('BOOKMARKS: ', bookmarks)


@app.route('/')
@app.route('/index')
def index():
    # return "Hello World!"
    return render_template('index.html')


@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == "POST":
        url = request.form['url']
        store_bookmarks(url)
        return redirect(url_for('index'))
    return render_template('add.html')


if __name__ == '__main__':
    app.run(debug=True)

而且不像您在问题中粘贴的内容。只需删除 app.py 中的所有内容,粘贴我上面提供的代码,重新启动服务器,看看它是否正常工作。

另外我建议您在开发过程中将debug 选项设置为True,这样您就不需要在每次更改代码时都自动重新启动服务器。可能您进行了更正,但没有重新启动服务器,这就是您认为更改没有帮助的原因。要启用调试,请在我的代码中添加:

if __name__ == '__main__':
    app.run(debug=True)

希望这会有所帮助。

【讨论】:

  • 我比较了我的和你的我的主要 python 文件。但是我找不到任何差异,但是缩进可能是原因,因为您的代码非常适合我。谢谢努尔詹。
猜你喜欢
  • 2016-09-28
  • 2014-10-14
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
相关资源
最近更新 更多