0
votes

I'm studying now main concepts of flask and flask-sqlalchemy. Keeping in my mind info from the tutorial (intro and contexts) I'm trying to create a simple database. My Flask app is strucured as follows:

./db/
./db/models.py
./main.py

The contents of the files is as follows:

./main.py:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object(__name__)

from db.models import create_app

dbapp = create_app()
with dbapp.test_request_context():
  from db.models import db, mumsUsers
  db.create_all()
  db.session.rollback()
  admin = mumsUsers("admin", "[email protected]")
  db.session.add(admin)
  db.session.commit()

./db/models.py:

from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask, current_app

db = SQLAlchemy()

def create_app():
  app = Flask(__name__)
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
  db.init_app(app)
  return(app)

class mumsUsers(db.Model):
  __tablename__ = 'mumsUsers'
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(80), unique=True)
  email = db.Column(db.String(80), unique=True)

  def __init__(self, username, email):
    self.username = username
    self.email = email

  def __repr__(self):
    return '<User %r>' % self.username

When I check the sqlite database, I see that sqlalchemy is trying to send commit() twice. So I have to remove the unique=True parameter in order to stop application crash. Meantime when I run the following commans from the python shell:

admin = mumsUsers('admin', '[email protected]')

db.session.add(admin)

db.session.commit()

only one record appears (as it is expected).

Therefore my question is how to prevent double call for commit()?

Update The appeared problem has been caused by my fault, while making looped imports. Indeed I didn't notice I called import for the application package. Therefore please ignore this post.

1
Why are you calling Flask twice? You only need it in the main.Stefano Sanfilippo
Thank you for your advise. I removed it, but the problem remains.wanderlust
Rather than editing the question, submit an answer (looped imports) and then mark it as closed. Someone might hit this question via search engine, and you'll be that person's hero.Clint

1 Answers

0
votes

The caused problem has been related to looped imports.

Please check what you import before asking.