Proper way to make a call to an Endpoint from the API using Flask

后端 未结 2 1029
花落未央
花落未央 2021-01-20 19:27

I\'m trying to build a Flask API and I have one endpoint that is supposed to create a user and another one that is suppose to check if a user is present in the database:

2条回答
  •  走了就别回头了
    2021-01-20 19:43

    I would do something like this for your use-case:

    @API.route('/users', defaults={'email': None} ,methods=['GET', 'POST'])
    @API.route('/users/', methods=['GET', 'POST'])
    def new_user(email):
        if(email):
            user = User.query.filter_by(email=email).first()
            if user:
                return jsonify(user=user.to_json()), 200
            else:
                return jsonify(error=404), 404
        else:
            user_json = json.loads(request.get_json())
            first_name = user_json.get('first_name')
            last_name = user_json.get('last_name')
            email = user_json.get('email')
            password = user_json.get('password')
            user = User(first_name=first_name, last_name=last_name, email=email, password=password)
            db.session.add(user)
            db.session.commit()
            return jsonify(user=user.to_json()), 200
    

提交回复
热议问题