Unexplainable Flask 404 errors - python

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'

Related

404 error constantly encountered when working with Flask

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

How to link flask with react application ? [duplicate]

I have a Flask back-end with API routes which are accessed by a React single page application created using create-react-app. When using the create-react-app dev server, my Flask back end works.
I would like to serve the built (using npm run build) static React app from my Flask server. Building the React app leads to the following directory structure:
- build
- static
- css
- style.[crypto].css
- style.[crypto].css.map
- js
- main.[crypto].js
- main.[crypto].js.map
- index.html
- service-worker.js
- [more meta files]
By [crypto], I mean the randomly generated strings generated at build time.
Having received the index.html file, the browser then makes the following requests:
- GET /static/css/main.[crypto].css
- GET /static/css/main.[crypto].css
- GET /service-worker.js
How should I serve these files? I came up with this:
from flask import Blueprint, send_from_directory
static = Blueprint('static', __name__)
#static.route('/')
def serve_static_index():
return send_from_directory('../client/build/', 'index.html')
#static.route('/static/<path:path>') # serve whatever the client requested in the static folder
def serve_static(path):
return send_from_directory('../client/build/static/', path)
#static.route('/service-worker.js')
def serve_worker():
return send_from_directory('../client/build/', 'service-worker.js')
This way, the static assets are successfully served.
On the other hand, I could incorporate this with the built-in Flask static utilities. But I do not understand how to configure this.
Is my solution robust enough? Is there a way to use built-in Flask features to serve these assets? Is there a better way to use create-react-app?
import os
from flask import Flask, send_from_directory
app = Flask(__name__, static_folder='react_app/build')
# Serve React App
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def serve(path):
if path != "" and os.path.exists(app.static_folder + '/' + path):
return send_from_directory(app.static_folder, path)
else:
return send_from_directory(app.static_folder, 'index.html')
if __name__ == '__main__':
app.run(use_reloader=True, port=5000, threaded=True)
Thats what I ended up with. So bascially catch all routes, test if the path is a file => send file => else send the index.html. That way you can reload the react app from any route you wish and it does not break.
First do npm run build to build the static production files as mentioned by you above
from flask import Flask, render_template
app = Flask(__name__, static_folder="build/static", template_folder="build")
#app.route("/")
def hello():
return render_template('index.html')
print('Starting Flask!')
app.debug=True
app.run(host='0.0.0.0')
Unfortunately, I don't think you can get it work with the development hot-reload.
A working solution here.
Ever thought why we need two separate folders for static and templates. To segregate the mess, right?
But, it's a problem with the production build since it has one folder for both static and templates type of files and all dependencies are linked like that.
The build folder will be served if you consider it both static and templates.
Use something like this
from flask import Flask, render_template
app = Flask(__name__, static_url_path='',
static_folder='build',
template_folder='build')
#app.route("/")
def hello():
return render_template("index.html")
Your flask app will run fine.
The accepted answer does not work for me. I have used
import os
from flask import Flask, send_from_directory, jsonify, render_template, request
from server.landing import landing as landing_bp
from server.api import api as api_bp
app = Flask(__name__, static_folder="../client/build")
app.register_blueprint(landing_bp, url_prefix="/landing")
app.register_blueprint(api_bp, url_prefix="/api/v1")
#app.route("/")
def serve():
"""serves React App"""
return send_from_directory(app.static_folder, "index.html")
#app.route("/<path:path>")
def static_proxy(path):
"""static folder serve"""
file_name = path.split("/")[-1]
dir_name = os.path.join(app.static_folder, "/".join(path.split("/")[:-1]))
return send_from_directory(dir_name, file_name)
#app.errorhandler(404)
def handle_404(e):
if request.path.startswith("/api/"):
return jsonify(message="Resource not found"), 404
return send_from_directory(app.static_folder, "index.html")
#app.errorhandler(405)
def handle_405(e):
if request.path.startswith("/api/"):
return jsonify(message="Mehtod not allowed"), 405
return e
I used a flask server with only one route / which read the index.html file from the build folder of Create react app(CRA)
from flask import Flask
app = Flask(__name__)
app.static_folder = '../build'
#app.route('/')
def index():
fref = open(r'../build/index.html')
html_text = fref.read()
fref.close()
return html_text
app.run()
Setting up this way I faced an error, the static files are not properly served due to path mismatch, so the solution I used is
Add a homepage property in package.json of CRA and set it to "/static"
{
"name":"App-name",
"version":"",
"dependencies":{}
"homepage":"/static",....[other keys]}
Add **homepage** key parallel to the **dependencies** key in the package.json file
This homepage property will be used during the build process of CRA and used in the place of %PUBLIC_URL% of index.html and gets appended to other static assets URL path (you can verify by viewing the index.html code after the build process)
After the build process, run the flask server,we can see the GET request coming with / for the first time and index.html will be served and followed by requests /static/static/js/[[filename]] for other static assets from HTML file and everything works correctly

