2013-04-28 20 views
0

試圖在python中的方法中返回請求庫文件會話... 看起來很簡單,我的腳本工作正常,然後我將它清理成類和方法,它會不工作,似乎會議不能從一個方法返回?相當困惑,我相信這應該是這樣的。請求庫文件python,在方法中返回會話

這是改變之前它的代碼,它工作正常:

import requests 

httpHeaders = { 'Host' : 'www.somesite.com', 
    'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:16.0) Gecko/20100101 Firefox/16.0', 
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
    'Accept-Language' : 'en-US,en;q=0.5', 
    'Accept-Encoding' : 'gzip, deflate', 
    'Connection' : 'keep-alive', 
    'Referer' : 'https://blah.someloginsite.com/logon', 
    'Content-Type' : 'application/x-www-form-urlencoded', 
    'Content-Length' : '59', 
    'Referer' : 'someurl.com'} 

postContent = { 'UserName': 'blabhbhbhb', 
    'Password': 'qwerty', 
    'submit' : '', 
    'returnUrl' : ''} 

s = requests.Session() 
s.post('https://blah.someloginsite.com/logon', data=postContent, headers=httpHeaders) 

param = {'someID': '225', 'anotherID': '0'} 
r = s.post('https://someurl/doactionthatneedslogin', data=param) 

print r.status_code 
print r.headers['content-type'] 
print r.encoding 
print r.text 

上面的代碼工作正常,但是當我把它分成一類和函數/方法將無法正常工作。現在我清理代碼,它不起作用,似乎我不能在請求庫裏返回一個會話,但我確定我可以......?

import requests 


class doit(): 

    def __init__(self, username, password): 
     print "test" 
     spSession = self.getSession(username, password) 
     self.doAction(spSession, 33, 4)  

    #Initializes session 
    def getSession(self, username, password): 
     httpHeaders = {SAME AS ABOVE BLAHBLAHBLAH} 

     postContent = { 'UserName': username , 
      'Password': password , 
      'submit' : '', 
      'returnUrl' : ''} 

     s = requests.Session() 
     s.post('https://someurl.com/logon', data=postContent, headers=httpHeaders)  
     return s 

    def doAction(self, spSession, someid,anotherid): 
     param = {'someid': someid , 'anotherid': anotherid} 
     r = spSession.post('https://someurl/doactionthatneedslogin', data=param) 

     print r.status_code 
     print r.headers['content-type'] 
     print r.encoding 
     print r.text 

doit("usernameas","qwerty") 

有關發生了什麼的任何想法?第一個腳本的作品;而第二個則沒有。我所做的只是清理它... 我想擁有它,所以我可以反覆使用不同方法的會話。

第二個腳本確實與登錄工作,所以它似乎會是不錯,但如預期,即使它是在記錄的第二項行動是行不通的。

什麼是去這裏?

斯科特

回答

0

好了,兩個例子似乎可以用不同的參數,但唯一的區別顯著我能看到的是此行的第一個例子之間...

param = {'someID': '225', 'anotherID': '0'} 

..此。而線路在第二個例子...

self.doAction(spSession, 33, 4) 

...其中所述第一使用字符串其參數,第二個是使用整數。如果您將第二行更改爲...

self.doAction(spSession, '33', '4') 

...?