My hello world flask program is not running? - python

I'm a beginner in Flask, And i'm trying to create a simple hello world program but it's giving me errors on everytime with Undefined variable from import: run.
Here is my directory looks like:
/MyApplicationName:
/app
/__init__.py
/views.py
/run.py
My __init__.py is:
from flask import Flask
app = Flask(__name__)
import views
Here is my views.py:
from app import app
#app.route("/")
#app.route("/index")
def main():
return "Hello Flask!!"
Here is my last one run.py:
from app import app
if __name__ == "__main__":
app.run(debug=True)
Every time it gives me this error:
Undefined variable from import: run.
HELP WOULD BE APPRECIATED

Move:
from flask import Flask
app = Flask(__name__)
to views.py. Then make __init__.py:
from views import app
You have a circular import, but I'm not exactly sure as to why it's throwing the error it's throwing.

Have a look at flask-script, anyway evaluate to use a factory, something like create_app() that returns an app object.
It seems to be the common practice when using flask:
def create_app():
app = Flask(
'portal', static_folder='static/build', static_url_path='/static'
)
init_config(app)
init_login(app)
init_csrf(app)
app.register_blueprint(views)
return app

Without changing a single line of what you've coded, just move run.py out of the app directory.
Your project directory should look then like this:
└── MyApplication
├── __init__.py
├── app
│   ├── __init__.py
│   ├── views.py
└── run.py
Happy coding,
J.

Related

Flask Blueprint already registered

