Blake G
Blake G

Reputation: 581

Trouble Routing in Flask

I have a static HTML file (But one in which I want to add dynamic template variables to once I get it working.)

My html file is in the templates directory.

My Flask code looks like this:

@restServer.route('/mypage/', methods=['GET'])
def func(self):
    return render_template('mypage.html')

I then try opening the page in a browser by going to

localhost:5000/mypage

And I get an HTTP 500 Error. Can someone please provide some insight? Thanks.

Upvotes: 0

Views: 120

Answers (2)

Blake G
Blake G

Reputation: 581

I was really getting an HTTP 500 Error. The reason for the error was accepting self as a parameter to the function. Once I removed the reference to self and changed the code to

def func():
     return render_template('mypage.html')

Everything worked as it should.

Upvotes: 0

Sean Vieira
Sean Vieira

Reputation: 160043

Flask provides automatic redirection from the non-slash route to the slash route by default to ensure that there is only one canonical URL for a resource. Quoting the docs:

Take these two rules; @app.route("/projects/") and @app.route("/about")

Though they look rather similar, they differ in their use of the trailing slash in the URL definition. In the first case, the canonical URL for the projects endpoint has a trailing slash. In that sense, it is similar to a folder on a file system. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.

In the second case, however, the URL is defined without a trailing slash, rather like the pathname of a file on UNIX-like systems. Accessing the URL with a trailing slash will produce a 404 “Not Found” error.

This behavior allows relative URLs to continue working even if the trailing slash is omitted, consistent with how Apache and other servers work. Also, the URLs will stay unique, which helps search engines avoid indexing the same page twice.

Upvotes: 2

Related Questions