How can I create sql dump for a flask application - python

I would like to export or import sql db from a flask application. After searching I found the following package which is supposed to do the job.
https://pypi.org/project/Flask-AlchemyDumps/
But it seems it doesn't work with flask now .
Thats what I have tried
from flask import Flask
from flask_login import LoginManager
from flask_migrate import Migrate
from flask.ext.alchemydumps import AlchemyDumps, AlchemyDumpsCommand
from flask.ext.script import Manager
from flask_sqlalchemy import SQLAlchemy
from commands import create_tables
from config import Config
db = SQLAlchemy()
app = Flask(__name__)
manager = Manager(app)
# init Alchemy Dumps
alchemydumps = AlchemyDumps(app, db)
manager.add_command('alchemydumps', AlchemyDumpsCommand)
I get this error ModuleNotFoundError: No module named 'flask.ext'
Is there any alternatives available?

Related

ModuleNotFoundError Cannot import from app.__init__.py

I'm trying to setup a flask application which runs on Python 3.7.x. I've referenced many tutorials online but can't seem to resolve this ModuleNotFoundError and none of the stackoverflow questions are related.
Below is my project structure:
project/
app/
__init__.py
api.py
conf.py
models.py
schema.py
orders-mgmt.toml
requirements.txt
README.md
# app/__init__.py
from flask import Flask
from flask_restful import Api
from app.conf import load_from_toml
import logging
import os.path
if os.path.isfile('/opt/project/orders-mgmt.toml'):
config = load_from_toml('/opt/project/orders-mgmt.toml')
else:
config = load_from_toml()
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = config['mysql']['db_uri']
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
'pool_recycle': 3000,
'pool_pre_ping': True,
}
# app/api.py
from flask import jsonify
from flask_restful import Resource
from flask_sqlalchemy import SQLAlchemy
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema
db = SQLAlchemy(app)
class TestGet(Resource):
def get(self):
return 'okay'
api.add_resource(TestGet, '/')
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=5000)
I'm getting the ModuleNotFoundError in app/api.py line from app import app, api, config when I run python app/api.py:
$ python app/api.py
Traceback (most recent call last):
File "app/api.py", line 4, in <module>
from app import app, api, config
ModuleNotFoundError: No module named 'app'
May I know what is the issue here with my flask application?
You have circular dependency issue
Your app will not work in such files structure
Remove logic from init module to another one OR you'll need to remove all absolute imports(imports for your own modules) and replace them with relative
for __init__ module
replace this line:
from app.conf import load_from_toml
with
from .conf import load_from_toml
for app module
replace these lines:
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema
with
from . import app, api, config
from .models import Request
from .schema import RequestSchema

Cannot import database models in interactive terminal within Flask app context

I'm trying to test my database how it behaves in a many-to-many relationships. I'm struggling to access the application context of the Flask app.
I ran the Python terminal in the parent folder of the app and followed the steps found on SO and elsewhere. I could manage (i think) to import the app, create it, push the context, import the db. However, whenever I want to import models I'm prompted with a:
Error ModuleNotFoundError: No module named 'db'
Despite the fact that db is definately defined:
This is the screenshot of the complete process.
The folder structure is:
- app
--__int__.py
This is the app/init.py file:
from flask import Flask,Blueprint
from flask_sqlalchemy import SQLAlchemy
from app.config import Config
from mailjet_rest import Client
db = SQLAlchemy()
mailjet = Client(auth=(Config.MJ_APIKEY_PUBLIC, Config.MJ_APIKEY_PRIVATE), version='v3.1')
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
from app.views.users import users
from app.views.data import data
from app.views.admin import admin
app.register_blueprint(users,url_prefix='/users')
app.register_blueprint(data,url_prefix='/data')
app.register_blueprint(admin,url_prefix='/admin')
# with app.app_context():
# db.create_all()
return app
I'd greatly appreciate any input!
Thank you,
Matija
The solution was quite simple. I ought to import models from app.models and not from db.
The steps I took:
Rename the folder to app
Ran Flask shell command on the app level
Imported app
Import models from app.models

Flask Application Circular Dependencies

