Flask:重定向不起作用

时间:2017-06-10 15:01:43

标签: python url flask

以下是我的烧瓶代码

 y.Player(Double.Parse(Console.ReadLine()));

base.html文件

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 ()

add.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>

的index.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 %}

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

{% 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 %}

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

请帮忙。

谢谢。

1 个答案:

答案 0 :(得分: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)

希望这有帮助。