Flask static file giving 404

Code in main.py file:
from flask import Flask, render_template, send_from_directory
app = Flask(__name__, static_url_path="")
app._static_folder = "static"
#app.route("/")
def root():
return app.send_static_file("index.html")
#app.route("/about")
def about():
return app.send_static_file("about/index.html")
#app.route("/projects")
def projects():
return app.send_static_file("projects/index.html")
#snip
if __name__ == "__main__":
app.run(host="0.0.0.0")
When I go to the root directory or the /about directory it works fine, but when I try to go to the /projects directory, I got the error:
Error message:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
There are two possible reasons.
You mis-typed the path. Did you perhaps have a typo in projects (i.e., project) or index.html?
The path doesn't exist. Unlike render_template, app.send_static_file just dies if the path doesn't exist. Since the static_folder is static, then the project page code should exist under static/projects/index.html (and not projects/index.html).
To test if it's a rogue issue, replace the body of the projects view with return 'some string'. If that string doesn't show, then you have a different beast on your hands. If it does, then it's most definitely one of the two bugs I've identified above.
On an un-related note, I would add debug=True to the list of app.run(...) kwargs, to make development more convenient. (The app refreshes whenever there's a file save)

Structuring Flask using Blueprints error

I'm attempting to break a small app into units and use the Blueprint pattern in Flask. However I seem to have trouble in getting the app running.
Here is my structure:
\myapp
login.py
\upload
__init__.py
views.py
Here is login.py:
import sys, os
from flask import Flask, Blueprint, request
from flask import render_template, session
from .upload import views
app = Flask(__name__)
app.register_blueprint(views)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
print app.url_map
print app.blueprints
app.run(debug = True)
for __init__.py
from flask import Flask
app.register_blueprint('upload', __name__)
and in views.py
from flask import Flask, Blueprint, request, redirect, url_for, render_template
import views
upload = Blueprint('upload', __name__)
#upload.route('/uploaded', methods=['GET', 'POST'])
def upload_file():
...
Looking at the logs on heroku, here is the error:
from .upload import views
2015-09-05T10:59:00.506513+00:00 app[web.1]: ValueError: Attempted relative import in non-package
Have a structured my package and blueprint correctly? I used the documentation, but I think I'm missing something here.
There are three problems with your code:
You are using a relative import in login.py to include views, but given the folder structure and the fact that you use login.py as starting point, it cannot work here. Simply use from upload import views instead.
The __init__.py references an unknown variable, app. You actually don't need anything in this file, remove everything.
You try to register a module as a blueprint via app.register_blueprint(views) in login.py. This cannot work, a module is not a blueprint. Instead, import the upload variable defined in the views module, that is a blueprint: app.register_blueprint(views.upload).
Changing that should get you started. Two side notes:
You have an import in views.py that should probably not be there: import views. This should be harmless however.
I answered a question about Flask blueprints some days ago, and gave an example about how to use them. Maybe would you find the answer useful in your case as well (in particular the part where the blueprint definition is moved to the __init__.py file defining the blueprint).

Flask routing using wsgi not working

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

Categories

Resources