2012-10-05 16 views
54

मैं requests मॉड्यूल (पायथन 2.5 के साथ संस्करण 0.10.0) का उपयोग कर रहा हूं। मैंने यह पता लगाया है कि वेबसाइट पर लॉगिन फॉर्म में डेटा कैसे सबमिट किया जाए और सत्र कुंजी पुनर्प्राप्त करें, लेकिन मुझे बाद के अनुरोधों में इस सत्र कुंजी का उपयोग करने का एक स्पष्ट तरीका नहीं दिखाई दे रहा है। क्या कोई नीचे दिए गए कोड में इलिप्सिस भर सकता है या कोई अन्य दृष्टिकोण सुझा सकता है?पायथन अनुरोध और लगातार सत्र

>>> import requests 
>>> login_data = {'formPosted':'1', 'login_email':'[email protected]', 'password':'pw'} 
>>> r = requests.post('https://localhost/login.py', login_data) 
>>> 
>>> r.text 
u'You are being redirected <a href="profilePage?_ck=1349394964">here</a>' 
>>> r.cookies 
{'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'} 
>>> 
>>> r2 = requests.get('https://localhost/profile_data.json', ...) 

उत्तर

113

आप आसानी से बना सकते हैं:

डॉक्स से

एक सतत सत्र का उपयोग कर:

s = requests.session() 

उसके बाद, जैसा कि आप अपने अनुरोध के साथ जारी रखने के लिए:

s.post('https://localhost/login.py', login_data) 
#logged in! cookies saved for future requests. 
r2 = s.get('https://localhost/profile_data.json', ...) 
#cookies sent automatically! 
#do whatever, s will keep your cookies intact :) 

सत्र के बारे में अधिक जानकारी के लिए: यह समान प्रश्न में http://docs.python-requests.org/en/latest/user/advanced/#session-objects

+0

धन्यवाद अनुज, यह एक सही समाधान है। पायथन-अनुरोध दस्तावेज में उदाहरण से यह बहुत स्पष्ट है। – ChrisGuest

+2

स्क्रिप्ट के बीच सत्र को बचाने के किसी भी तरीके से चलता है? – Gtx

+4

pickle.dump सत्र कुकीज़ जैसे pickle.dump (session.cookies._cookies, फ़ाइल) और pickle.load जैसे सत्र में कुकीज़ = pickle.load (फ़ाइल) cj = request.cookies.RequestsCookieJar() cj। _cookies = कुकीज़ और session.cookies = cj – Cyril

4

प्रलेखन का कहना है कि get आप का उपयोग करने के लिए कुकीज़ निर्दिष्ट करने की अनुमति एक वैकल्पिक cookies बहस में लेता है:

>>> url = 'http://httpbin.org/cookies' 
>>> cookies = dict(cookies_are='working') 

>>> r = requests.get(url, cookies=cookies) 
>>> r.text 
'{"cookies": {"cookies_are": "working"}}' 

http://docs.python-requests.org/en/latest/user/quickstart/#cookies

7

चेक आउट मेरा उत्तर:

python: urllib2 how to send cookie with urlopen request

import urllib2 
import urllib 
from cookielib import CookieJar 

cj = CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
# input-type values from the html form 
formdata = { "username" : username, "password": password, "form-id" : "1234" } 
data_encoded = urllib.urlencode(formdata) 
response = opener.open("https://page.com/login.php", data_encoded) 
content = response.read() 

संपादित करें:

मुझे लगता है कि मुझे अपने उत्तर के लिए एक डाउनवोट मिल गया है, लेकिन कोई व्याख्या नहीं है। मैं इसका अनुमान लगा रहा हूं क्योंकि मैं requests के बजाय urllib पुस्तकालयों का जिक्र कर रहा हूं। मैं ऐसा इसलिए करता हूं क्योंकि ओपी requests या किसी अन्य व्यक्ति के सुझाव के लिए मदद मांगता है।

+2

मैं आपके डाउन-वोटर्स में से एक नहीं हूं, लेकिन अनुमान के मुताबिक, कई पाठक शायद ओपी की आखिरी वाक्य को चमकते हैं क्योंकि "क्या कोई नीचे दिए गए कोड में इलिप्सिस भर सकता है या एक और दृष्टिकोण सुझा सकता है [अनुरोध पुस्तकालय के साथ जिसमें किसी अन्य चीज़ के साथ केवल इलिप्स में भरने से मेरे कोड में अधिक प्रमुख शल्य चिकित्सा शामिल होगी] "- लेकिन यह मेरे हिस्से पर सिर्फ एक अनुमान है। –

