Reputation: 2067
I want to make flask project to large project structure so I found sample project like following
~/LargeApp
|-- run.py
|-- config.py
|__ /env # Virtual Environment
|__ /app # Our Application Module
|-- __init__.py
|-- /module_one
|-- __init__.py
|-- views.py
|-- models.py
|__ /templates
|__ /module_one
|-- hello.html
|__ /static
|__ ..
|__ .
|__ ..
|__ .
I write create_app function in /app/init.py
def create_app():
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.logger = my_get_logger_function() # this function set log level, and add handler to logger and return logger
db.init_app(app)
from .module_one.views import mod as module_one_blueprint
app.register_blueprint(module_one_blueprint)
return app
and I want to use logger in my /app/module_one/views.py, following is my views.py file
from app import logger
...
@mod.route('/test/', methods=['GET'])
def test():
logger.info('test')
but when i run, i got message "ImportError: cannot import name 'logger"
I know it's because I call logger in views.py before app was created
but i really don't know how i fix it and how do i design a my project
Upvotes: 3
Views: 516
Reputation: 153
Try this : from flask.logging import logging
I also had this problem, I don't know why, but I tried it and it worked well.
Upvotes: 0
Reputation: 669
Really the error is due to you have not defined the name logger
in your module app
. If you want to use the app logger, you should import the current_app
from flask
which is the instance of your app as follows:
from flask import current_app
Then, in your view, you can use the logger:
current_app.logger.info('Your message')
Upvotes: 3