python - Exposing reusable functions to deal with HTTP POST methods -
i'm using flask & python write various api methods. example, 1 method checks database ascertain whether or not username being used. looks bit 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 user check if exists doesexist = str(usertable.find_one({"username": usertocheck})) conn.close() if doesexist == "none": return "username available" elif doesexist.find("objectid") != -1: return "username taken." else: return "error"
in short, allow checkuser() function able called elsewhere in flask application (possibly following other decorators). example, before create user account.
how should go doing this?
thanks.
wrap in function , send request function:
def checkuser(request): if request.method == "post": conn = connection('localhost', 27017) db = conn['user-data'] usertable = db["logins"] usertocheck = request.form['usertocheck'] #search user check if exists doesexist = str(usertable.find_one({"username": usertocheck})) conn.close() if doesexist == "none": return "username available" elif doesexist.find("objectid") != -1: return "username taken." else: return "error" @app.route('/register/checkuser', methods=['post']) def func(): return checkuser(request)
Comments
Post a Comment