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!!
Related
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 :/
In a Python authorization app, in my main py I have the following code:
# main.py
from flask import Blueprint, render_template
from flask_login import login_required, current_user
theapp = Blueprint('main', __name__)
#theapp.route('/')
def index():
return render_template('index.html')
When I try:
FLASK_APP=main.py
FLASK_DEBUG=1
flask run
I get the following error:
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
Basically a Blueprint is a way for you to organize your flask application into smaller and reusable applications. I am not sure why you have used it here in the main.py.
You could do that some other file, for example, you have a set of endpoints to implement login functionality in a separate file then what you should be doing is:
Assume you have a login.py .Sample Code looks like follows:
from flask import Blueprint
bp = Blueprint('login_bp', __name__)
def login_bp():
return bp
And the following code goes into you main.py , you need to start the Flask Server using .run()
from flask import Flask
from flask import Blueprint, render_template
from login import login_bp #Assume you have a module login and I am importing login_bp from login.py
theapp = Flask(__name__) #Creating Flask instance
theapp.register_blueprint(login_bp()) # Registering Blueprint here
#theapp.route('/')
def index():
return render_template('index.html')
theapp.run(host="0.0.0.0", port=2019, debug=True) #Starting the Flask Server
Hope this works, please do look out for documents and code example to get deeper insights.
My flask application currently consists of a single test.py file with multiple routes and the main() route defined. Is there some way I could create a test2.py file that contains routes that were not handled in test.py?
#app.route('/somepath')
def somehandler():
# Handler code here
I am concerned that there are too many routes in test.py and would like to make it such that I can run python test.py, which will also pick up the routes on test.py as if it were part of the same file. What changes to I have to make in test.py and/or include in test2.py to get this to work?
You can use the usual Python package structure to divide your App into multiple modules, see the Flask docs.
However,
Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.
You can create a sub-component of your app as a Blueprint in a separate file:
simple_page = Blueprint('simple_page', __name__, template_folder='templates')
#simple_page.route('/<page>')
def show(page):
# stuff
And then use it in the main part:
from yourapplication.simple_page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
Blueprints can also bundle specific resources: templates or static files. Please refer to the Flask docs for all the details.
You can use simple trick which is import flask app variable from main inside another file, like:
test_routes.py
from __main__ import app
#app.route('/test', methods=['GET'])
def test():
return 'it works!'
and in your main files, where you declared flask app, import test-routes, like:
app.py
from flask import Flask, request, abort
app = Flask(__name__)
# import declared routes
import test_routes
It works from my side.
This task can be accomplished without blueprints and tricky imports using Centralized URL Map
app.py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
views.py
from flask import render_template
def index():
return render_template('index.html')
def other():
return render_template('other.html')
I would like to recommend flask-empty at GitHub.
It provides an easy way to understand Blueprints, multiple views and extensions.
If you need split blueprint to separate files you can use snippet:
# app.py
from blueprint_module import blueprint
app = Flask(__name__)
app.register_blueprint(blueprint)
# blueprint_module\__init__.py
from flask import Blueprint
blueprint = Blueprint('my_blueprint', __name__)
from . import page
# blueprint_module\page.py
from . import blueprint
#blueprint.route("/url", methods=['GET'])
def hello():
return 'hello world'
Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.
I created a Gist with the code for doing this:
https://gist.github.com/Jaza/61f879f577bc9d06029e
As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:
https://github.com/mitsuhiko/flask/issues/593
Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.
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'
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