示例#1
0
def contact(id=None):
    if request.method == 'GET':
        if id is not None:
            contact = Contact.query.get(id)
            if contact:
                return jsonify(contact.serialize()), 200
            else:
                return jsonify({"msg": "Comment not Found"}), 404
        else:
            contacts = Contact.query.all()
            contacts = list(map(lambda contact: contact.serialize(), contacts))
            return jsonify(contacts), 200

    if request.method == 'POST':
        if not request.is_json:
            return jsonify({"msg": "Incorrect format"}), 400

        cont_name = request.json.get('cont_name', None)
        cont_lastname = request.json.get('cont_lastname', None)
        cont_email = request.json.get('cont_email', None)
        cont_phone = request.json.get('cont_phone', None)
        cont_message = request.json.get('cont_message', None)

        if not cont_name or cont_name == '':
            return jsonify({"msg": "Please enter Name"}), 400
        if not cont_lastname or cont_lastname == '':
            return jsonify({"msg": "Please enter Last name"}), 400
        if not cont_email or cont_email == '':
            return jsonify({"msg": "Please enter email"}), 400
        if not cont_phone or cont_phone == '':
            return jsonify({"msg": "Please enter a phone number"}), 400
        if not cont_message or cont_message == '':
            return jsonify({"msg": "Please enter a message"}), 400

        contact = Contact()
        contact.cont_name = cont_name
        contact.cont_lastname = cont_lastname
        contact.cont_email = cont_email
        contact.cont_phone = cont_phone
        contact.cont_message = cont_message

        db.session.add(contact)
        db.session.commit()

        return jsonify(contact.serialize()), 201

    if request.method == 'DELETE':
        contact = Contact.query.get(id)
        if not contact:
            return jsonify({"msg": "Contact message not found"}), 404
        db.session.delete(contact)
        db.session.commit()
        return jsonify({"msg": "Contact message was erased"}), 200