flask server won't run if I named my application factory function other than "create_app" - python

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.

Related

How to run the #app.route from other file

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

How to run Flask app by flask run with blueprint template

In a Python authorization app, in my main py I have the following code:
# main.py
from flask import Blueprint, render_template
from flask_login import login_required, current_user
theapp = Blueprint('main', __name__)
#theapp.route('/')
def index():
return render_template('index.html')
When I try:
FLASK_APP=main.py
FLASK_DEBUG=1
flask run
I get the following error:
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
Basically a Blueprint is a way for you to organize your flask application into smaller and reusable applications. I am not sure why you have used it here in the main.py.
You could do that some other file, for example, you have a set of endpoints to implement login functionality in a separate file then what you should be doing is:
Assume you have a login.py .Sample Code looks like follows:
from flask import Blueprint
bp = Blueprint('login_bp', __name__)
def login_bp():
return bp
And the following code goes into you main.py , you need to start the Flask Server using .run()
from flask import Flask
from flask import Blueprint, render_template
from login import login_bp #Assume you have a module login and I am importing login_bp from login.py
theapp = Flask(__name__) #Creating Flask instance
theapp.register_blueprint(login_bp()) # Registering Blueprint here
#theapp.route('/')
def index():
return render_template('index.html')
theapp.run(host="0.0.0.0", port=2019, debug=True) #Starting the Flask Server
Hope this works, please do look out for documents and code example to get deeper insights.

Order of registering Flask Blueprints

I ran into a strange issue (maybe not so strange for experienced in flask).
I have a flask application running in the context of Google App Engine's dev_appserver.py
I have a blueprint in my flask application
# rest_server.py
rest_api = Blueprint('rest_api', __name__)
app = Flask(__name__)
app.register_blueprint(rest_api, url_prefix='/api') # [1] DOESN'T WORK
#rest_api.route("/")
def hello():
return "Hello World"
app.register_blueprint(rest_api, url_prefix="/api") # [2] WORKS AS EXPECTED
I have the following in my app.yaml
-url: "/api/.*"
script: rest_server.app
When I hit localhost:8080/api/ when I register blueprint at position [1], I get an error saying there is no matching endpoint.
However, when I register bluerpint at [2], any position after the decorator, it works.
Is it required to register the blueprint after all the decorators?
Yes, it's required to register blueprints only after all their routes have been declared, at least if you want to use those routes. (If you don't mind the routes not being available, it doesn't look like there's actually any problem with declaring new routes after registering the blueprint.)
If you want to know why: basically, blueprint url rules are only registered on the application when Flask.register_blueprint is called. If you add routes after registering the blueprint, they just get added to the list of things to do when the blueprint is registered (Blueprint.deferred_functions), they don't get retroactively added to any existing applications that the blueprint was registered to in the past.
Though you have registered your blueprint, it is not actually registered!
the point is that your application is not aware of existence rest_server.py
You have to register it in the same file in which you have the following code:
app = Flask(__name__)
This should solve your problem.
I'd like to show the pattern of using blueprints I use.
(It is useful for a better organization of your code) :
Blueprint Pattern
your application can look like this:
/yourapplication
runserver.py
/application #your application is a package containing some blueprints!
__init__.py
models.py
/hello #(blueprint name)
__init__.py
views_file1.py
views_file2.py
your runserver.py should look like this:
# runserver.py
from application import app
app.run()
In this example, hello is a package and one of your blueprints:
# application/hello/__init__.py
from flask import Blueprint
hello = Blueprint('main', __name__)
# import views of this blueprint:
from application.hello import views_file1, views_file2
Import and register your blueprints in application/__ init__.py. your application/__ init__.py should look like this:
# application/__init__.py
from flask import Flask
from .hello import hello as hello_blueprint
app = Flask(__name__)
app.register_blueprint(hello_blueprint)
from application.models import * #your models (classes, or *)

Configure module logger to flask app logger

My flask application uses a module which gets a logger like this:
import logging
logger = logging.getLogger("XYZ")
...
logger.debug("stuff")
Without having to modify anything in the module, can I configure flask such that the module will get flask's app.logger when it makes the getLogger("XYZ") call?
This solution worked to me:
import logging
logger = logging.getLogger('werkzeug')
logger.debug('stuff')
The default Flask configuration seems to use the logger name werkzeug. Adding or changing handlers for this logger changes the way Flask logs.
PS.: Python 3.5, Flask 0.12.2
The Flask logger is accessible during a request or CLI command via current_app.
Example usage:
from flask import current_app, Flask
app = Flask('HelloWorldApp')
#app.route('/')
def hello():
current_app.logger.info('Hello World!')
return "Hello World!"
if __name__ == '__main__':
app.run()
If you want use your Flask apps logging instance that is already established then all you have to do is import the current app and give it a name for that module.
init.py
from flask import Flask
my_app = Flask(__name__)
my_other_module.py where I want to use Flask app logger
from flask import current_app as my_app
class myClass():
def __init__(self):
constructor stuff....
def my_class_method(self):
my_app.logger.info("log this message")
Yes, you can configure it.
By default flask logger's name is your app name, but flask has setting LOGGER_NAME.

NameError: name 'app' is not defined with Flask

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!"

Categories

Resources