I have a flask app, (following tutorial https://www.youtube.com/watch?v=dam0GPOAvVI) - I am getting the error
'ValueError: The name 'views' is already registered for a different blueprint. Use 'name=' to provide a unique name.
init.py:
def create_app():
app = Flask(__name__)
from .views import views
app.register_blueprint(views, url_prefix='/')
return app
this is views
from flask import Blueprint
views = Blueprint('views', __name__)
#views.route('/')
def home():
return '<h1>test/h1>'
my folder structure, and the main.py file I am calling.
C:.
│ main.py
│
└───website
│ views.py
│ __init__.py
from website import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
my best guess would be something along the lines of the app not un-registering the previous blueprint from the last time it was ran, but I doubt it would be something so simple. Any help would be appreciated.

How should the startup of a flask app be structured?

I have built a flask app that I have been starting from an if __name__ == '__main__': block, as I saw in a tutorial. When the time came to get the app to launch from wsgi for production use, I had to remove the port and host options from app.run(), and make changes to the structure of the launching code that I am not too sure about. I am now adding test cases, which adds more ways to launch and access the app (with app.test_client(), with app.test_request_context(), and who knows what else.) What is the right / recommended way to structure the code that creates and launches the application, so that it behaves correctly (and consistently) when launched stand-alone, from wsgi, and for testing?
My current structure is as follows:
def create_app():
"""
Create and initialize our app. Does not call its run() method
"""
app = Flask(__name__)
some_initialization(app, "config_file.json")
return app
app = create_app()
...
# Services decorated with #app.route(...)
...
if __name__ == "__main__":
# The options break wsgi, I had to use `run()`
app.run(host="0.0.0.0", port=5555)
To be clear, I have already gotten wsgi and tests to work, so this question is not about how to do that; it is about the recommended way to organize the state-creating steps so that the result behaves as a module, the app object can be created as many times as necessary, service parameters like port and server can be set, etc. What should my code outline actually look like?
In addition to the launch flag issue, the current code creates an app object (once) as a side effect of importing; I could create more with create_app() but from mycode import app will retrieve the shared object... and I wonder about all those decorators that decorated the original object.
I have looked at the documentation, but the examples are simplified, and the full docs present so many alternative scenarios that I cannot figure out the code structure that the creators of Flask envisioned. I expect this is a simple and it must have a well-supported code pattern; so what is it?
Disclaimer While this isn't the only struture for Flask, this has best suited my needs and is inspired from the Flask officials docs of
using a Factory
Pattern
Project Structure
Following the structure from the Documentation
/home/user/Projects/flask-tutorial
├── flaskr/
│ ├── __init__.py
│ ├── db.py
│ ├── schema.sql
│ ├── auth.py
│ ├── blog.py
│ ├── templates/
│ │ ├── base.html
│ │ ├── auth/
│ │ │ ├── login.html
│ │ │ └── register.html
│ │ └── blog/
│ │ ├── create.html
│ │ ├── index.html
│ │ └── update.html
│ └── static/
│ └── style.css
├── tests/
│ ├── conftest.py
│ ├── data.sql
│ ├── test_factory.py
│ ├── test_db.py
│ ├── test_auth.py
│ └── test_blog.py
├── venv/
├── setup.py
└── MANIFEST.in
flaskr/, a Python package containing your application code and files.
flaskr will contain the factory to generate flask app instances that can be used by WGSI servers and will work with tests, orms (for migrations) etc.
flaskr/__init__.py contains the factory method
The Factory
The factory is aimed at configuring and creating a Flask app. This means you need to pass all required configurations in one of the many ways accepted by Flask
The dev Flask server expects the function create_app() to be present in the package __init__.py file. But when using a production server like those listed in docs you can pass the name of the function to call.
A sample from the documentation:
# flaskr/__init__.py
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():
return 'Hello, World!'
return app
when running a dev flask server, set environment variables as described
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask run
The Routes
A Flask app may have multiple modules that require the App object for functioning, like #app.route as you mentioned in the comments. To handle this gracefully we can make use of Blueprints. This allows us to keep the routes in a differnt file and register them in create_app()
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
simple_page = Blueprint('simple_page', __name__,
template_folder='templates')
#simple_page.route('/', defaults={'page': 'index'})
#simple_page.route('/<page>')
def show(page):
try:
return render_template(f'pages/{page}.html')
except TemplateNotFound:
abort(404)
and we can modify the create_app() to register blueprint as follows:
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
# configure the app
.
.
.
from yourapplication.simple_page import simple_page
app.register_blueprint(simple_page)
return app
You will need to locally import the blueprint to avoid circular imports. But this is not graceful when having many blueprints. Hence we can create an init_blueprints(app) function in the blueprints package like
# flaskr/blueprints/__init__.py
from flaskr.blueprints.simple_page import simple_page
def init_blueprints(app):
with app.app_context():
app.register_blueprint(simple_page)
and modify create_app() as
from flaskr.blueprints import init_blueprints
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
# configure the app
.
.
.
init_blueprints(app)
return app
this way your factory does not get cluttered with blueprints. And you can handle the registration of blueprints inside the blueprint package as per your choice. This also avoids circular imports.
Other Extensions
Most common flask extensions support the factory pattern that allows you to create an object of an extension and then call obj.init_app(app) to initialize it with Flask App. Takeing Marshmallow here as an exmaple, but it applies to all. Modify create_app() as so -
ma = Marshmallow()
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
# configure the app
.
.
.
init_blueprints(app)
ma.init_app(app)
return app
you can now import ma from flaskr in which ever file required.
Production Server
As mentioned initialially, the production WSGI serevrs will call the create_app() to create instances of Flask.
using gunicorn as an example, but all supported WSGI servers can be used.
$ gunicorn "flaskr:create_app()"
You can pass configurations as per gunicorn docs, and the same can be achieved within a script too.
What I did was:
class App:
def __init__(self):
# Various other initialization (e.g. logging, config, ...)
...
self.webapp = self._start_webapp(self.app_name, self.app_port, self.log)
pass
def _start_webapp(self, app_name: str, app_port: Optional[int], log: logging):
log.info('Running webapp...')
webapp = Flask(app_name)
# other flask related code
...
webapp.run(debug=False, host='0.0.0.0', port=app_port)
return webapp
pass
if __name__ == '__main__':
app = App()
This way you can add optional parameters to the init to override during tests or override via config change and even create additional types of endpoints in the same application, if you need.

How to import blueprints with the same name as the file they are in?

Background
I'm trying to set up a blueprint whose name matches the filename it resides in, so that when I reference it in my app.py I know where the blueprint comes from. This should be possible because the example on exploreflask uses the same pattern. Still, I cannot figure out how to make this work with my structure.
File structure
├── app.py
├── frontend
   ├── __init__.py
   └── views
   ├── home.py
   └── __init__.py
Example
frontend/views/home.py
from flask import Blueprint, render_template
home = Blueprint('home', __name__)
home1 = Blueprint('home1', __name__)
frontend/views/__init__.py
from .home import home
from .home import home1
app.py
from flask import Flask
from frontend.views import home
from frontend.views import home1
print (type(home)) --> <class 'function'>
print (type(home1)) --> <class 'flask.blueprints.Blueprint'>
As home1 registers correctly as a Blueprint but home does not I suspect that
there is a name collision but I don't know how to resolve it despite looking into
this excellent article on importing conventions.
As a result, when I try to register my blueprints with the app
this will work:
app.register_blueprint(home1, url_prefix='/home1') --> Fine
but this won't:
app.register_blueprint(home, url_prefix='/home')
--> AttributeError: 'function' object has no attribute 'name'
Why not just go along with using home1?
I want to understand how the collision can be resolved
I want to be able to use route names that are the same as the filename they are in like so:
frontend/views/home.py
from flask import Blueprint, render_template
home = Blueprint('home', __name__)
#home.route('/')
def home():
pass
I think your views/__init__.py file is causing this issue. It's making python assume your home.py file is a module to be imported. I believe the line from frontend.views import home is trying to import the home.py file rather than your intended home.home Blueprint.
Here's a working example:
/app.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
/app/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
from .bp import bp
app.register_blueprint(bp)
return app
/app/bp/__init__.py
from flask import Blueprint
bp = Blueprint('bp', __name__, template_folder='templates')
from . import views
/app/bp/views.py
from app.bp import bp
#bp.route('/helloworld')
def helloworld():
return "hello world"
Try to use Capital letters in the Blueprint Module.
also you can use the url_prefix in the module.
Home = Blueprint("Home", __name__, url_prefix="/home")
#Home.route("/")
def home():
pass

Object is not imported properly in a Flask structure

I'm trying to learn Flask from Instant Flask Web Development book following it step-by-step but I get the error presented below.
(It seems to be a problem with circular imports.)
The questions are:
Can someone explain what would be the fix and detail the circular imports?
Directory structure:
├── manage.py
├── requirements.txt
└── sched
├── __init__.py
├── __init__.pyc
├── app.py
├── app.pyc
├── static
└── templates
manager.py:
from flask.ext.script import Manager
from sched import app
manager = Manager(app)
app.config['DEBUG'] = True
if __name__ == '__main__':
manager.run()
app.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
__init__.py is ampty.
Command line generated error:
$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 8, in <module>
app.config['DEBUG'] = True
AttributeError: 'module' object has no attribute 'config'
When you do
from sched import app
you are importing the app module. The app object is inside the module. The import you want to use is
from sched.app import app
Alternative architecture :
# app.py:
from flask import Flask
app = Flask(__name__)
app.debug = True
from flask.ext.script import Manager
manager = Manager(app)
# __init__.py:
from .sched import app, manager
import sched.views # for your views
import sched.commands # for additional commands
# manager.py:
from sched import manager
if __name__ == '__main__':
manager.run()
#views.py:
from .app import app
#app.route('/')
def hello_world():
return 'Hello World!'
I suggest following an app factory pattern for your app.
manage.py
sched/
__init__.py
in __init__.py you can do the following:
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['DEBUG'] = True
return app
in manage.py
from app import create_app
from flask.ext.script import Manager
app = create_app()
manager = Manager(app)
if __name__ == '__main__':
manager.run()
This tends to be an extensible solution for larger application structures.

flask : how to architect the project with multiple apps?

Lets say I want to build a project Facebook
I need a project structure like
facebook/
__init__.py
feed/
__init__.py
models.py
business.py
views.py
chat/
__init__.py
models.py
business.py
views.py
games/
__init__.py
models.py
business.py
views.py
common/
common.py
runserver.py
How can I structure this well so that when I run
python facebook/runserver.py
It loads views from all my apps internally?
I want to keep this structure because extending the project further is more natural way
I am trying to follow their advice, but don't really understand where I need to write
from flask import Flask
app = Flask(__name__)
and how to import all views from all apps at one place, please help
If lets say I write the above code in facebook/__init__.py, then how in facebook/feed/views.py, I can do
from facebook import app
Use blueprints. Each one of your sub-applications should be a blueprint, and you load every one of them inside your main init file.
Answering your second question
from flask import Flask
app = Flask(__name__)
You should put this into facebook/__init__.py
BTW, my runserver.py and settings.py always resides one level under facebook/.
Like this:
facebook/
__init__.py
feed/
__init__.py
models.py
business.py
views.py
chat/
__init__.py
models.py
business.py
views.py
games/
__init__.py
models.py
business.py
views.py
common/
common.py
runserver.py
settings.py
Content of runserver.py:
from facebook import app
app.run()
I suppose the content of settings.py should not be explained.
Content of facebook/__init__.py:
from flask import Flask
app = Flask(__name__)
app.config.from_object('settings')
from blog.views import blog #blog is blueprint, I prefer to init them inside views.py file
app.register_blueprint(blog,url_prefix="/blog")
I have tried blueprints and came up with a solution which works for me, let me know if you have other ideas.
Project Structure
facebook/
runserver.py
feed/
__init__.py
views.py
chat/
__init__.py
views.py
Code
# create blueprint in feed/__init__.py
from flask import Blueprint
feed = Blueprint('feed', __name__)
import views
# create blueprint in chat/__init__.py
from flask import Blueprint
chat = Blueprint('chat', __name__)
import views
# add views (endpoints) in feed/views.py
from . import feed
#feed.route('/feed')
def feed():
return 'feed'
# add views (endpoints) in chat/views.py
from . import chat
#chat.route('/chat')
def chat():
return 'chat'
# register blueprint and start flask app
from flask import Flask
from feed import feed
from chat import chat
app = Flask(__name__)
app.register_blueprint(feed)
app.register_blueprint(chat)
app.run(debug=True)
In Action
* Running on http://127.0.0.1:5000/
# Hit Urls
http://127.0.0.1:5000/feed # output feed
http://127.0.0.1:5000/chat # output chat

Categories