I am trying to run the server of this repository (it's about oauth2): https://github.com/lepture/flask-oauthlib/blob/master/tests/oauth2/server.py
The main file looks like this:
if __name__ == '__main__':
from flask import Flask
app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
app.config.update({
'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.sqlite'
})
app = create_server(app)
app.run()
However, I am getting this error:
Error: Failed to find Flask application or factory in module 'hello'. Use 'FLASK_APP=hello:name' to specify one.
I executed the following commands in terminal:
export FLASK_APP=server.py` and
export FLASK_APP=main.py
After that, I tried rerunning with flask run
Again, I am getting this error:
Error: Failed to find Flask application or factory in module 'main'. Use 'FLASK_APP=main:name' to specify one.
Try this code
from flask import Flask
app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
app.config.update({
'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.sqlite'
})
if __name__ == '__main__':
app.run(host="0.0.0.0", port="5000", debug=True)
You should run it directly
python server.py
And if you want to use flask run then you would have to put all (except app.run()) before if __name__ == '__main__': because flask run will import this file and import will skip code inside if __name__ == '__main__':
# ... other code ...
from flask import Flask
app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
app.config.update({
'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.sqlite'
})
app = create_server(app)
if __name__ == '__main__':
app.run()
And it will need export FLASK_APP=server:app because you want to run file server.py and use instance of Flask() with name app
export FLASK_APP=server:app
flask run
Because code uses standard name app so you could skip it in export
export FLASK_APP=server
flask run
You can also run without export
flask --app server run
Try this one:
But I recommend you to start with the basics before work with databases. Try to render HTML templates, use bootstrap, etc. You are running here. Anyway, this boilerplate works for me.
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
# Key for Forms
app.config['SECRET_KEY'] = 'mysecretkey'
# SQL DATABASE AND MODELS
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db)
class Puppy(db.Model):
__tablename__ = 'puppies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
#app.route('/')
def index():
return '<h1>Hello Puppy!</h1>'
if __name__ == '__main__':
app.run(debug=True)
Related
I would like to call the create_app method from my run.py and then use it to start a Flask server. However, when I try this it does not start and no output appears in the console. Can someone help me with this?
main.py
from flask import Flask
from flask_restx import Api
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_cors import CORS
def create_app():
app = Flask(__name__, static_url_path='/',static_folder='./UI/client/build')
bootstrap = Bootstrap(app)
app.config.from_object('settings')
app.secret_key = os.urandom(24)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
csrf = CSRFProtect(app)
CORS(app)
JWTManager(app)
api=Api(app,doc='/docs')
#app.route('/')
def index():
return app.send_static_file('index.html')
#app.errorhandler(404)
def not_found(err):
return app.send_static_file('index.html')
return app
run.py
from main import create_app
app=create_app()
With the following code I was able to start flask:
if __name__ == '__main__':
app = create_app()
app.run()
I'm trying to deploy a flask app on AWS Lambda using Zappa. However, when I call zappa deploy dev, I'm getting an error. After examining the logs, I've found that the error is being caused when the code runs db.create_all() within my create_database() function. The database isn't being created which is strange because when I run it locally, it works fine. I'm including the code for my application and a stack trace of the error below.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
db = SQLAlchemy()
DB_NAME = 'database.db'
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdfghjkl'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
db.init_app(app)
from .views import views
app.register_blueprint(views, url_prefix = '/')
from .models import User
create_database(app)
login_manager = LoginManager()
login_manager.login_view = 'views.home'
login_manager.init_app(app)
#login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app
def create_database(app):
if not path.exists('website/' + DB_NAME):
db.create_all(app = app) #where error is occuring
print('Created Database')
After running zappa deploy/update dev:
Any help would be appreciated!
My code structure. I tried but kept getting error cannot import name 'caching'. I guess my method isn't correct as caching will not have app initiation when I import caching in external file.
xyz
-app.py
-run.py
-urls
-v2.py
-resource
-views.py
-external.py
run.py
from app import create_app
if __name__ == "__main__":
career_app = create_app()
career_app.run(host=HOST,
port=PORT,
debug=True)
app.py
from flask import Flask
from flask_caching import Cache
caching = Cache(config={'CACHE_TYPE': 'simple'})
def create_app():
"""Create web app."""
app = Flask(__name__)
configure_app(app)
caching.init_app(app)
setup_blueprints(app)
return app
external.py
from app import caching
v1.py
v2_api.add_resource(UserConfigView, '/user/config',
endpoint='user_config_view')
It is a simple factory app setup
ext.py
from flask_caching import Cache
cache = Cache()
app.py
def create_app():
app = Flask(__name__)
register_extensions(app)
...
def register_extensions(app):
cache.init_app(app, config=settings.params.CACHE_CONFIG)
I created a Flask app with SQLAlchemy.
I initialised the database in app.py but I want to use it in another file: otherfile.py.
app.py
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database'
db = SQLAlchemy(app)
print("TEST")
otherfile.py
from app import db
print(db)
But I get the error.
ImportError: cannot import name 'db'
Basically, I am doing this because I do not want to write the SQLAlchemy logic in app.py but I want to keep it in another file.
In addition, I just want the variable db to be exported. I do not want that when I run otherfile.py, this runs also print("TEST") which is in app.py
I looked at these answer with little luck:
How to share the global app object in flask?
Split Python Flask app into multiple files
How to divide flask app into multiple py files?
The SQLAlchemy class doesn't need to receive the app param on its initialization. So what you can do is create the db object in your otherfile.py and import it in app.py, where you can pass it the app object with SQLAlchemy.init_app().
app.py
from flask import Flask
from otherfile import db
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database'
db.init_app(app)
otherfile.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
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!"