Flask gives 404 when trying to render a template - python

#app.route('/')
def index():
return render_template("home.html")
My folder structure looks like this
tree-/
-static/
-styles.css
-templates/
-home.html
-app.py
I get
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
On the browser and
127.0.0.1 - - [01/May/2021 09:41:47] "GET / HTTP/1.1" 404 -
In the debugger
Have looked at other related posts saying stuff about trailing slashes and it doesn't look like its making a difference, either I access
http://127.0.0.1:5000
or
http://127.0.0.1:5000/
I run my application using
app = Flask(__name__)
if __name__ == '__main__':
app.run()
I get
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
if __name__ == '__main__':
app.run()
#app.route('/')
def index():
return "Hello World"

Problem is order of code.
Line app.run() has to be at the end of code because it runs endless code/loop (which gets requests from clients/browsers and sends reponses) and it blocks next lines of code. All code after app.run() is executed after server is closed.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World"
if __name__ == '__main__':
app.run()

Move app.run() to the bottom.
Thanks to furas for this solution, hope this can help people looking at this thread

Related

Not getting web output

I used Flask command in my program for first time. Following was the bit of code I wrote:
from flask import Flask,jsonify, request
app = Flask(__name__)
#app.route("/")
def hello_world():
return "Hello World!"
if (__name__ == "__main__"):
app.run(debug=True)
This code was written by me in IDLE Shell 3.8-32 bit and the output should had come in a web browser. But it didn't came. I just got the following output from IDLE:
* Serving Flask app "sa" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
app.run(host=0.0.0.0, port=5000, debug=True)
You can change your port number to your convenience.

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

waitress command line returning "Malformed Application" when deploying flask web app

I'm attempting to deploy a simple web app, and I'm using command line waitress-serve --call command. But every time, the command immediately returns 1. Malformed application 'name_of_project_here'.
Here's my flask web app in python:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run(debug = True)
and the command I run is just
waitress-serve --call "name_of_project"
I did try looking through the documentation, and I found where the error occurs, but couldn't find an explanation of why it's occurring. What does malformed application mean?
Minimal working example:
If you put code in file main.py
from flask import Flask
def create_app():
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World!"
return app
if __name__ == '__main__':
app = create_app()
app.run()
then you can run it as
waitress-serve --call "main:create_app"
So "name_of_project" has to be "filename:function_name" which creates Flask() instance.
It can't be any text. And if you forget : then you may see "Malformed application"
when defining your appname and the function that initialize your app with : dont put them into quotes('')

flask app gives 404 for non-root route

I want to give flask a try. Using flask 0.12, python 3.4
I've created the project tree similar like in:
https://damyanon.net/post/flask-series-structure/
controllers.py code:
from flask import Blueprint
import functools, operator
main = Blueprint('main', __name__)
#main.route('/')
def index():
return "Main world"
#main.route('/foo')
def foo():
return "this is foo"
when I run the app,
I got 404 for /foo route but '/' is OK
* Serving Flask app "run"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [27/Dec/2017 15:19:21] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2017 15:19:25] "GET /foo HTTP/1.1" 404 -
Any clue?
Thanks.
edit:
As requested, here how I register blueprint in
flask_app/localservice/init.py. Not sure about application factory. I'm still new with this. I substitute bookshelf with localservice and not use admin
from flask import Flask
from localservice.main.controllers import main
app = Flask(__name__)
app.register_blueprint(main, url_prefix='/')
I was following the same tutorial and the same error occurred for me as well. After being stuck on this for quite a while I finally figured it out.
So looks like there's an error in the tutorial. You can't register using '/'.
app.register_blueprint(main, url_prefix='/')
This is the actual github codebase where the tutorial guy wrote the code.
If you look at the code and commit history, he changed url_prefix from '/' to 'main'. Change your url_prefix and the code should work.
If you don't insist on following that tutorial, the code in the Flask Quickstart docs works perfectly fine
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Main world"
#app.route('/foo')
def foo():
return "this is foo"
if __name__ == '__main__':
app.run()

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