2013-11-25 36 views
0

當使用如何獲取python中的request.environ值?

request.environ['QUERY_STRING'] 

我得到價值ugq_no=2,但我怎麼能得到價值?

參考代碼:

def get_ugall_record(request):   
    qry_obj = db.Query(user_guide).order('ugq_no')    
    all_list = []  
    for q in qry_obj: 
     all_list.append(q) 
    return HttpResponse(serializers.serialize('json', all_list), mimetype='application/json') 

def get_faqall_record(request):   
    qry_obj = db.Query(faqs).order('faq_no')    
    all_list = []  
    for q in qry_obj: 
     all_list.append(q) 
    return HttpResponse(serializers.serialize('json', all_list), mimetype='application/json') 

我想在一個功能,使這兩個功能。

所以我試圖用:

def get_ugall_record(request): 
    logging.debug('----1-----') 
    logging.debug(request.GET.get('ugq_no')) 
    if request.GET.get('ugq_no') != 'None': 
     logging.debug('----2-----') 
     ug_qry_obj = db.Query(user_guide).order('ugq_no')    
     ug_all_list = []  
     for q in ug_qry_obj: 
      ug_all_list.append(q) 
     return HttpResponse(serializers.serialize('json', ug_all_list), mimetype='application/json') 
    elif request.GET.get('faq_no') != 'None': 
     logging.debug('----3-----') 
     qry_obj = db.Query(faqs).order('faq_no')    
     all_list = []  
     for q in qry_obj: 
      all_list.append(q) 
     return HttpResponse(serializers.serialize('json', all_list), mimetype='application/json') 

但這不是在ELIF request.GET.get( 'faq_no')= '無' 可以做什麼去!?

回答

1

使用urlparse.parse_qs

>>> import urlparse 
>>> formdata = urlparse.parse_qs('ugq_no=2') 
>>> formdata 
{'ugq_no': ['2']} 
>>> formdata['ugq_no'] 
['2'] 
>>> formdata['ugq_no'][0] 
'2' 

在Python 3.x中,使用urllib.parse.parse_qs

>>> import urllib.parse 
>>> formdata = urllib.parse.parse_qs('ugq_no=2') 
>>> formdata 
{'ugq_no': ['2']} 
>>> formdata['ugq_no'] 
['2'] 
>>> formdata['ugq_no'][0] 
'2' 

或者使用request.GET

value = request.GET.get('ugq_no') 

UPDATE

def get_ugall_record(request): 
    if 'ugq_no' in request.GET: 
     qry_obj = db.Query(user_guide).order('ugq_no')    
     return qry_response(qry_obj) 
    elif 'faq_no' in request.GET: 
     qry_obj = db.Query(faqs).order('faq_no')    
     return qry_response(qry_obj) 

def qry_response(qry_obj): 
    all_list = [] 
    for q in qry_obj: 
     all_list.append(q) 
    return HttpResponse(serializers.serialize('json', all_list), mimetype='application/json') 
+0

我想結合兩個Python功能,其功能是相同的,但有兩個JS分別發揮兩個URL,且兩個Python函數都寫。我想將這些python函數合併爲一個url。在這個例子中,ugq_no是一個鍵,另一個是假設ugq_no2。如何添加if和elif這兩個鍵 – eegloo

+0

@eegloo,對不起,但我不明白你的意思。 – falsetru

+0

我編輯過的問題。請看一下。 – eegloo

相關問題