Domanda

I'm still new with Flask and I am trying to put together a very simple site. Here is my code.

(app.py)

from __future__ import with_statement
import os
from flask import (Flask, session, redirect, url_for, abort,
               render_template, flash, request)
from werkzeug import secure_filename


app = Flask(__name__)
app.debug = True

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/image')
def image():
    return render_template('image.html')

@app.route('/video')
def video():
    return render_template('video.html')



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

In my layout.html I have links which lead to the html files above but yet when I run my app.py and click on a link, it takes me to a 404 page and I'm really unsure of why.

Here is the layout.html

<ol class="naviA">
    <li class="navi">
        <a class="navi" href="/image.html"><p>Image</p></a></li>
        <li class="navi"><a class="navi" href="/music.html"><p>Music</p></a></li>
        <li class="navi"><a class="navi" href="/video.html"><p>Video</p></a></li>
        <li class="navi"><a class="navi" href="/link.html"><p>Links</p></a></li>
        <li class="navi"><a class="navi" href="/storage.html"><p>Storage</p></a></li>
    </li>
</ol>

Any help would be great.

È stato utile?

Soluzione

You are linking to the endpoints incorrectly. Remove the .html in the links and you should be fine.

<ol class="naviA">
    <li class="navi">
        <li class="navi"><a class="navi" href="/image"><p>Image</p></a></li>
        <li class="navi"><a class="navi" href="/music"><p>Music</p></a></li>
        <li class="navi"><a class="navi" href="/video"><p>Video</p></a></li>
        <li class="navi"><a class="navi" href="/link"><p>Links</p></a></li>
        <li class="navi"><a class="navi" href="/storage"><p>Storage</p></a></li>
    </li>
</ol>

If you look at your @app.route-decorators, they define the endpoint as so:

@app.route('/image')
def image():
    return render_template('image.html')

This means that you now have a URL which ends at /image. The template surely ends with .html but your flask app does not serve such an endpoint, it loads that template and fills it with data your functions provide.

Altri suggerimenti

In addition to what @msvalkon said, you should use url_for() to generate URLs in templates, as it is cleaner, more secure and simply "the way" to do it. Here are some examples on it.

Hence, one of your links in the template might look like:

<li class="navi"><a class="navi" href="{{ url_for('image') }}"><p>Image</p></a></li>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top