ICanKindOfCode
ICanKindOfCode

Reputation: 1120

Flask returns 404 when trying to supply GET parameters to root '/' url

Here is my route: @app.route('/'). In it I use request.args.get('page') for pagination. But the problem I am having is, if I go to my browser and visit localhost:5000/?page=2 flask returns a 404. What is the reason for this? It works fine on localhost:5000 but I want to supply a page. How do I do this?
EDIT: Here is my route:

from flaskblog import app
from flaskblog.models import Post # Flask-SQLAlchemy
@app.route('/')
def blog_index():
    page_num = int(request.args.get('page', 1))
    post_data = Post.query.paginate(per_page=10, page=page_num).items
    return render_template('index.html', posts=post_data)

And for the data I have a single post.

Upvotes: 0

Views: 1877

Answers (2)

ICanKindOfCode
ICanKindOfCode

Reputation: 1120

I found out my error. In Flask-SQLAlchemy pagination, if nothing is found in a page, it abort(404)s. To prevent this from happening I did this:

#...
Post.query.paginate(per_page=10, page=page_num, error_out=False).items #the error_out=False part
#...

And then I handle the problems on my own such as negative page number, no posts found in page etc.

Upvotes: 1

hcheung
hcheung

Reputation: 4014

First, you din't pass in page as a parameter into your route; Second, your route is not designed to handle subsequence page(s).

In order for the route to handle default page 1 and subsequent pages, You specify the route as:

@app.route('/', defaults={'page': 1})
@app.route('/page/<int:page>/')
def index(page):
    # rest of the code

Upvotes: 0

Related Questions