title: cannot import name 'db' from partially initialized module 'models' (most likely due to a circular import)
body: <p>I am able to run my flask tests utilizing the following command <code>python -m unittest discover -p testing.py</code> but when I try to run <code>python app.py runserver</code> it shows me the following error message:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;app.py&quot;, line 10, in &lt;module&gt;
      from models import db
    File &quot;/home/paula/projects/envioclicktest/restaurant_flask/models.py&quot;, line 1, in &lt;module&gt;
      from app import app as app
    File &quot;/home/paula/projects/envioclicktest/restaurant_flask/app.py&quot;, line 10, in &lt;module&gt;
      from models import db
  ImportError: cannot import name 'db' from partially initialized module 'models'
  (most likely due to a circular import) (/home/paula/projects/envioclicktest/restaurant_flask/models.py)
  </code></pre>
  <p>My project structure is the following:</p>
  <pre><code>-restaurant_flask
      |-app.py
      |-models.py
      |-testing.py
  </code></pre>
  <p>Here's the content of my files as well as the line I think is causing trouble in each of them</p>
  <h2>App.py</h2>
  <pre><code>from flask import Flask
  from flask_script import Manager, Shell
  from flask_migrate import Migrate, MigrateCommand
  
  
  app = Flask(__name__)
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///restaurant.db'
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  
  from models import db
  migrate = Migrate(app, db)
  
  manager = Manager(app)
  manager.add_command('db', MigrateCommand)
  
  
  if __name__ == '__main__':
      manager.run()
  </code></pre>
  <h2>models.py</h2>
  <pre><code>from app import app as app &lt;-------Trouble line Originally &quot;from __main__ import app&quot; but that doesnt work with testing.py
  from flask_sqlalchemy import SQLAlchemy
  from sqlalchemy.sql.functions import func
  from sqlalchemy.exc import IntegrityError
  import datetime
  import pytz
  import random
  mx = pytz.timezone('America/Mexico_City')
  
  db = SQLAlchemy(app)
  
  class Waiter(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      name = db.Column(db.String(128))
      services = db.relationship(&quot;Service&quot;, back_populates=&quot;waiter&quot;)
  
  class Table(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      table_no = db.Column(db.String(128))
      services = db.relationship(&quot;Service&quot;, back_populates=&quot;table&quot;)
      
  class Service(db.Model):
  
      def __init__(self, tip):
          time = datetime.datetime.now(mx)
          self.tip = tip
          # check for waiters
          waiters = db.session.query(Waiter, func.count(Service.id).\
              filter(Service.exit&gt;time)).\
                  outerjoin(Service).group_by(Waiter).all()
          print(waiters)
          available_waiters= [i for i in waiters if i[1] &lt; 4]
          available_waiters_length = len(available_waiters)
          # Check for tables
          tables = db.session.query(Table, func.count(Table.id).\
              filter(Service.exit&gt;time)).\
                  outerjoin(Service).group_by(Table).all()
          print(tables)
          available_tables= [i for i in tables if i[1] &lt; 1]
          available_tables_length = len(available_tables)
          #check if available 
          if available_tables_length == 0 and available_waiters_length == 0:
              raise Exception(&quot;not enough waiters or tables&quot;)
          if available_waiters_length == 0:
              raise Exception(&quot;not enough waiters&quot;)
          if available_tables_length == 0:
              raise Exception(&quot;not enough tables&quot;)
          # add waiter and table
          waiter_obj = random.choice(available_waiters)
          self.waiter_id = waiter_obj[0].id
          table_obj = random.choice(available_tables)
          self.table_id = table_obj[0].id
  
          
          # check if current time is open
          if time.time() &lt; datetime.time(9,0) or time.time()&gt; datetime.time(23, 30):
              raise Exception(&quot;The restaurant is closed&quot;)
          # add timedelta to init_time
          if time.time() &lt; datetime.time(17,0):
              self.exit = time + datetime.timedelta(minutes=90)
          if time.time() &gt; datetime.time(17,0):
              self.exit = time + datetime.timedelta(minutes=120)
  
      id = db.Column(db.Integer, primary_key=True)
      table_id = db.Column(db.Integer, db.ForeignKey('table.id'))
      table = db.relationship(&quot;Table&quot;, back_populates=&quot;services&quot;)
      waiter_id = db.Column(db.Integer, db.ForeignKey('waiter.id'))
      waiter = db.relationship(&quot;Waiter&quot;, back_populates=&quot;services&quot;)
      arrival = db.Column(db.DateTime, default=datetime.datetime.now(mx))
      exit = db.Column(db.DateTime)
      tip = db.Column(db.Numeric(10,2))
  </code></pre>
  <h2>testing.py</h2>
  <pre><code>from app import app as app &lt;------- This line does not work as &quot;from __main__ import app&quot;
  import unittest
  from models import db, Waiter, Table, Service
  from freezegun import freeze_time
  import datetime
  import pytz
  
  
  class UserTest(unittest.TestCase):
  
      def setUp(self):
          app.config['SQLALCHEMY_DATABASE_URI']  = 'sqlite:///test.db'
          app.config['TESTING'] = True
          app.config['WTF_CSRF_ENABLED'] = False
          self.app = app.test_client()
          db.create_all()
  
      def tearDown(self):
          db.session.remove()
          db.drop_all()
  
      dt = datetime.datetime(2018,1,1,11,0,0,tzinfo=pytz.timezone('America/Mexico_City'))
      @freeze_time(dt)
      def test_models(self):
          #Create a Table and a Waiter
          table = Table(table_no=&quot;table1&quot;)
          db.session.add(table)
          waiter = Waiter(name=&quot;Juan&quot;)
          db.session.add(waiter)
          db.session.commit()
          service = Service(tip=90.80)
          db.session.add(service)
          db.session.commit()
          
          query =  Service.query.all()
          #Check that all users exist
          assert len(query) == 1
          assert query[0].table_id == 1
          assert query[0].waiter_id == 1
          assert ((query[0].exit-query[0].arrival).seconds/60) &gt;= 90
  </code></pre>
  <p>I can't figure it out and it's driving me nuts.</p>
  <p>Any help is much appreciated :)</p>