2013-03-06 44 views
0

我正在製作一個用於與Jasper Report Server進行通信的小腳本,但現在我需要用Python讀取它。Python基本認證。得到一個Cookie

這在我的Ruby腳本的一個片段:

def get_uuid_and_cookie 
    body = "" 
    cookie = "" 
    puts "FULL URL: #{"#{REPORT_PATH}/reports/#{REPORT_GROUP}/#{REPORT_NAME}"}" 
    uri = URI.parse("#{REPORT_PATH}/reports/#{REPORT_GROUP}/#{REPORT_NAME}") 
    http = Net::HTTP.new(uri_put.host, uri_put.port) 
    http.start do |http| 
     req = Net::HTTP::Put.new(uri_put.path + "?RUN_OUTPUT_FORMAT=#{FORMAT}") 
     puts "ACESSANDO: #{uri_put.path}?RUN_OUTPUT_FORMAT=#{FORMAT}" 
     req.basic_auth(SERVER_USER, SERVER_PASSWORD) 
     req.body = build_xml_request 
     resp = http.request(req) 
     body = resp.body 
     puts "COOKIE RECEBIDO: #{resp['Set-Cookie']}"  
     cookie = resp['Set-Cookie'] 
    end 

這是我的Python的片段腳本

def get_uuid_and_cookie(): 
    handle = None 
    req = urllib2.Request(REPORT_URI+"reports/"+REPORT_GROUP+"/"+REPORT_NAME+"/") 
    base64string = base64.encodestring('%s:%s' % (SERVER_USER, SERVER_PASSWORD))[:-1] 
    authheader = "Basic %s" % base64string 
    req.add_header("Authorization", authheader) 
    req.get_method = lambda: 'PUT' 
    req.data = build_xml_request() 
    try: 
     handle = urllib2.urlopen(req) 
    except IOError, e: 
     print "ERROR: "+str(e) 

在Ruby腳本中可以得到這樣一個cookie:

cookie = resp['Set-Cookie'] 

我該如何在Python中做到這一點?

回答

0

這應該工作

import urllib2 
from cookielib import CookieJar 
cj = CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
response = opener.open(my_url) 
    if response.getcode() == 200: 
     print 'now cj is the cookie' 
     for c in cj: 
      print c.name 
1

太好了! 我發現了一個簡單的回答我的問題考生處理結果

首先

print str(handle.__dict__) 
    { 
'fp': <socket._fileobject object at 0x7f0b44d534d0>, 
'fileno': <bound method _fileobject.fileno of <socket._fileobject object at 0x7f0b44d534d0>>, 
'code': 201, 
'read': <bound method _fileobject.read of <socket._fileobject object at 0x7f0b44d534d0>>, 
'readlines': <bound method _fileobject.readlines of <socket._fileobject object at 0x7f0b44d534d0>>, 
'next': <bound method _fileobject.next of <socket._fileobject object at 0x7f0b44d534d0>>, 
'headers': <httplib.HTTPMessage instance at 0x7f0b44d6bef0>, 
'__iter__': <bound method _fileobject.__iter__ of <socket._fileobject object at 0x7f0b44d534d0>>, 
'url': 'http://127.0.0.1:8080/jasperserver/rest/report/reports/Athenas/protocolo/', 'msg': 'Created', 
'readline': <bound method _fileobject.readline of <socket._fileobject object at 0x7f0b44d534d0>> 
} 

觀察變量httplib.HTTPMessage我發現我能得到的Set-Cookie後。

print handle.headers 
Server: Apache-Coyote/1.1 
Pragma: No-cache 
Cache-Control: no-cache 
Expires: Wed, 31 Dec 1969 16:00:00 PST 
P3P: CP="ALL" 
Set-Cookie: JSESSIONID=92826DC36E6DB54164C47744FE1605CB; Path=/jasperserver 
Content-Type: text/xml;charset=UTF-8 
Content-Length: 256 
Date: Wed, 06 Mar 2013 13:19:26 GMT 
Connection: close 

所以才需要還可以這樣:

cookie = handle.headers["Set-Cookie"] 

:d