Flask-SQLAlchemy does not create tables using create_all ()

I have a Flask application that uses Flask-SQLAlchemy. In my unit tests, I initialize the application and the database, then call db.create_all() , and for some reason it looks like it doesn’t match any of my models, therefore it doesn’t create any tables.

I use both __tablename__ and __bind_key__ in my models, as I have two databases.

My configuration:

 SQLALCHEMY_DATABASE_URI = 'sqlite://' SQLALCHEMY_BINDS = { 'db1': SQLALCHEMY_DATABASE_URI, 'db2': SQLALCHEMY_DATABASE_URI } 

Cut the version of my setUp() method in my unit tests:

 from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy class APITestCase(unittest.TestCase): app = Flask(__name__) db = SQLAlchemy(app) db.create_all() 

Here is an example of my two models: one from each type of binding:

 class Contact(db.Model): __tablename__ = 'contact' __bind_key__ = 'db1' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(255)) last_name = db.Column(db.String(255)) ... def __init__(first_name, last_name): self.first_name = first_name self.last_name = last_name ... class BaseUser(db.Model): __tablename__ = 'User__GeneralUser' __bind_key__ = 'db2' id = db.Column(db.Integer, primary_key=True) username = db.Column('Username', db.String(100)) first_name = db.Column('FirstName', db.String(100)) last_name = db.Column('Surname', db.String(100)) ... def __init__(username, first_name, last_name): self.username = username self.first_name = first_name self.last_name = last_name ... 

Am I missing something obvious? How does Flask-SQLAlchemy know where to look for my models to create related tables?

+4
source share
2 answers

In your unit tests, you should not create a new instance of the SQLAlchemy object ('db'), you should import an instance from which your models come off:

models.py:

 from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() class Contact(db.Model): ... 

tests.py:

 from models import db from flask import Flask import unittest class TestExample(unittest.TestCase): def setUp(self): self.app = Flask(__name__) db.init_app(self.app) with self.app.app_context(): db.create_all() 
+10
source

your SQLALCHEMY_DATABASE_URI is wrong, read here how to configure your Sqlite database for the system http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#sqlite

if you never experience, check out this repo and apply to your apps :) https://github.com/Fird0s/Banda-Maps/blob/master/models.py

-1
source

All Articles