2016-07-04 54 views
0

我有一個Flask視圖,它使用request.args從請求中獲取一些查詢參數。我想將它稱爲請求之外的功能,因此request.args將不可用。如何修改視圖功能以獨立工作?使用Flask視圖,需要請求之外的查詢參數

http://localhost:5000/version/perms?arg1=value1&arg2=value2 
@app.route(version + 'perms', methods=['GET']) 
def get_perms(): 
    arg1 = request.args.get('arg1') 
    arg2 = request.args.get('arg2') 

我想使用這個功能作爲基本Python函數,傳遞給它的參數通話。

def get_perm(arg1, arg2): 

回答

2

有支撐得到URL部分進入蟒蛇變量,但據我所知它不與查詢參數的工作,你需要使用request.args中了點。

from flask import request 
@app.route(version + 'perms', methods=['GET']) 
def get_perm(): 
    arg1 = request.args.get('arg1') 
    arg2 = request.args.get('arg2') 

如果你想提取的是不是一個查詢參數(即它不是後的網址是什麼?),像這樣的工作(從燒瓶中的文件直接複製 - http://flask.pocoo.org/docs/0.11/quickstart/#routing

@app.route('/post/<int:post_id>') 
def show_post(post_id): 
    # show the post with the given id, the id is an integer 
    return 'Post %d' % post_id 

我不確定你的意思是「沒有web部分調用」 - 你想從其他python代碼調用它,例如從批處理作業?我想我會做這樣的事情:

from flask import request 
@app.route(version + 'perms', methods=['GET']) 
def get_perm_ws(): 
    arg1 = request.args.get('arg1') 
    arg2 = request.args.get('arg2') 
    return get_perm(arg1, arg2) 

def get_perm(arg1, arg2): 
    pass # your implementation here 

另一種選擇(如果你不能把請求參數的URL別的地方)將與默認值的函數參數。注意你真的應該在這裏使用不可變的東西,或者你要求麻煩(一個可變的默認參數可以被修改,並且修改後的值將被用作默認值)。

@app.route(version + 'perms', methods=['GET']) 
def get_perm(params = None): 
    if params == None: 
     params = request.params 
    # your code here 
+0

是的,我想從另一個python代碼中調用這個函數。是的,我已經知道request.args.get()。是的,最後一點應該幫助我,謝謝你的幫助!我應該想到它:/ –

+0

其實我已經管理的情況下,如果我的參數爲空(無)。在這些情況下,我將使用默認值:) –

+0

對於評論混淆感到抱歉,我無法將Python代碼放入評論中,所以我將其添加到我的回覆中 –