Flask custom "not found" code - python

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.

Related

'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')

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

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>-->

Basic flask application with after_request returns server error

from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return "k?"
#app.after_request
def sendsms():
pass
if __name__ == '__main__':
app.run()
What am I doing wrong? Or do I understand the after_request wrong if so I'd really appreciate an explanation.
The documentation is usually a good place to find answers to things like this.
Your function must take one parameter, a response_class object and return a new response object or the same (see process_response()).
Your function does neither of those things.
#app.after_request
def sendsms(response):
return response

Using requests module in flask route function

Consider the following minimal working flask app:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "I am /"
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
This happily works. But when I try to make a GET request with the "requests" module from the hello route to the api route - I never get a response in the browser when trying to access http://127.0.0.1:5000/
from flask import Flask
import requests
app = Flask(__name__)
#app.route("/")
def hello():
r = requests.get("http://127.0.0.1:5000/api")
return "I am /" # This never happens :(
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
So my questions are: Why does this happen and how can I fix this?
You are running your WSGI app with the Flask test server, which by default uses a single thread to handle requests. So when your one request thread tries to call back into the same server, it is still busy trying to handle that one request.
You'll need to enable threading:
if __name__ == "__main__":
app.run(threaded=True)
or use a more advanced WSGI server; see Deployment Options.

Categories