公开可重用的函数来处理HTTP POST方法

时间:2014-04-06 15:05:02

标签: python python-2.7 routes flask python-decorators

我正在使用Flask& Python编写各种API方法。例如,一种方法检查数据库以确定用户名是否已被使用。看起来有点像这样:

@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"

简而言之,我想允许从我的Flask应用程序中的其他地方调用checkuser()函数(可能跟随其他装饰器)。例如,在我创建用户帐户之前。

我该怎么做呢?

感谢。

1 个答案:

答案 0 :(得分:1)

将其包装在另一个函数中并将请求发送到函数:

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)