In the last tutorial, I speak about some tricks and tips.
Today, I will show some steps for fixing and run with flask-sqlalchemy.
The source code from my GitHub account can be updated with this source code.
app = Flask (__name__)
app.config['SECRET_KEY'] = 'abcdefg'
# set SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'server.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
If you run it then you get this:C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
C:\Python373\lib\site-packages\flask_sqlalchemy\__init__.py:835: FSADeprecationW
arning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be dis
abled by default in the future. Set it to True or False to suppress this warnin
g.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
You will have a database file named server.sqlite.#app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
Let's create and show the database:C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
>>> db.create_all()
>>> db.engine.table_names()
['user']
A good approach is to create a config.py file and used into the application area.The config.py file will have this source code:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'server.sqlite')
DEBUG=True
The server.py has this source code:...
app = Flask (__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
...