【问题标题】:Exposing reusable functions to deal with HTTP POST methods公开可重用函数来处理 HTTP POST 方法
【发布时间】:2014-05-18 17:05:38
【问题描述】:

我正在使用 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() 函数(可能跟随其他装饰器)。例如,在我创建用户帐户之前。

我该怎么做呢?

谢谢。

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 谢谢乌迪!最简单的事情可能最令人困惑!
    • np,您也可以将此函数定义为装饰器并装饰使用它的其他函数。
    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多