如何在flask-sqlalchemy中插入重复数据。通过利用SQL-ALCHEMY完整性错误

时间:2019-01-23 05:24:18

标签: python sqlite sqlalchemy

    from flask import Flask, jsonify, request
    from flask_sqlalchemy import SQLAlchemy
    from flask_restful import Resource, reqparse, Api


    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
    app.secret_key = 'Thinkonce'
    api = Api(app)
    db = SQLAlchemy()


    class UserModel(db.Model):
        __tablename__ = 'items'
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(120), unique=False)
        email =  db.Column(db.String(120), unique=False)


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

        def json(self):
            return {"username": self.username, "email": self.email}

    @app.before_first_request
    def create_tables():
        db.create_all()

    @app.route('/')
    def home():
        return "Home Page"

    class ItemList(Resource):
        parser = reqparse.RequestParser()
        parser.add_argument('username',
            type=str,
            required=True,
            help="username cannot be blank"
        )
        parser.add_argument('email',
            type=str,
            required=True,
            help="email cannot be blank"
        )
        def post(self):
            data = ItemList.parser.parse_args()
            db.session.add(UserModel(username=data["username"], email=data['email']))
            db.session.commit()
            return {"message":"User created successfully"}, 201

        def get(self):
            print(UserModel.query.all())
            return {'item':[i.json() for i in UserModel.query.all()]}, 200

    api.add_resource(ItemList, '/api')


    if __name__ == '__main__':
        db.init_app(app)
        app.run(port=5000, debug=True, use_reloader=False)

我要插入的数据:

{
    "username":"soubhagya",
    "email":"soubhagya@gmail.com"
}

flask_sqlalchemy不接受重复数据。 有什么办法可以避免这种情况或如何插入重复数据。 它给出了sqlalchemy.exc.IntegrityError

错误:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
      "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: items.email [SQL: 'INSERT INTO items (username, email) VALUES (?, ?)'] [parameters: ('soubhagya', 'soubhagya@gmail.com')] (Background on this error at: http://sqlalche.me/e/gkpj) // Werkzeug Debugger</title>
            <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"
            type="text/css">
            <!-- We need to make sure this has a favicon so that the debugger does
             not by accident trigger a request to /favicon.ico which might
             change the application state. -->
            <link rel="shortcut icon"
            href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
            <script src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
            <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
            <script type="text/javascript">
          var TRACEBACK = 140039101353152,
              CONSOLE_MODE = false,
              EVALEX = true,
              EVALEX_TRUSTED = false,
              SECRET = "kTQfbKAGsVJTWQ4ihbMf";
        </script>

我也分享了模型。

请看看这个。

问题已编辑,我已经分享了完整的代码。

现在请看看

1 个答案:

答案 0 :(得分:1)

似乎出现了此问题,因为flask-sqlalchemy向电子邮件字段隐式添加了唯一约束。这留下了两种可能的解决方案。

首先,通过以下方式显式删除此约束

email = db.Column(db.String(120), unique=False)

或者通过为该列命名其他名称。

为了更好地理解SQLAlchemy中的约束,我建议访问its documentation

UPD (基于对此答案的评论)

该错误与SQLite或SQLAlchemy无关。它只是说您正在尝试将非唯一值添加到所有值都应该唯一且必须以某种方式处理的列中。另外,Flask和SQLAlchemy都不进行任何数据迁移。这意味着,如果您向模型中添加一些字段或向数据库方案中添加其他模型,则需要从头开始创建数据库或使用特殊的工具进行数据迁移。

可能,您所需要做的就是删除存在此约束的旧data.db文件。