I can't go to the other paths i am using flask - python

I am studying this course on flask. This is the basic flask code. When I am on the first route I am fine but when I try to put slash and got for another page it doesn't work.
I get this message:
"The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
I did run FLASK_APP=app.py flask run
after saving.
from Flask import flask
app= Flask(__name__)
#app.route('/')
def index():
return "index"
#app.route('/me')
def me():
return "me"
if __name__== "__main__":
app.run(debug=True)
In class it works well. When i do it it does not
127.0.0.1 - - [08/Jul/2019 02:43:55] "GET /me/ HTTP/1.1" 404 -
I'm guessing 404 at the end is problem
After the reply
from Flask import flask
app= Flask(__name__)
strict_slashes=False
#app.route('/')
def index():
return "index"
#app.route('/me/')
def me():
return "me"
if __name__== "__main__":
app.run(debug=True)

You have declared your "/me" route explicitly without trailing slash. However, when calling the URL, you are calling it with slash in the end "/me/". Werkzeug (Flask development application server) by default has the rule of "strict_slashes=True", which requires you to follow exact route declaration when calling your URLs. In other words, if in your code, you declared "#app.route('/me'), your should call "127.0.0.1/me", not "127.0.0.1/me/".
Removing the slash in the end (e.g. http://localhost/me) will fix your issue. You can also change the Werkzeug setting and set strict_slashes=False if you want to remove the default rule.

I would say make a app.errorhandler(404) and then define what to do after you get an error to check if it is a 404 error, and other errors. I would also say use html and make links which you can use to go into different pages, it is easier than typing manually. here is my code:
python:
from flask import Flask, render_template
app = Flask(__name__)
app.route('/')
def home():
return render_template('home.html')
app.route('/me')
def me():
return 'me'
app.errorhandler(404)
def error(arg):
return 'wrong url'
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
html:
<!-- you can use css to make the link look better or <style> </style>-->

Related

Flask 404 Not Found ( 33mGET / HTTP/1.1 [0m" 404 - )

I am trying to create my first script with flask.
Here is my code:
from flask import Flask
from flask import Blueprint, request
prediction_app = Blueprint('prediction_app', __name__)
#prediction_app.route('/health', methods=['GET'])
def health():
if request.method == 'GET':
return 'ok'
def create_app() -> Flask:
"""Create a flask app instance."""
flask_app = Flask('ml_api')
# import blueprints
flask_app.register_blueprint(prediction_app)
return flask_app
application = create_app()
if __name__ == '__main__':
application.run()
I run this code as python run.py and I am getting "Running on http://127.0.0.1:5000/".
I go to this link and I am getting instead of "ok" a page with the next error:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Command promt gives the following output:
127.0.0.1 - - [17/Jun/2020 16:59:25] "[33mGET / HTTP/1.1[0m" 404 -
Where is the problem?
I don't see a default route (/) defined; did you try pointing your browser at http://localhost:5000/health? That's the route you did define.
(localhost and 127.0.0.1 are typically equivalent, by the way...)

'The requested URL was not found on the server'

from flask import Flask
app = Flask(__name__)
#app.route('/hello')
def hello_world():
return "Hello world"
if __name__ == '__main__':
app.run(host='0.0.0.0',port=8000, debug=True)
While clicking the link http://0.0.0.0:8000/, it is showing:
> The requested URL was not found on the server If you entered the URL
> manually please check your spelling and try again.
The only URL you have defined is /hello, so when you request /, there is nothing to be served, so you get the Not Found Error. You'll need to either define something for / or use http://0.0.0.0:8000/hello instead. E.g.,
#app.route('/')
def index_view():
return "hello from index"

My code shows this error whatever I try, and when I click on the link it shows there's a 404

Whatever I seem to try (using different secret keys, trying to fix small errors) this error shows when I run my code.
I have tried making small changes to the code such as changing the secret key, fixing indentation, etc. However, I do not understand why my code does not work, so I wanted to ask here.
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secretcodehere29403949493'
socketio = SocketIO(app)
#app.route("/template/chat.html/")
def chat():
return render_template("template/login.html")
#app.route(r'/template/login.html/')
def login():
return render_template('login.html')
#socketio.on('message', namespace='/chat')
def chat_message(message):
print("message = ", message)
emit('message', {'data': message['data']}, broadcast=True)
#socketio.on('connect', namespace='/chat')
def test_connect():
emit('my response', {'data': 'Connected', 'count': 0})
if __name__ == '__main__':
socketio.run(app)
Restarting with stat
Debugger is active!
Debugger PIN: 183-355-780
(18512) wsgi starting up on http://127.0.0.1:5000
nothing displays in the link it provides in the error here, and localhost:8080 shows nothing.
Your routes may not be correct. When you call app.route, you're mapping a url to the function.
In your case the urls in your routes are defining: 127.0.0.1:5000/template/chat.html/ and 127.0.0.1:5000/template/login.html/.
Try changing a route to #app.route('/') and then navigating to 127.0.0.1:5000 or localhost:5000
Concerning your last comment (I can't comment on dylanj.nz's post), the render_template function uses the default templates folder, so there is no need to specify it on your code :)
Thus you should remove template/ in this line:
return render_template("template/login.html").
If you want to change the default folder location, add a template_folder instruction in your app = Flask(...).
Example:
app = Flask(__name__, template_folder='application/templates', static_folder='heyanotherdirectory/static')

Flask dynamic route not working - Real Python

I'm working through RealPython and I'm having trouble with the flask dynamic route.
Everything seemed to work until the dynamic route. Now if I try to enter a "search query" (i.e. localhost:5000/test/hi) the page is not found. localhost:5000 still works fine.
# ---- Flask Hello World ---- #
# import the Flask class from the flask module
from flask import Flask
# create the application object
app = Flask(__name__)
# use decorators to link the function to a url
#app.route("/")
#app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
return "Hello, World!"
# start the development server using the run() method
if __name__ == "__main__":
app.run()
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
I can't see that other people using RealPython have had an issue with the same code, so I'm not sure what I'm doing wrong.
The reason why this is not working is because flask never learns that you have another route other / and /hello because your program gets stuck on app.run().
If you wanted to add this, all you need to do would be to add the new route before calling app.run() like so:
# ---- Flask Hello World ---- #
# import the Flask class from the flask module
from flask import Flask
# create the application object
app = Flask(__name__)
# use decorators to link the function to a url
#app.route("/")
#app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
return "Hello, World!"
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
# start the development server using the run() method
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True, port=5000)
Now this will work.
Note: You don't need to change the run configurations inside of app.run. You can just use app.run() without any arguments and your app will run fine on your local machine.
Try using the entire URL instead of just the IP address.

Flask custom "not found" code

I want to change the default 404 code, when flask doesn't finds the route, to other code. How can I do that?
As already said, it is generally not a good idea to redefine the meaning of standard status codes.
Although you can change a status code returned, here's an example:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 777
if __name__ == '__main__':
app.run()
This will return status code 777 on any page other than /.
Here's a result:
More on the topic you can find here.

Categories