when I run the website on any browser, the typical 404 error "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." regardless of what I route it to or if I route it at all. I have checked, and everything seems to be in the right place, but I have no idea what is causing the error, especially as I have tried every fix I have found online.
My route.py file is as follows:
from flask import Flask, render_template, url_for
from blog import app, db
from blog.models import User, Post
app = Flask(__name__, template_folder='templates', static_folder='static')
app = Flask(__name__)
#app.route('/')
#app.route("/home")
def home():
posts = Post.query.all()
return render_template('home.html', posts=posts)
#app.route("/about")
def about():
return render_template('about.html', title='About')
The WSGI is:
from blog import app as application
if __name__ == '__main__':
app.run(debug=True)
and the __init__.py file is:
from flask import Flask
import os
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'be35984218226b31d6ca0bf1ccefdaf78e47c9181177a41a'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'blog.db')
db = SQLAlchemy(app)
from blog import routes
Thanks in advance for any advice given
There are 2 things that could be going wrong:
Your Firewall is blocking the flask app
You entered the wrong IP Address.
If you entered the wrong IP Address, use this IP instead: localhost:5000.
A better alternative would be to use this app.run function instead
app.run(host="0.0.0.0", port=ENTER YOUR DESIRED PORT HERE)
If the firewall is the issue, stackoverflow isn't the right place :/
Related
I am trying to use the wsgi DispatcherMiddleware in order to prefix a url on my application. I've written one module for the dispatcher and one for the app, which has just one view called home and this is where the homepage is served from.
here is my app1.py
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/home', methods=['GET'])
def home():
return "<h1>Home</h1>"
and dispatcher.py
from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.exceptions import NotFound
from app1 import app
app = Flask(__name__)
app.wsgi_app = DispatcherMiddleware(NotFound(), {
"/prefix": app
})
if __name__ == "__main__":
app.run()
what I wanna do is be able to navigate to http://127.0.0.1:5000/prefix/home
when I run on console py dispatcher.py, but however when I navigate on that url I get a 404 response. What works in only the navigation to the pagehttp://127.0.0.1:5000/home. Could someone help me understand why this happens? I appreciate any help you can provide
Adding prefix to all routes is really simple if you opt for using Blueprints
https://flask.palletsprojects.com/en/1.0.x/tutorial/views/#create-a-blueprint
from flask import Flask, Blueprint
app = Flask(__name__)
prefixed = Blueprint('prefixed', __name__, url_prefix='/prefixed')
#app.route('/nonprefixed')
def non_prefixed_route():
return 'this is the nonprefixed route'
#prefixed.route('/route')
def some_route():
return 'this is the prefixed route'
app.register_blueprint(prefixed)
if __name__ == "__main__":
app.run()
Testing the routes:
> curl localhost:5000/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
> curl localhost:5000/nonprefixed
this is the nonprefixed route
> curl localhost:5000/prefixed/route
this is the prefixed route
SOLUTION:
I was using wrong tha same name for the dispacher and the app1.
dispacher.py should be edited as follows:
from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.exceptions import NotFound
from app1 import app as app1
app = Flask(__name__)
app.wsgi_app = DispatcherMiddleware(NotFound(), {
"/prefix": app1
})
if __name__ == "__main__":
app.run()
I have a website that uses Flask. It used to work well, but since recently, every request returns a 404, and it seems it can't find the right endpoints. However:
Locally, the site still works, only on my VPS it shows this strange behaviour.
url_for works and app.view_functions contains all the routes as well.
And yet, I keep getting 404s on the VPS, even for / and anything under /static/.
Here's part of the code, it's a bit much to show all of it and it's not all relevant:
#snip
from flask import Flask, render_template, abort, request, redirect, url_for, session
from flask.ext.babelex import Babel
from flask.ext import babelex
#snip
app = Flask(__name__)
app.secret_key = #snip
#snip
#just one of the routes
#app.route('/')
def about():
return render_template('about.html')
#snip
#app.errorhandler(404)
def page_not_found(e):
#snip
return render_template('404.html'), 404
#snip
if __name__ == '__main__':
app.run(debug=True)
else:
app.config.update(
SERVER_NAME='snip.snip.com:80',
APPLICATION_ROOT='/',
)
I had the same issue. I had it because I changed the parameters SERVER_NAMEof the config to a name which is not the name of the server.
You can solve this bug by removing SERVER_NAME from the config if you have it.
I know this is old, but I just ran into this same problem. Yours could be any number of issues but mine was that I had commented out the from app import views line in my __init__.py file. It gave me the same symptom: every endpoint that required #app.route and a view was responding with 404's. Static routes (.js and .css) were fine (that was my clue).
Had the same issue because the following lines
if __name__ == '__main__':
app.run(host='127.0.0.1', threaded=True)
were declared before the function and decorator.
Moving these lines in the very bottom of file helped me.
Extremely old by this point, but mine was related to bug in importing. I'm using blueprints and I had:
from app.auth import bp
instead of
from app.main import bp
I was importing the wrong bp/ routes
I received this error from defining my flask_restful route inside the create_app method. I still don't quite understand why it didn't work but once I changed the scope / moved it outside as shown below it worked.
from flask import Flask
from flask_restful import Resource
from extensions import db, api
from users.resources import User
def create_app():
app = Flask(__name__)
app.config.from_object('settings')
db.init_app(app)
api.init_app(app)
return app
api.add_resource(User, '/users')
Also check carefully the routes. If some does not end with a slash but you are calling it with a trailing slash, flask will return a 404.
I had this error following a url from an email client that (I don't know why) append a trailing slash to the urls.
See documentation.
I had this problem and in my case it was about my templates. I had an index page like this:
<div>
Home |
Login |
Register
<hr>
</div>
I should have used url_for('index') instead of index.html.
<div>
Home |
Login |
Register
<hr>
</div>
For me, I was getting 404s on every request due to missing favicon.ico and manifest.json. The solution was to provide the missing favicon.ico, and remove the link rel refence to manifest.json.
I found this out by printing the path that was causing problems on every request in my #app.errorhandler(Exception):
from flask import request
#app.errorhandler(Exception)
def handle_exception(err):
path = request.path # this var was shown to be 'favicon.ico' or 'manifest.json'
I have been following the methods provided in this post:
https://stackoverflow.com/questions/12167729/flask-subdomains-with-blueprint-getting-404
Here is my relevant code:
__init__.py
from flask import Flask, render_template
app = Flask(__name__, static_url_path="", static_folder="static"
import myApp.views
views.py
from flask import Flask, render_template, request, Blueprint
from myApp import app
app.config['SERVER_NAME'] = 'myapp.com'
app.url_map.default_subdomain = "www"
#app.route("/")
def index():
return "This is index page."
test = Blueprint('test', 'test', subdomain='test')
#test.route("/")
def testindex():
return "This is test index page."
app.register_blueprint(test)
if __name__ == "__main__":
app.run()
Using this method I am able to get subdomains 'test' and 'www' working, but now I am unable to access my website via IP address.
Any guidance into the right direction would be appreciated!
I have a simple flask app I'm working on (my website), but for whatever reason routing doesn't work. It will only present '/' - nothing else. However, when I use the embedded debug server, it all routes fine to where it needs to go.
I've followed this tutorial to the letter. Any help is greatly appreciated.
View.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
#app.route('/index')
def index():
return render_template("index.html", title='Site Title')
#app.route('/software/')
def software():
return "LALALA"
if __name__ == '__main__':
app.run()
run.wsgi
import sys
sys.path.insert(0,'/home/www/flaskweb')
from web import web as application
I fixed this. It was an issue in my package names. Thanks!!
from flask import Flask, render_template
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/page/<path:page>')
def article(page):
return render_template('page.html')
if __name__ == "__main__":
app.run()
Work just fine. But if i change the second route to #app.route('/<path:page>'), then any access to URL like /path/to/page yields 404.
Why doesn't #app.route('/<path:page>') work?
Related questions, that don't answer the question however:
Flask: Handle catch all url different if path is directory or file
Custom routing in Flask app
Capture arbitrary path in Flask route
static_url_path conflicts with routing. Flask thinks that path after / is reserved for static files, therefore path converter didn't work. See: URL routing conflicts for static files in Flask dev server
works flawless for me:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/page/<path:page>')
def article(page):
return render_template('page.html')
if __name__ == "__main__":
app.debug = True
app.run()
I can access: http://localhost/ -> index and http://localhost/page/<any index/path e.g.: 1> -> article