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...)
Related
You see Im having a problem where in flask, I made a web app. and I added the URL prefix as views
and you see without /views attached to localhost it throws a 404, I wanna change it so it will redirect automatically to /views when you go to the regular URL such as http://127.0.0.1:8000/
I tried adding #app.route in app.py but it just caused even more problems
You could redirect automatically from http://127.0.0.1:8000/ to http://127.0.0.1:8000/views using the code below.
from flask import Flask, jsonify, redirect
app = Flask(__name__)
#Page 1
#app.route('/', methods=['GET'])
def welcome():
return redirect("http://127.0.0.1:8000/views", code=302)
#Page 2
#app.route('/views', methods=['GET'])
def hello():
return jsonify({"data": "Hello"})
if __name__ == '__main__':
app.run(host="0.0.0.0", port="8000")
Output
#127.0.0.1 - - [01/Dec/2022 15:23:23] "GET / HTTP/1.1" 302 - (Redirecting to views page)
#127.0.0.1 - - [01/Dec/2022 15:23:23] "GET /views HTTP/1.1" 200 -
Hope this helps. Happy Coding :)
#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
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>-->
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()
I'm using flask app factory pattern like and have this run.py file:
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(host='localhost', debug=True)
Then I run the app like this:
python run.py
But when I go to http://localhost:5000 it doesn't work.
It says:
Not Found
The requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
What could be wrong? it works well when I have 127.0.0.1 address...
I need to run on "localhost" because I'm integrating square payments and their sandbox setup requires I make requests to their API from a 'localhost'.
Also, when I make the request in the browser, on the terminal when flask responds there is this:
127.0.0.1 - - [09/Sep/2017 00:30:45] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [09/Sep/2017 00:30:45] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [09/Sep/2017 00:30:45] "GET /favicon.ico HTTP/1.1" 404 -
So it looks like request reaches flask but flask returns 404.
Here is part of my init.py file:
# from __future__ import print_function
# import flask
from flask import Flask, render_template, url_for, redirect, flash, request, \
session, current_app, abort
import os
# flask sqlaclhemy
from sqlalchemy import func, desc, asc, or_, and_
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
# Flask secrutiy
from flask_security import (Security, SQLAlchemyUserDatastore,
login_required, current_user)
from flask_login import LoginManager
from flask_mail import Mail
# square connect setup
import uuid
import squareconnect
from squareconnect.rest import ApiException
# from squareconnect.apis.locations_api import LocationsApi
from squareconnect.apis.transactions_api import TransactionsApi
mail = Mail()
class CustomAdminIndexView(AdminIndexView):
def is_accessible(self):
return current_user.is_authenticated and current_user.has_role('admin')
def create_app():
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
mail.init_app(app)
from models import db, User, Role
db.init_app(app)
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
#app.route('/')
def home():
return render_template('home.html')
return app
the simple alternative solution is first to check if the port 5000 is avialable you can check that with this comand :
netstat -lat
find more about available port here :
if you are not obliged to use port 5000 you can try anything else you want ..
if every thing is ok that mean you have a problem with your home page , you don't have a route to '/' , that why you are getting the 404 error when you go to localhost:5000/ :
so to correct it you have 3 solution :
add the app.route('/') in your init.py file
add it directly in your run.py after creating the app (not a good way)
try to use blueprints
as you didn't provide your init.py code let add it to your run.py ,
from app import create_app
app = create_app()
#app.route('/')
def homepage():
return 'hello world'
if __name__ == '__main__':
app.run(host='localhost', port=9874)
another solution as suggest in comment is to check if 127.0.0.1 resolve to localhost find the host file by typing this command and check if you have the same line as mine :
nano /etc/hosts
and open the file :
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
Just incase anyone on a mac runs into this issue and has trouble finding any answers (like me), I just discovered that it's because Apple Airplay Receiver runs on port 5000. Disable airplay receiver and try again.
there will be no entry as localhost in your hosts file
example host file
127.0.0.1 localhost
you can check your hosts file in following ways
for linux
sudo vi /etc/hosts
for windows
open this file C:\Windows\System32\Drivers\etc\hosts
if there is no localhost in your hosts file add and save it.
May be you need to install virtual enviroment
pip install virtualenv
does this. Hope this works
You should try switching out localhost for 0.0.0.0.
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
This has it serve on localhost for me.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello"
if name == "main":
app.run(host='0.0.0.0', port=9874)