Search code examples
pythonpostgresqlflaskflask-restfulpeewee

Getting peewee IntegrityError for unique constraint only through API


Getting an IntegrityError when trying to update records on my PostgreSQL database with peeweee. It only happens when I try HTTP PUT method, however.

Using Flask and Flask-Restful to create API resources. GET, DELETE to a single Blog Post works perfectly. Post to the bucket works perfectly

I can run the exact same code through the REPL and it works just fine. Whats even stranger is the API just kind of broke all of a sudden, I tested this function yesterday and it was fine. Now I can't pinpoint what changed.

Here is my peewee model in models.py


class BlogPost(Model):
    title = CharField(default='', unique=True)
    content = TextField(default='')
    created = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = DATABASE

Here is the resource for a single BlogPost in resources.blogposts.py


class BlogPost(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            'title',
            required=False,
            help='No title provided',
            location=['form', 'json']
        )
        self.reqparse.add_argument(
            'content',
            required=False,
            nullable=True,
            location=['form', 'json'],
            default=''
        )
        super().__init__()

    @marshal_with(blogpost_fields)
    def get(self, id):
        return (blogpost_or_404(id))

    @marshal_with(blogpost_fields)
    @auth.login_required
    def put(self, id):
        args = self.reqparse.parse_args()
        try:
            blogpost = models.BlogPost.get(models.BlogPost.id==id)
        except models.BlogPost.DoesNotExist:
            return make_response(json.dumps(
                    {'error': 'That blogpost does not exist or is not editable'}
                ), 403)
        else:
            query = blogpost.update(**args)
            query.execute()
            blogpost = (blogpost_or_404(id))
            return (blogpost, 200, {
                'Location': url_for('resources.blogposts.blogpost', id=id)
               })

    @auth.login_required
    def delete(self, id):
        try:
            blogpost = models.BlogPost.select().where(
                models.BlogPost.id==id
            ).get()
        except models.BlogPost.DoesNotExist:
            return make_response(json.dumps(
                    {'error': 'That blogpost does not exist or is not editable'}
                ), 403)
        else:
            query = blogpost.delete().where(models.BlogPost.id==id)
            query.execute()
            return '', 204, {'Location': url_for('resources.blogposts.blogposts')}

blogposts_api = Blueprint('resources.blogposts', __name__)
api = Api(blogposts_api)
api.add_resource(
    BlogPost,
    'api/v1/blogposts/<int:id>',
    endpoint='blogpost'
)

If I perform a GET to http://localhost:8000/api/v1/blogposts/8 I get my only BlogPost in the table (I deleted all but this one to test)


{
    "id": 8,
    "title": "Test3",
    "content": "This is to test changes to BlogPost 1",
    "created": "Wed, 19 Jun 2019 12:44:31 -0000"
}

However, if I PUT to the same URL I get a Unique Constraint.. I definitely don't have a database entry with this title.


{
    "title": "9sdnfsudngfisdngondasgjns",
    "content": "lkbksigsndignsoidugnlis",
}

I can do this in a REPL and it works perfectly fine, it should be the exact same thing as what I'm doing above:


blogpost = models.BlogPost.get(models.BlogPost.id==8)
blogpost.update(
    title="9sdnfsudngfisdngondasgjns",
    content="lkbksigsndignsoidugnlis"
)
blogpost.execute()

The actual error:

peewee.IntegrityError: duplicate key value violates unique constraint "blogpost_title" DETAIL: Key (title)=(9sdnfsudngfisdngondasgjns) already exists.

EDIT: Before the peewee error psycopg2 is throwing this error as well:

UniqueViolation: duplicate key value violates unique constraint "user_username_key" DETAIL: Key (username)=(9sdnfsudngfisdngondasgjns) already exists.


Solution

  • This is really strange but I figured it out. I had to update my put method to be the same syntax of my delete method. Basically, I had to pass in the context to the actual update method:

    
    @marshal_with(blogpost_fields)
        @auth.login_required
        def put(self, id):
            args = self.reqparse.parse_args()
            try:
                blogpost = models.BlogPost.select().where(
                    models.BlogPost.id==id).get()
            except models.BlogPost.DoesNotExist:
                return make_response(json.dumps(
                        {'error': 'That blogpost does not exist or is not editable'}
                    ), 403)
            else:
                query = blogpost.update(**args).where(models.BlogPost.id==id)
                query.execute()
                blogpost = (blogpost_or_404(id))
                return (blogpost, 200, {
                    'Location': url_for('resources.blogposts.blogpost', id=id)
                   })
    
        @auth.login_required
        def delete(self, id):
            try:
                blogpost = models.BlogPost.select().where(
                    models.BlogPost.id==id).get()
            except models.BlogPost.DoesNotExist:
                return make_response(json.dumps(
                        {'error': 'That blogpost does not exist or is not editable'}
                    ), 403)
            else:
                query = blogpost.delete().where(models.BlogPost.id==id)
                query.execute()
                return '', 204, {'Location': url_for('resources.blogposts.blogposts')}