Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to prevent double data submission in flask-sqlalchemy
    text
    copied!<p>I'm studying now main concepts of flask and flask-sqlalchemy. Keeping in my mind info from the tutorial (<a href="http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html" rel="nofollow">intro</a> and <a href="http://pythonhosted.org/Flask-SQLAlchemy/contexts.html" rel="nofollow">contexts</a>) I'm trying to create a simple database. My Flask app is strucured as follows:</p> <pre><code>./db/ ./db/models.py ./main.py </code></pre> <p>The contents of the files is as follows:</p> <p><code>./main.py</code>:</p> <pre><code>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", "admin@example.com") db.session.add(admin) db.session.commit() </code></pre> <p><code>./db/models.py</code>:</p> <pre><code>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 '&lt;User %r&gt;' % self.username </code></pre> <p>When I check the sqlite database, I see that sqlalchemy is trying to send commit() twice. So I have to remove the <em>unique=True</em> parameter in order to stop application crash. Meantime when I run the following commans from the python shell:</p> <blockquote> <blockquote> <p>admin = mumsUsers('admin', 'admin@example.com')</p> <p>db.session.add(admin)</p> <p>db.session.commit()</p> </blockquote> </blockquote> <p>only one record appears (as it is expected). </p> <p>Therefore my question is how to prevent double call for commit()?</p> <p><strong>Update</strong> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload