I am new to flask and i have been struggling to create an sqlite database but whenever i run the from app import db I get the error message:
NameError: name 'app' is not defined
This is my code:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
db = SQLAlchemy()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db.init_app(app)
class Todo:
id = db.Column(db.Integer(), primary_key=True)
content = db.Column(db.String(length=300), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)`
The image below is my directory structure. I don't know if it has anything to do with it: Image of directory structure
I tried import db from app so that I will create the db file.
First u need to replace db.init_app(app) with db = SQLAlchemy(app). The starting code could look like this:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
Then after your class Todo:
with app.app_context():
db.create_all()
Related
i have created app.py
and tables.py
which are the main app and a file used to define the tables of a database [database.db] respectively.
I cannot create tables in the database.db, what could be the problem?
Code for both is given below
#app.py
from flask import Flask, render_template, request, session, redirect
from tables import db
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db.init_app(app)
#app.before_first_request
def create_tables():
db.create_all()
#app.route("/")
def home():
return render_template("register.html")
#tables.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class users (db.Model):
users_key = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(21), nullable=False)
email = db.Column(db.String(31), nullable=False, unique=True)
password = db.Column(db.String(61), nullable=False)
i expected to get tables in the database.db file which is located in the same directory as the app.py file. i could not add any tables though.
You have to create database context and initialize it.
with app.app_context():
db.create_all()
Also make sure to import the Flask module from the flask package and SQLAlchemy from the flask_sqlalchemy package in tables.py.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
Im trying to connect my first Flask app with SQLAlchemy and PostGreSQL but got stuck with the following error.
UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
After several hours of debugging for something that may be very simple I ran out of options. From the error seems like the issue is with the variables for SQLAlCHEMY_DATABASE_URI, but not 100% sure. I tried localhost and localhost:5000` but same error.
Reading other answers in SO, I saw that some times people get this issue when defining the config after the db = SQLAlchemy(app) but I don't have it like this in my code. Any leads are greatly appreciated.
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.update(
SECRET_KEY='rafadbpw',
SQLAlCHEMY_DATABASE_URI='postgresql://postgres:rafadbpw#localhost:5000/catalog_db',
SQLALCHEMY_TRACK_MODIFICATIONS=False
)
db = SQLAlchemy(app)
#app.route('/index')
#app.route('/')
def hello_flask():
return "Hello Flask!"
class Publication(db.Model):
__tablename__ = 'publication'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
def __init__(self,id,name):
self.id = id
self.name = name
def __repr__(self):
return 'The id is {}, name is {}'.format(self.id, self.name)
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
With Flask SQL Alchemy, I am using the Chinook sqlite db.
sqlalchemy.exc.ArgumentError: Mapper mapped class PlayLists->playlists could not assemble any primary key columns for mapped table 'playlists'
My code is like this. "app/init.py"
from flask import Flask
from config import app_config
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.app = app
db.init_app(app)
db.Model.metadata.reflect(db.engine)
Bootstrap(app)
from app import models
return app
The app/model.py
from app import db
class PlayLists(db.Model):
__tablename__ = db.Model.metadata.tables['playlists']
What am I doing wrong?
In your Playlists class you are assigning db.Model.metadata.tables['playlists'] to __tablename__ . However, db.Model.metadata.tables['playlists'] returns an object of class 'sqlalchemy.sql.schema.Table'. You should instead assign it to a string with the name of the table, as in:
app/model.py
from app import db
class PlayLists(db.Model):
__tablename__ = 'playlists'
This example works for me, returning the column names of the reflected database:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = 'SUPERSECRET'
app.config['SQLALCHEMY_DATABASE_URI'] = ''mysql+pymysql://user:pass#localhost:port/db''
db = SQLAlchemy(app)
db.init_app(app)
db.Model.metadata.reflect(db.engine)
class User(db.Model):
__tablename__ = "users"
#app.route("/")
def hello():
user = User()
table_columns = str(user.__table__.columns)
return table_columns
if __name__ == "__main__":
app.run()
I am new to deploying to aws as well as flask. Basically I have a simple Flask app but every time I make a change and deploy the new code to aws elastic beanstalk, the db gets reset.
from dateutil import parser
from datetime import datetime
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
import os
application = app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
ma = Marshmallow(app)
cors = CORS(app)
#app.route('/')
def hello():
return 'hello'
.
.
.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
weight = db.Column(db.Float)
workouts = db.relationship('Workout', backref='user', lazy=True)
def __init__(self, name, weight):
self.name = name
self.weight = weight
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'weight')
user_schema = UserSchema(strict=True)
users_schema = UserSchema(many=True, strict=True)
.
.
.
db.create_all()
if __name__ == '__main__':
app.run(debug=True)
I expect that each time I
eb deploy flask-env my db wouldnt get reset but it does. For instance if i create a user and then later change something in the code and deploy, that user is gone.
You should:
Create an EBS Volume
Load the database into that volume
Attach the EBS Volume to your Beanstalk app with an .ebextension. An example can be found here.
With all that being said, this is not a highly available, well architected solution and will deteriorate at scale rapidly.
You will want to replace SQLite with an RDS instance at some point in the future before it becomes a problem.
I'm new in bluprint, and have problem with importing db into mydatabase.py file which is models file.
I've faced with this error:
ImportError: cannot import name 'db'
The tree of my project
nikoofar/
run.py
bookshelf/
__init__.py
mydatabase.py
main/
controllers.py
__init__.py
run.py
from bookshelf import app
if __name__ == '__main__':
app.run(debug=True, port=8000)
bookshelf / intit.py
from flask import Flask
from bookshelf.main.controllers import main
from flask_sqlalchemy import SQLAlchemy
from mydatabase import pmenu
app = Flask(__name__, instance_relative_config=True)
db = SQLAlchemy(app)
db.init_app(app)
application.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password#localhost/databasename'
app.config.from_object('config')
app.register_blueprint(main, url_prefix='/')
bookshelf / main / controllers.py
from flask import Blueprint
from bookshelf.mydatabase import *
from flask_sqlalchemy import SQLAlchemy
main = Blueprint('main', __name__)
#main.route('/')
def index():
g = pmenu.query.all()
print (g)
return "ok"
The problem backs to from bookshelf import db, and if I delete that, the error will be changed to:
ImportError: cannot import name 'db'
bookshelf / mydatabase.py
from bookshelf import db
class pmenu(db.Model):
__tablename__ = 'p_menu'
id = db.Column(db.Integer, primary_key=True)
txt = db.Column(db.String(80), unique=True)
link = db.Column(db.String(1024))
def __init__(self, txt, link):
self.txt = txt
self.link = link
def __repr__(self):
return "{'txt': " + self.txt + ", 'link':" + self.link + "}"
Any solution?
This is actually a simple, yet frustrating issue. The problem is you are importing main BEFORE you are creating the instance of db in your __init__.py
If move the import to after your db = SQLAlchemy(app), it will work:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://uername:password#localhost/test'
db = SQLAlchemy(app)
from bookshelf.main.controllers import main #<--move this here
app.register_blueprint(main, url_prefix='/')