Unexplainable Flask 404 errors

2020-06-30 04:09发布

问题:

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='/',
    )

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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



回答5:

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


标签: python flask