This is the code read but Flask not rendering html
from flask import Flask,render_template
import psycopg2
import psycopg2.extras
app=Flask(__name__)
app.route('/')
def index():
return render_template('index.html')
if __name__=="__main__":
app.run(debug=True, port=9001)
If I'm not mistaking, it's just a typo error. Supposed you already have a file called index.html in your templates folder. So your tree look like this:
.
└── my_app/
├── templates/
│ └── index.html
└── run.py
This code should work:
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/') # <-- You are missing the '#' here
def index():
return render_template('index.html')
if __name__ == "__main__": # <-- Note this too
app.run(debug=True, port=9001)
Now you can access to your project at http://127.0.0.1:9001/
To learn more about Flask view decorator, go here.
For more information about what mean if __name__ == "__main__":, you can read more here.
Related
I am following the official flask tutorial.
I have already set up blueprints and they are working just fine.
I can use app.logger.debug('route "/hello" called') from __init__.py to log something–my issue is that I am struggling to use the app.logger from routes/routes.py though...
I have set up a structure like this:
fzwk_access
├── __init__.py
├── db.py
├── routes
│ ├── routes.py
│ ├── ...
...
So here's the question:
how can I use the app.logger from the file routes.py?
I already tried the following:
use from flask import app which did not work
use from fzwk_access import __init__ which does not work as I don't have app as a global variable there (I guess?)
My __init__.py looks like this:
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
#app.route('/hello')
def hello():
app.logger.debug('route "/hello" called')
return 'Hello, World!'
from . import db
db.init_app(app)
from .routes import routes, routes_admin, routes_logs
app.register_blueprint(routes.home_bp)
app.register_blueprint(routes_admin.admin_bp)
# app.register_blueprint(routes_logs.logs_bp)
return app
I am getting a template not found error while trying to run a flask app using blueprints. The template directory is located at the root directory as expected at the same level as the app directory. I am not very sure why this is happening.
The directory structure
root/
app/
blueprint1/
routes.py
__main__.py
templates/
base.html
index.html
routes.py
from flask import Blueprint, render_template
blueprint = Blueprint(
"blueprint", __name__, template_folder="templates")
#blueprint.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
Error
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: index.html
main.py
from flask import Flask
from app.blueprint1.routes import blueprint
def create_app():
app = Flask(__name__)
app.register_blueprint(blueprint)
return app
def _main():
daemon_app = create_app()
daemon_app.run(debug=True)
if __name__ == "__main__":
_main()
This works, I edited it a little
routes.py
from flask import Blueprint, render_template
blueprint = Blueprint("blueprint", __name__, template_folder="../../templates")
#blueprint.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
__main__.py
from flask import Flask
from routes import blueprint
def create_app():
app = Flask(__name__)
app.register_blueprint(blueprint)
return app
def _main():
daemon_app = create_app()
daemon_app.run(debug=True)
if __name__ == "__main__":
_main()`
Based on your file structure, your blueprint renders html files from the main template folder. It might work if you remove the template_folder argument from routes.py file.
I copied your codes and tried to emulate the error but it works for me. A year ago I have the same problem and somehow I solved it. Since I can't emulate the error I can't solve your problem.
Instead, I will just give you advise. You are making an effort to create blueprints in their own package, and yet you are using the main template folder. When you have a lot of blueprints managing the template folder will become a challenge. Thus, I recommend putting the html file within the blueprint package itself.
Here's the file structure:
root/
app/
blueprint1/
pages/blueprint1/index.html
routes.py
__main__.py
templates/
base.html
and routes.py should be like this
blueprint = Blueprint(
"blueprint", __name__, template_folder="pages")
#blueprint.route("/", methods=["GET", "POST"])
def index():
return render_template("blueprint1/index.html")
I have app.py file as below
from flask import Flask
app = Flask(__name__)
app.secret_key = "password"
My test.py is below
from app import app
#app.route('/')
def hello_world():
return 'Hello World!'
I have done export FLASK_APP=app then flask run
My expected out in the browser Hello world
Disclaimer: creating the app.py and adding the below script works perfect. please don't answer like that.But need to upload app.py to another module but need to run app.py
`
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'`
Make a folder let it be testing_flask and add both the app.py and test.py file inside the folder and also make an init file to form an module.
then app.py file look like this:
from flask import Flask
app = Flask(__name__)
app.secret_key = "password"
from testing_flask import test
test.py look like this:
from testing_flask.app import app
#app.route('/')
def hello_world():
return 'Hello World!'
folder structure will be
- testing_flask
|- __init__.py
|- app.py
|- test.py
I am trying to organize my flask project, but there's something wrong.
I have this directory:
app/
__init__.py
views/
pages.py
On my __init__.py file I've imported the pages object and
registered it as a blue print.
This is the code on my pages.py file.
from flask import Blueprint, render_template
pages = Blueprint('pages', __name__) #no prefix
#pages.route('/')
def index():
return '<h1>in index.html</h1>'
#pages.route('/home')
def home():
return '<h1>in home.html</h1>'
If I run the flask app, open the browser, and go to localhost:5000,
I will see the headline 'in index.html'.
But if I go to localhost:5000/home, I will get the message 404 Not Found message.
Does anyone know the reason for this behavior?
Ok, first the folder structure:
app/
__init__.py
main.py
views/
__init__.py
test.py
Contents of main.py:
from flask import Flask
from views.test import pages
app = Flask(__name__)
app.register_blueprint(pages) <-- blueprint registration
Contents of test.py:
from flask import Blueprint
pages = Blueprint('pages', __name__) #no prefix
#pages.route('/')
def index():
return '<h1>in index.html</h1>'
#pages.route('/home')
def home():
return '<h1>in home.html</h1>'
I believe the register_blueprint was the only thing missing.
When stuff like that happen, just turn off everything, reset your computer.
Sometimes the bug is not yours.
How are routes suppose to be handled in flask when using an app factory? Given a package blog that contains everything needed for the app and a management script that creates the app then how are you suppose to reference the app in the routes?
├── blog
├── manage.py
└── blog
├── __init__.py
├── config.py
└── routes.py
manage.py
#!/usr/bin/env python
from flask.ext.script import Manager
manager = Manager(create_app)
# <manager commands>
# ...
# ...
manager.add_option('-c', '--config', dest='config', required=False)
manager.run()
blog/__init__.py
from flask import flask
from .config import Default
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(Default)
if config is not None:
app.config.from_pyfile(config)
return app
blog/routes.py
#app.route() # <-- erm, this won't work now!?
def index():
return "Hello"
The problem is the app is created outside the package so how are the routes suppose to be handled with a setup like this?
Usually I use application factories with blueprint.
blog/__init__.py
from flask import flask
from .config import Default
def create_app(config=None):
app = Flask(__name__)
if config is not None:
app.config.from_pyfile(config)
else:
app.config.from_object(Default)
from blog.routes import route_blueprint
app.register_blueprint(route_blueprint)
return app
blog/routes.py
from flask import Blueprint
route_blueprint = Blueprint('route_blueprint', __name__)
#route_blueprint.route()
def index():
return "Hello"
docs: Application Factories