3

I am facing a problem with flask url routing; it seems routes are not working as expected.

  1. Under project/src/views.py, I have the following sample routes

    from flask import (Flask,request,jsonify,Blueprint)
    my_view = Blueprint('my_view', __name__)
    
    @my_view.route('/',methods=("GET",))
    @my_view.route('/index',methods=("GET",))
    def index():
        ....
        <return response code here> 
    
    @my_view.route("/key/<inp1>/<inp2>", methods=("POST","GET"))
    def getKey(inp1=None, inp2=None):
        ....
        <return response code here>
    
  2. Now, under project/src/app.py, I have the following code

    from ../src.views import my_view 
    
    my_app = Flask("myappname")
    my_app.register_blueprint(my_view)
    my_app.run(debug=True,host=APP_IP,port=APP_PORT)
    

Now, when I access the URL http://ip:port/index or http://ip:port/key... with valid parameters, it returns 404, with the message "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." I believe mentioned routes are not working.

2
  • Team, any suggestions? As well, how do we know as whats happening when this endpoint was hit? Anyway, we can add few debug statements to the code. Commented Jun 11, 2015 at 7:52
  • 2024 and still without solution? Commented Mar 8, 2024 at 10:18

1 Answer 1

4

The first issue spotted is with your methods parameter. It expects a list/tuple but you're passing a string ('GET'). Change to methods=('GET', ). Note the comma after 'GET' here. Or to avoid potential confusion in the future, use methods=['GET']

The second issue is the way you're import my_view in app.py. Since views.py and app.py are in the same directory, and you're starting your flask app inside that directory, you can just do:

from views import my_view

However you should look into structuring your app as a Python Package

The third issue is a missing from flask import Flask. Maybe you overlooked this when you posted your code.

I tested your code with the above fixes and it works like it should.

EDIT: Thanks to @dirn for pointing out that tuples are accepted for methods parameter.

Sign up to request clarification or add additional context in comments.

2 Comments

Tuples are okay. The problem is that ('GET') is not a tuple, it's a string; ('GET',) is a tuple.
Just to be clear, when i run the app.py with out blueprints and keeping all routes and business logic in same code file app.py, these are working, so decorators, arguments, business code is not the issue i believe, after testing i just moved some stuff to views.py as a good project structure and added blueprints, thereafter the issue started.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.