I am calling a module inside urbancloth package from home.py
This runs the __init__ file but doesn't run another module present in urbancloth.
The directory structure is as follows -
The code in home.py:
from urbancloth import app
if __name__ == '__main__':
app.run(debug =True)
The code in __init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'b0fe7021532f0541f87226aafd71ec77'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
from urbancloth import routes
and the error message is-
I am following Sir CoreySchafers Flask tutorials
Github for original code
If you will look at you error closely
from urabncloth import app
Looking at your directory there is no urabncloth it is urbancloth. Just a typo. So in your routes.py change the package name.
Hope this solves your problem!!!
Related
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
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
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
I am trying to implement Flask-PyMongo with blueprints and an application factory and keep getting AttributeError: 'Flask' object has no attribute 'db'
My directory structure looks like
myapp/
myapp.py
config.py
/app
__init__.py
/v1
__init__.py
endpoints.py
In my python script that starts the Flask app I have:
import os
from app import create_app
app = create_app('dev')
In my top level init.py I have:
mongo = PyMongo()
def create_app(config_name):
app = Flask(__name__)
mongo.init_app(app)
app.config.from_object(config[config_name])
from app.v1 import psapi as psapi_bp
app.register_blueprint(psapi_bp, url_prefix='/api')
if not os.path.exists('logs'):
os.mkdir('logs')
In my endpoints.py I have a route that looks like
#myapp.route('/addentry', methods=['POST'])
def addentry():
username = request.json['username']
userid = current_app.db.user_entry.insert({'username':username})
return jsonify({'userid':userid})
I feel like there is something small that I am missing but I am not seeing it.
You need to call db on your mongo object, not on the app object
to those who may be facing this problem again :
you should first define mongo oustside create_app to have access to it from inside other files.
then init_app with that like the following:
from flask import Flask, current_app
from flask_pymongo import PyMongo
mongo = PyMongo()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(app_config[config_name])
# INIT EXTENSIONS ----------------------
mongo.init_app(app)
return app
then in any file you can import mongo from above file. for example:
from ../factory import mongo
Trying to run the tutorial here: http://flask-sqlalchemy.pocoo.org/2.1/quickstart/ using my app
I have looked at the circular imports problem but I don't think that's it. I'm an absolute beginner to python and flask (and sqlalchemy). My app currently runs, but the database part doesn't
This is the current setup:
mysite
|- __init__.py
|- flask_app.py
|- models.py
|- views.py
init.py
from flask import Flask
app = Flask(__name__)
flask_app.py
from flask import Flask, request, url_for
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:// -- database uri --'
... app continues here
models.py
from app import app
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Foo(db.Model):
... model continues here
views.py
from app import app,models
... views continue here, still not using anything from models
when I run from mysite import db in the python console I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'db'
Declare your db object in __init__.py. The stuff that is declared in __init__.py defines what can be imported under mysite/.
See: What is __init__.py for?
Also consider moving to the application factory pattern.
For example in __init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['DEBUG'] = True
... more application config ...
db.init_app(app)
return app
Then in flask_app.py:
from mysite import create_app, db
app = create_app()
if __name__ == '__main__':
app.run()
I point this out because you instantiate the app object twice in the code you've shown. Which is definitely wrong.