+2

ओपी के रूप में, मैं कह सकता हूं कि आपका उत्तर उपयोगी विकल्प प्रदान करता है। अगर केवल यह दर्शाता है कि 'अनुरोध' किसी समस्या के लिए एक सरल और उच्च स्तरीय समाधान प्रदान करता है जो अन्यथा लागू करने के लिए 3 पुस्तकालयों को ले जाएगा। – ChrisGuest

4

अन्य उत्तरों इस तरह के सत्र को बनाए रखने के तरीके को समझने में मदद करते हैं। इसके अतिरिक्त, मैं एक कक्षा प्रदान करना चाहता हूं जो स्क्रिप्ट के विभिन्न रनों (कैश फ़ाइल के साथ) पर सत्र बनाए रखे। इसका मतलब है कि उचित "लॉगिन" केवल तभी किया जाता है जब आवश्यक हो (टाइमआउट या कैश में कोई सत्र मौजूद नहीं है)। इसके अलावा यह 'प्राप्त' या 'पोस्ट' के बाद की कॉल पर प्रॉक्सी सेटिंग्स का समर्थन करता है।

यह पायथन 3 के साथ परीक्षण किया जाता है।

इसे अपने कोड के आधार के रूप में उपयोग करें। निम्नलिखित स्निपेट जीपीएल v3 के साथ रिलीज कर रहे हैं

import pickle 
import datetime 
import os 
from urllib.parse import urlparse 
import requests  

class MyLoginSession: 
    """ 
    a class which handles and saves login sessions. It also keeps track of proxy settings. 
    It does also maintine a cache-file for restoring session data from earlier 
    script executions. 
    """ 
    def __init__(self, 
       loginUrl, 
       loginData, 
       loginTestUrl, 
       loginTestString, 
       sessionFileAppendix = '_session.dat', 
       maxSessionTimeSeconds = 30 * 60, 
       proxies = None, 
       userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1', 
       debug = True, 
       forceLogin = False, 
       **kwargs): 
     """ 
     save some information needed to login the session 

     you'll have to provide 'loginTestString' which will be looked for in the 
     responses html to make sure, you've properly been logged in 

     'proxies' is of format { 'https' : 'https://user:[email protected]:port', 'http' : ... 
     'loginData' will be sent as post data (dictionary of id : value). 
     'maxSessionTimeSeconds' will be used to determine when to re-login. 
     """ 
     urlData = urlparse(loginUrl) 

     self.proxies = proxies 
     self.loginData = loginData 
     self.loginUrl = loginUrl 
     self.loginTestUrl = loginTestUrl 
     self.maxSessionTime = maxSessionTimeSeconds 
     self.sessionFile = urlData.netloc + sessionFileAppendix 
     self.userAgent = userAgent 
     self.loginTestString = loginTestString 
     self.debug = debug 

     self.login(forceLogin, **kwargs) 

    def modification_date(self, filename): 
     """ 
     return last file modification date as datetime object 
     """ 
     t = os.path.getmtime(filename) 
     return datetime.datetime.fromtimestamp(t) 

    def login(self, forceLogin = False, **kwargs): 
     """ 
     login to a session. Try to read last saved session from cache file. If this fails 
     do proper login. If the last cache access was too old, also perform a proper login. 
     Always updates session cache file. 
     """ 
     wasReadFromCache = False 
     if self.debug: 
      print('loading or generating session...') 
     if os.path.exists(self.sessionFile) and not forceLogin: 
      time = self.modification_date(self.sessionFile)   

      # only load if file less than 30 minutes old 
      lastModification = (datetime.datetime.now() - time).seconds 
      if lastModification < self.maxSessionTime: 
       with open(self.sessionFile, "rb") as f: 
        self.session = pickle.load(f) 
        wasReadFromCache = True 
        if self.debug: 
         print("loaded session from cache (last access %ds ago) " 
           % lastModification) 
     if not wasReadFromCache: 
      self.session = requests.Session() 
      self.session.headers.update({'user-agent' : self.userAgent}) 
      res = self.session.post(self.loginUrl, data = self.loginData, 
            proxies = self.proxies, **kwargs) 

      if self.debug: 
       print('created new session with login') 
      self.saveSessionToCache() 

     # test login 
     res = self.session.get(self.loginTestUrl) 
     if res.text.lower().find(self.loginTestString.lower()) < 0: 
      raise Exception("could not log into provided site '%s'" 
          " (did not find successful login string)" 
          % self.loginUrl) 

    def saveSessionToCache(self): 
     """ 
     save session to a cache file 
     """ 
     # always save (to update timeout) 
     with open(self.sessionFile, "wb") as f: 
      pickle.dump(self.session, f) 
      if self.debug: 
       print('updated session cache-file %s' % self.sessionFile) 

    def retrieveContent(self, url, method = "get", postData = None, **kwargs): 
     """ 
     return the content of the url with respect to the session. 

     If 'method' is not 'get', the url will be called with 'postData' 
     as a post request. 
     """ 
     if method == 'get': 
      res = self.session.get(url , proxies = self.proxies, **kwargs) 
     else: 
      res = self.session.post(url , data = postData, proxies = self.proxies, **kwargs) 

     # the session has been updated on the server, so also update in cache 
     self.saveSessionToCache()    

     return res 

