Ten-Coin Ten-Coin -4 years ago 123
Python Question

Flask: Redirection not working

Below is my flask code

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>


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


I am trying to add a URL with 'add' function and once input received , I want to redirect back to Index page but after clicking 'submit' button I am getting HTTP 400 error message and debugging shows Bad syntax or invalid data as below

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


Dont know what I am missing here.

Please help.

Thank you.

Answer Source

I ran your code. After fixing the code formatting it works as expected. Proper indentation is very important for python. Your html templates look fine at least I did not get any errors with them. However, you app.py should look like this:

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)

And not like what you pasted in the question. Just delete everything in your app.py, paste the code I provided above, restart the server and see if it is working.

Also I would recommend you to set the debug option to True during development so that you don't need to restart the server automatically each time you change your code. Probably, you made corrections, but did not restart the server and this is why you thought the changes did not help. To enable debug add this as in my code:

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

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download