Python - Mongo Engine Error: Tried to save Duplicate Keys (Duplicate Key Error)

Asked

Viewed 67 times

1

Python I am trying to save more than one user in Json but it does not accept the introduction of more than one, always gives the:

Tried to save Duplicate Unique Keys (Duplicate Key Error)

here is the code:

from .model import User, UserSchema
from flask import Blueprint, request
from flask import jsonify

schema = UserSchema()
api = Blueprint('users', __name__)

@api.route('/', methods=['POST'])
def create():
    # Pegar os dados da requisição
    user_json = request.get_json(silent=True)
    if not user_json:
        return "FAIL"

    # Criar uma entidade a partir do JSON
    user, errors = schema.load(user_json)
    if bool(errors):
        return jsonify(errors)
    user.save()
    return "SUCCESS"

@api.route('/', methods=['PATCH'])
def update():
    # Pegar os dados da requisição
    user_json = request.get_json()
    user = User.objects(name=user_json['name']).first()
    schema.update(user, user_json)
    user.save()
    return "SUCESS"

@api.route('/auth', methods=['POST'])
def auth():
    # cria a senha 
    user_json = request.get_json()
    if not user_json:
        return "FAIL"

    user = User.objects(name = user_json['name']).first()
    if not user:
        return "FAIL"
    if user.password == user_json['password']:
        user.save()
        return "SUCCESS"
    else:
        return "FAIL"

@api.route('/', methods=['GET'])
def list():
    # Retorna os usuários do JSON
    list_users = []
    for user in User.objects():
        list_users.append(schema.dump(user))
    return jsonify(list_users)
  • I think the problem is due to the json format sent in user_json = request.get_json(), probably has repeated Ids or does not have defined Ids.

1 answer

1


Solved, it was discovered that I had two variables:

name = Stringfield(Unique=True) password = Stringfield(Unique=True)

we switched to required and it worked.

Thank you for the attention of those who tried to help :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.