ऊपर वर्ग का उपयोग कर कुछ ऐसा दिखाई देगा के लिए एक कोड का टुकड़ा:

if __name__ == "__main__": 
    # proxies = {'https' : 'https://user:[email protected]:port', 
    #   'http' : 'http://user:[email protected]:port'} 

    loginData = {'user' : 'usr', 
       'password' : 'pwd'} 

    loginUrl = 'https://...' 
    loginTestUrl = 'https://...' 
    successStr = 'Hello Tom' 
    s = MyLoginSession(loginUrl, loginData, loginTestUrl, successStr, 
         #proxies = proxies 
         ) 

    res = s.retrieveContent('https://....') 
    print(res.text) 

    # if, for instance, login via JSON values required try this: 
    s = MyLoginSession(loginUrl, None, loginTestUrl, successStr, 
         #proxies = proxies, 
         json = loginData) 
+1

यह एक अच्छा जवाब है, इस समाधान की खोज करना भी मुश्किल है। – duality

0

ऊपर सभी प्रश्नों के उत्तर की कोशिश कर रहा पर, मैंने पाया कि बजाय RequestsCookieJar का उपयोग करने का बाद के अनुरोधों के लिए नियमित कुकीज ने मेरी समस्या तय की। json डेटा पुनः प्राप्त करने

import requests 
import json 

authUrl = 'https://whatever.com/login' 

#The subsequent url 
testUrl = 'https://whatever.com/someEndpoint' 

#Whatever you are posting 
login_data = {'formPosted':'1', 'login_email':'[email protected]', 'password':'pw'} 

#The auth token or any other data that we will recieve from the authRequest. 
token = '' 

# Post the loginRequest 
loginRequest = requests.post(authUrl,login_data) 
print loginRequest.text 

# Save the request content to your variable. In this case I needed a field called token. 
token = str(json.loads(loginRequest.content)['token']) 
print token 

# Verify successfull login 
print loginRequest.status_code 

#Create your RequestsCookieJar for your subsequent requests and add the cookie 
jar = requests.cookies.RequestsCookieJar() 
jar.set('LWSSO_COOKIE_KEY', token) 

#Execute your next request(s) with the RequestCookieJar set 
r = requests.get(testUrl, cookies=jar) 
print(r.text) 
print(r.status_code) 
0

टुकड़ा, पासवर्ड से सुरक्षित

import requests 

username = "my_user_name" 
password = "my_super_secret" 
url = "https://www.my_base_url.com" 
the_page_i_want = "/my_json_data_page" 

session = requests.Session() 
# retrieve cookie value 
resp = session.get(url+'/login') 
csrf_token = resp.cookies['csrftoken'] 
# login, add referer 
resp = session.post(url+"/login", 
        data={ 
         'username': username, 
         'password': password, 
         'csrfmiddlewaretoken': csrf_token, 
         'next': the_page_i_want, 
        }, 
        headers=dict(Referer=url+"/login")) 
print(resp.json()) 
संबंधित मुद्दे