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
Related
I am trying to structure a flask API application to separate routes and create tests for each of these routes in the same application. Ultimately, my objective is to have a gitlab runner file automate this eventually. This is currently what the structure looks like:
my-flask-application:
- venv:
- gitlab-ci.yml
- requirements.txt
- app:
|- app.py
|- routes
|- home.py
|- square.py
|- ...
- test:
|- test_home.py
|- test_square.py
|- ...
Here are the files:
(1) app.py
#app.py
from flask import Flask
from app.routes.home import home_bp
from app.routes.square import square_bp
app = Flask(__name__)
API_PREFIX = "/api/v1"
app.register_blueprint(home_bp, url_prefix=API_PREFIX)
app.register_blueprint(square_bp, url_prefix=API_PREFIX)
if __name__ == '__main__':
app.run(debug=True)
(2) home.py
#home.py
from flask import Blueprint, jsonify
home_bp = Blueprint('home', __name__)
#home_bp.route('/home')
def home():
return jsonify({'message': 'Welcome to the home page!'}), 200
(3) test_home.py
import unittest
from flask import Flask, jsonify
# Need help importing the app or routes
class TestCase(unittest.TestCase):
test_app = Flask(app)
# Need help with an example of a unit test
if __name__ == '__main__':
unittest.main()
Ultimately, I need help (1) figuring out how to import the application into the test file, and (2) learn how to structure the test files effectively so that I can ultimately run it automatically using a runner file (this can come later).
Thanks!
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")
My server will run if I name application factory function as create_app like this:
def create_app():
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello, World!'
return app
but naming it other than create_app, will throw an error Failed to find Flask application or factory
def foo_app():
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello, World!'
return app
changing the case will also throw the same error, like this:
def Create_app():
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello, World!'
return app
Is this behavior is normal? or is there something wrong in my setup?
this is my project layout:
...\projects\mainfoo
|--packagefoo
| |--__init__.py
|--venvfiles
in the cmd,
...\projects\mainfoo>set FLASK_APP=packagefoo
...\projects\mainfoo>set FLASK_ENV=development
...\projects\mainfoo>flask run
I just follow this tutorial Project Layout & Application setup
From the flask documentation
$ export FLASK_APP=hello
$ flask run
While FLASK_APP supports a variety of options for specifying your
application, most use cases should be simple. Here are the typical
values:
(nothing)
The name “app” or “wsgi” is imported (as a “.py” file, or
package), automatically detecting an app (app or application) or
factory (create_app or make_app).
FLASK_APP=hello
The given name is imported, automatically detecting an
app (app or application) or factory (create_app or make_app).
You cannot customize this behavior, as its a specification in flask to follow.
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.
I have the following structure in my project
\ myapp
\ app
__init__.py
views.py
run.py
And the following code:
run.py
from app import create_app
if __name__ == '__main__':
app = create_app()
app.run(debug=True, host='0.0.0.0', port=5001)
views.py
#app.route("/")
def index():
return "Hello World!"
_init_.py
from flask import Flask
def create_app():
app = Flask(__name__)
from app import views
return app
I'm trying to use the factory design pattern to create my app objects with different config files each time, and with a subdomain dispatcher be able to create and route different objects depending on the subdomain on the user request.
I'm following the Flask documentation where they talk about, all of this:
Application Context
Applitation Factories
Application with Blueprints
Application Dispatching
But I couldn't make it work, it seems that with my actual project structure there are no way to pass throw the app object to my views.py and it throw and NameError
NameError: name 'app' is not defined
After do what Miguel suggest (use the Blueprint) everything works, that's the final code, working:
_init.py_
...
def create_app(cfg=None):
app = Flask(__name__)
from api.views import api
app.register_blueprint(api)
return app
views.py
from flask import current_app, Blueprint, jsonify
api = Blueprint('api', __name__)
#api.route("/")
def index():
# We can use "current_app" to have access to our "app" object
return "Hello World!"