I am developing a Flask application, and I am not sure why I am getting this error:
File "app.py", line 17, in <module>
from endpoints.users.resource import UserResource
File "{basedir}/endpoints/users/resource.py", line 4, in <module>
from .model import User
File "{basedir}/endpoints/users/model.py", line 1, in <module>
from app import db
File "{basedir}/app.py", line 17, in <module>
from endpoints.users.resource import UserResource
ImportError: cannot import name 'UserResource' from 'endpoints.users.resource' ({basedir}/endpoints/users/resource.py)
I believe it is due to a circular dependency, from looking at the error, but I can't figure out why, because I think that the order in which I am importing things in my code should have circumvented this issue:
app.py:
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
api = Api(app)
api.prefix = '/api'
from endpoints.users.resource import UserResource
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from app import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from .model import User
from app import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
In app.py, since I am importing from endpoints.users.resource after db is created, shouldn't that circumvent the circular dependency?
In addition, I can run this with flask run but when I try to use python app.py, then it gives me the above error. Why would these give different results?
So on from endpoints.users.resource import UserResource line python tries to import from app import db line to app.py which causes app reference to itself, which is not good at all.
One workaround to solve circual import errors in Flask is using init_app function which exists in most of Flask apps. So just create database file like this:
database.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app.py
from flask import Flask
from flask_restful import Api
from database import db
from endpoints.users.resource import UserResource
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
api = Api(app)
api.prefix = '/api'
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from database import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from endpoints.users.model import User
from database import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
Note that I rewrote your imports from related, so don't forget to add __init__.py files
Your structure will be like this:
.
├── app.py
└── database.py/
└── endpoints/
├── __init__.py
└── users/
├── __init__.py
├── model.py
└── resource.py

I cannot get file import to work in my python flask app

I am using AWS cloud9 IDE and Python flask to develop a webpage where users can create an account and sign in. However when I run my program I get from flasklab8 import app
File "/home/ec2-user/environment/flasklab8/flasklab8/app/init.py", line 15, in
from flasklab8 import routes
ImportError: cannot import name 'routes'. There are a few other files for this web page but I think this is the only file that is causing the issue if needed I can edit in the rest of the code. I also do not know if this is because I am using AWS. The code for the problem file is below:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
from flasklab8 import routes
It looks like your file chain is
/home/ec2-user/environment/flasklab8/flasklab8/app/init.py
Unless you are doing something really strange, you routes.py file should be in your app folder, not your flasklab8, meaning your import statement is incorrect. It should read
from app import routes

Using flask-admin with flask blueprints

I want to set up a basic admin interface using flask-admin, and I want all of this to sit in a blueprint. Here's a minimal version my code:
#app.py
from flask import Flask
from bp import bp
app = Flask(__name__)
app.register_blueprint(bp)
if __name__ == "__main__":
app.run(debug=True)
#bp.py
from flask import Blueprint, current_app
from flask_admin import Admin
from flask_admin.contrib.pymongo import ModelView
import pymongo
conn = pymongo.MongoClient()
bp = Blueprint('bp', __name__,
template_folder='templates')
admin = Admin(current_app)
admin.add_view(ModelView(conn.my_db.my_collection))
When running python app.py, it crashes with RuntimeError: working outside of application context, because admin is in no way hooked (or whatever word is used to describe that) to bp.
Normally, one would write
#bp.route('/<page>')
def show(page):
pass
But I can't find the right decorator in the context of creating an Admin object. One thing I tried is to do admin = Admin() in bp.py, import admin in app.py and then admin.app = app in app.py. That works, but it feels like I'm splitting logic in several files, so I'm not really comfortable with that. What's the pythonic way to deal with this situation?
You need the actual app object to init the Flask admin Class. Current_app won't work. This call should be placed on app.py. Then on the blueprint you can use
from app import admin
It work out in this way. just for your reference.
#YourApp/init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
db = SQLAlchemy()
admin = Admin(name='TuozhanOA', template_mode='bootstrap3')
def create_app(config_class=Config):
app = Flask(name)
app.config.from_object(Config)
db.init_app(app)
admin.init_app(app)
from YourApp.main.routes import main
app.register_blueprint(main)
from YourApp.adminbp.routes import adminbp, user_datastore
app.register_blueprint(adminbp)
security = Security(app, user_datastore)
return app
#YourApp/adminbp/routes.py
from flask import render_template, Blueprint
from YourApp.models import User, Role
from YourApp import db, admin
from flask_admin.contrib.sqla import ModelView
from wtforms.fields import PasswordField
from flask_admin.contrib.fileadmin import FileAdmin
import os.path as op
from flask_security import current_user, login_required, RoleMixin, Security,
SQLAlchemyUserDatastore, UserMixin, utils
adminbp = Blueprint('adminbp', name)
admin.add_view(ModelView(User, db.session, category="Team"))
admin.add_view(ModelView(Role, db.session, category="Team"))
path = op.join(op.dirname(file), 'tuozhan')
admin.add_view(FileAdmin(path, '/static/tuozhan/', name='File Explore'))

Categories