This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 7 years ago.
I'm tinkering around with Flask to play around with Postgres, and the db stuff is going swimmingly, but vexingly, I cannot get render_template to work. Here are the relevant bits:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/test2/")
def test2():
return render_template('test2.html')
if __name__ == "__main__":
app.debug = True
app.run()
The file test2.html is located in the ./templates directory. When I run the app and hit that url I get jinja2.exceptions.TemplateNotFound
So I've looked at this:
Python - Flask: render_template() not found
And it's not particularly enlightening. My templates folder is next to the application in the directory tree. I'm sure it's something dead simple, but I'm not seeing it.
Well, I'm a dope. Went to git commit my changes on the command line and saw that the templates directory was in the parent directory. It did not look that way in Finder.
Related
I am a Flask beginner, please excuse me if the answer to my question is obvious.
I have been working on a project using an OVH server. I have been using this tutorial to set up a first "Hello world": https://docs.ovh.com/gb/en/web-power/python-install-flask/
Here is the structure of my project :
www/
venv/
myapp.py
At this point, everything is working fine. When I connect to my website, it shows a good "Hello, world !" as expected.
However I now want to add a template to my page, I have therefore added a few lines :
this_file = "venv/bin/activate_this.py"
exec(open(this_file).read(), {'__file__': this_file})
from flask import Flask, render_template
application = Flask(__name__)
#application.route('/')
#application.route('/index')
def index():
return render_template('index.html')
I have imported render_template and changed from "return 'Hello'" to "return render_template('index.html')".
Unfortunately, my website now displays "Incomplete response received from application". I have tried these 2 structures :
www/
venv/
myapp.py
templates/
index.html
and :
www/
templates/
index.html
venv/
myapp.py
But it doesn't change anything... Does any know how to return a template?
instead of starting the venv up from within the program with
this_file = "venv/bin/activate_this.py"
exec(open(this_file).read(), {'__file__': this_file})
(works only on mac/Linux) you might want to do that in the terminal instead,
as
venv/bin/activate
source: https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/
then, to run your file, you can add this:
from flask import Flask, render_template
application = Flask(__name__)
#application.route('/')
#application.route('/index')
def index():
return render_template('index.html')
if __name__ == '__main__':
application.run(debug=True)
the last lines are good habit for projects like these, debugger on is extremely useful. Your structure is fine. I understand why you might want to add the first few lines, I am working on a venv flask app too. However, I tried implementing the windows version of those lines, which did not work... even if that works fine for you, please consider adding
if __name__ == '__main__':
application.run(debug=True)
either way.
The Following is my code hierarchy.
I am trying to create a package for my project, "UIGenerator" but it is giving me following error.
traceback (most recent call last):
File "run.py", line 1, in <module>
from UIGenerator import app
File "/Users/______/Desktop/UIGenerator/UIGenerator/__init__.py", line 2, in <module>
from site.routes import site
ModuleNotFoundError: No module named 'site.routes'; 'site' is not a package
Here is the code for run.py =>
from UIGenerator import app
#app.route('/')
def test_connection():
return "<h1>Connected<h1>"
if __name__ == '__main__':
app.run(debug=True)
There is nothing in site =>__init__.py file and in site=>routes.py, I have some sample code to test-
from flask import Blueprint
site = Blueprint('site', __name__)
#site.route('/site')
def site():
return "this is test for site package"
The following is my code for the UIGenerator's init.py file =>
from flask import Flask
from site.routes import site
def getApp():
app = Flask(__name__)
app.register_blueprint(site)
return app
app = getApp()
Can anyone give me any clue, please.
One way to fix this is to build a Python package with you files, like outlined here. This will be better in the long run if you want to scale this project up, and will allow you to declare things in init
That being said, I think you can get your setup working by moving this chunk of code
def getApp():
app = Flask(__name__)
app.register_blueprint(site)
return app
app = getApp()
to the run.py file for the time being.
So, here is what I found out from a different post. In my site=>routes, I declared a global blueprint with the name, site and later I created a site() function which somehow masked my site blueprint. If I just renamed the site method name, it works.
I have written my 1st Python API project with Flask and now am trying to deploy it to Netlify.
Searched online and found I need to use Flask-Frozen to generate a static website.
Not sure I'm doing it correctly, because my project is a API project not a website project, so may be I should not use Flask-Frozen(FF)?
But if I could still use FF to generate static website for my API project, here is my project:
--
app.py
mazesolver
mazeapi.py
Here is the app.py
from flask_frozen import Freezer
from mazesolver import mazeapi
# Call the application factory function to construct a Flask application
# instance using the development configuration
# app = mazeapi()
# Create an instance of Freezer for generating the static files from
# the Flask application routes ('/', '/breakfast', etc.)
freezer = Freezer(mazeapi)
if __name__ == '__mazeapi__':
# Run the development server that generates the static files
# using Frozen-Flask
freezer.run(debug=True)
mazeapi.py
import io
from mazesolver.solver import MazeSolver
from markupsafe import escape
from flask import Flask, flash, request, redirect, send_file
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = { 'png', 'jpg', 'jpeg' }
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
#app.route('/maze/<mazename>')
def maze(mazename):
return 'maze 4 %s' % escape(mazename)
Whenever I run:
python app.py
I got this error:
Traceback (most recent call last):
File "app.py", line 10, in <module>
freezer = Freezer(mazeapi)
File "/home/winstonfan/anaconda3/envs/maze/lib/python3.7/site-packages/flask_frozen/__init__.py", line 98, in __init__
self.init_app(app)
File "/home/winstonfan/anaconda3/envs/maze/lib/python3.7/site-packages/flask_frozen/__init__.py", line 108, in init_app
self.url_for_logger = UrlForLogger(app)
File "/home/winstonfan/anaconda3/envs/maze/lib/python3.7/site-packages/flask_frozen/__init__.py", line 588, in __init__
self.app.url_default_functions.setdefault(None, []).insert(0, logger)
AttributeError: module 'mazesolver.mazeapi' has no attribute 'url_default_functions'
I had the same issue and added
url_default_functions={}
to the app, right before
if __name__ == "__main__":
app.run()
I guess you could put it right after
app = Flask(__name__)
and the error went way... but there are many more :) It seems that frozen-flask isn't working with the lastest flask, but I couldn't get any other versions working with it.
Did you manage to get it working?
You have a simple namespace bug.
In the code you've posted, you are freezing your module mazeapi, not the actual Flask application, mazeapi.app.
Try changing your Freezer call in line 10 of app.py to:
freezer = Freezer(mazeapi.app)
I'm relatively new to python and am trying to build a flask server. What I would like to do is have a package called "endpoints" that has a list of modules where each module defines a subset of application routes. When I make a file called server.py with the following code this works like so
import os
from flask import Flask
app = Flask(__name__)
from endpoint import *
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
Right now there's only one endpoint module called hello.py and it looks like this
from __main__ import app
# a simple page that says hello
# #app.route defines the url off of the BASE url e.g. www.appname.com/api +
# #app.route
# in dev this will be literally http://localhost:5000/hello
#app.route('/hello')
def hello():
return 'Hello, World!'
So... the above works when I run python server.py, the issue happens when I try to run the app using flask.
Instead of server.py it just calls __init__.py which looks like this
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from endpoint import *
When I run flask run in terminal I get ModuleNotFoundError: No module named 'endpoint'
but again if I change the code so it looks like the following below, then flask run works.
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
# #app.route defines the url off of the BASE url e.g. www.appname.com/api +
# #app.route
# in dev this will be literally http://localhost:5000/hello
#app.route('/hello')
def hello():
return 'Hello, World!'
I'm pretty sure this is happening because I don't fully understand how imports work...
So, how do I set up __init__.py so that it imports all the modules from the "endpoint" package and works when I call flask run?
When you use a __init__.py file, which you should, Python treats the directory as a package.
This means, you have to import from the package, and not directly from the module.
Also, usually you do not put much or any code in a __init__.py file.
Your directory structure could look like this, where stack is the name of the package I use.
stack/
├── endpoint.py
├── __init__.py
└── main.py
You __init__.py file is empty.
main.py
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from stack.endpoint import *
endpoint
from stack.main import app
# a simple page that says hello
# #app.route defines the url off of the BASE url e.g. www.appname.com/api +
# #app.route
# in dev this will be literally http://localhost:5000/hello
#app.route('/hello')
def hello():
return 'Hello, World!'
You can then run your app...
export FLASK_APP=main.py
# followed by a...
flask run
This all said, when I create a new Flask app, I usually only use one file, this makes initial development easier, and only split into modules when the app really grows bigger.
Also, for separating views or let's call it sub packages, Flask offers so called Blue prints. This is nothing you have to worry about right now, but comes especially handy when trying to split the app into sub applications.
I've encountered an issue while trying to access PostgreSQL from heroku python console (first attempt).
First up, I launch python using $ heroku run python
Then I try to load up the db module with >>> from app import db, this action returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named app
I have one web dyno running python which has app = Flask(__name__), apart from that, I don't know what other details should I provide in order to shed more light into the issue.
After experimenting with the terminal, it became clear, that there really is no way for it to know what variables do I have in my main.py, so what I did then was load the main parts of the app through the terminal like so:
>>> import os
>>> from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
>>> from flask.ext.sqlalchemy import SQLAlchemy
>>> # create the application
>>> app = Flask(__name__)
>>> app.config.from_object(__name__)
>>> app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'some-url.com')
>>> db = SQLAlchemy(app)
And from then on I was able to access the db object as intended.
EDIT - the issue completely resolved below.
So the reason I was having an error while trying to import my apps code into the python shell was two fold:
The *.py that was the target of my import was not at the root directory, I was telling the shell to look in the wrong place.
Since the *.py I was importing was not named app.py (and I was asking to from app import db), I was also telling the shell to look for the wrong file.
The way to solve this issue was to append the path of my *.py file to the sys.path and instead of from app import db, us from my_filename_without_the_extenssion import db. For a summary, the shell received these instructions:
>>> import sys
>>> sys.path.append('path/to/my/file')
>>> from my_filename_without_the_extenssion import db
>>> # to test if everythings ok
>>> db