سؤال

I'm using Flask & Python to write various API methods. For example, one method checks the database to ascertain whether or not a username is already being used. It looks a bit like this:

@app.route('/register/checkuser', methods=['POST'])
def checkuser():

if request.method == "POST":

    conn = Connection('localhost', 27017)
    db = conn['user-data']
    userTable = db["logins"]

    userToCheck = request.form['usertocheck']

    #search for user to check if it already exists
    doesExist = str(userTable.find_one({"username": userToCheck}))
    conn.close()

    if doesExist == "None":
        return "Username is available"
    elif doesExist.find("ObjectId") != -1:
        return "Username already taken."
    else:
        return "Error"

In short, I would like to allow the checkuser() function to be able to be called from elsewhere in my Flask application (possibly following other decorators). For example, before I create a user account.

How should I go about doing this?

Thanks.

هل كانت مفيدة؟

المحلول

wrap it in another function and send the request to the function:

def checkuser(request):
    if request.method == "POST":
        conn = Connection('localhost', 27017)
        db = conn['user-data']
        userTable = db["logins"]

        userToCheck = request.form['usertocheck']

        #search for user to check if it already exists
        doesExist = str(userTable.find_one({"username": userToCheck}))
        conn.close()

        if doesExist == "None":
            return "Username is available"
        elif doesExist.find("ObjectId") != -1:
            return "Username already taken."
        else:
            return "Error"


@app.route('/register/checkuser', methods=['POST'])
def func():
    return checkUser(request)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top