本文整理汇总了Python中httplib.HTTP.getfile方法的典型用法代码示例。如果您正苦于以下问题:Python HTTP.getfile方法的具体用法?Python HTTP.getfile怎么用?Python HTTP.getfile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类httplib.HTTP
的用法示例。
在下文中一共展示了HTTP.getfile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: action_delete
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def action_delete():
vip = sys.argv[3]
h = HTTP('home.shaunkruger.com:8087')
h.putrequest('DELETE','/module/mod_cluster_admin/vip/'+vip)
h.putheader('Authorization','Basic '+base64.standard_b64encode('skruger:testing'))
h.endheaders()
errcode, errmsg, headers = h.getreply()
if errcode == 200:
f = h.getfile()
print f.read()
return
示例2: gethttpfile
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def gethttpfile(url, size=1024*1024):
from urllib import splithost
from httplib import HTTP
if not url.startswith('http:'):
raise ValueError, "URL %s" % url
host, selector = splithost(url[5:])
h = HTTP(host)
h.putrequest('GET', url)
h.endheaders()
h.getreply()
res = h.getfile().read(size)
h.close()
return res
示例3: RetrieveAsFile
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def RetrieveAsFile(self, host, path=''):
from httplib import HTTP
try:
h = HTTP(host)
except:
self.logprint("Failed to create HTTP connection to %s... is the network available?" % (host))
return None
h.putrequest('GET',path)
h.putheader('Accept','text/html')
h.putheader('Accept','text/plain')
h.endheaders()
errcode, errmsg, headers = h.getreply()
if errcode != 200:
self.logprint("HTTP error code %d: %s" % (errcode, errmsg))
return None
f = h.getfile()
return f
示例4: __makeRequest
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def __makeRequest(self, url, path):
from httplib import HTTP
http = HTTP(HTTP_PROXY or url.replace("http://", ""))
http.putrequest("GET", url + path)
http.putheader("Accept", "text/plain")
http.endheaders()
htcode, errmsg, headers = http.getreply()
if htcode not in (200, 403, 404):
raise HTTPCaptachaUnexpectedResponse(htcode, errmsg)
# endif
file = http.getfile()
content = file.read()
file.close()
return htcode, content
示例5: action_list
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def action_list():
h = HTTP(surrogate_conf.get('hostname'))
h.putrequest('GET','/module/mod_cluster_admin/vip')
userpass = "%s:%s" % (surrogate_conf.get('username'),surrogate_conf.get('password'))
h.putheader('Authorization','Basic '+base64.standard_b64encode(userpass))
h.endheaders()
errcode, errmsg, headers = h.getreply()
if errcode == 200:
f = h.getfile()
data= f.read()
vip = json.loads(data) # Convert json string to python array object
formatstr = "%-35s %-8s %s" # reusable format string for header and data output lines
print formatstr % ("Address", "Status","Nodes")
print "==============================================================================="
for v in vip["items"]:
print formatstr % (v["address"], v["status"],v["nodes"])
elif errcode == 401:
print "Authentication error."
else:
print "HTTP %s: %s" % (errcode,errmsg)
return
示例6: server_lookup
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def server_lookup(self, addr):
req = HTTP("deinadmin.de")
req.putrequest("GET", "/projects/pharmcheck/pharmcheck.php?name=" + addr)
req.putheader("Host", "deinadmin.de")
req.putheader("User-Agent", "pharmcheck v0.3 2005-08-14")
req.endheaders()
ec, em, h = req.getreply()
if (ec != 200):
return [-2, ec, em]
else:
fd=req.getfile()
lines=[]
line=fd.readline()
while line:
lines.append(line[:-1]) # \n abschneiden. windows-kompatibel?
line=fd.readline()
fd.close()
return [1, lines]
示例7: get
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def get(host,port,url):
concaturl = host+url
print "Checking Host:",concaturl
h = HTTP(host, port)
h.putrequest('GET', url)
h.putheader('Host', host)
h.putheader('User-agent', 'python-httplib')
h.endheaders()
time.sleep(1)
(returncode, returnmsg, headers) = h.getreply()
if returncode != 200:
print returncode,returnmsg
return returncode
else:
f = h.getfile()
# return f.read() #returns content of page for further parsing
print returncode, returnmsg
return returncode
示例8: send_request
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def send_request(self, request, response):
h = HTTP(urlparse(request.uri)[1]) #TODO: split out port, userinfo
h.putrequest(request.method, request.uri)
for field_name, field_value in request.representation.headers.items():
if field_name == "Content-Length": continue
h.putheader(field_name, field_value.string)
if request.representation.has_body:
h.putheader('Content-Length', str(len(request.representation.body))) #FIXME: hmm. accesses body. options?
h.putheader('User-Agent', self.user_agent) # FIXME: use header dict, don't override
h.endheaders()
if request.representation.has_body:
h.send(request.representation.body) #FIXME: use iterator?
status_code, status_phrase, headers = h.getreply()
response_type = status.lookup.get(status_code, None)
if response_type is not None:
response.__class__ = response_type
response.status_code = status_code
response.status_phrase = status_phrase
response.representation.headers.parseMessage(headers) #FIXME: split entity and message hdrs
response.representation._body_iter = h.getfile() #FIXME: iterator, shouldn't have to do this _ ...
if not isinstance(response, status.Successful):
raise response
示例9: download_web_page
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def download_web_page(domain, url):
try:
h = HTTP(domain)
h.putrequest("GET", url)
h.putheader('Accept', 'text/html')
h.putheader('Accept', 'text/plain')
h.endheaders()
except:
return(None)
print "Placed request, downloading web page..."
try:
errcode, errmsg, headers = h.getreply()
except:
sys.stderr.write("Error in receiving response from " + domain + \
'\n')
return None
if errcode != 200:
sys.stderr.write("Error in receiving response from " + domain + \
'\n')
return None
results = h.getfile().read()
return(results)
示例10: HTTP
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
from httplib import HTTP
req = HTTP("www.zoo-berlin.de")
req.putrequest("GET", "/?Knut")
req.putheader("Accept", "text/html")
req.putheader("User-Agent", "Python26")
req.endheaders()
ec, em, h = req.getreply()
print ec, em
fd = req.getfile()
textlines = fd.read()
print textlines
fd.close()
示例11: __call__
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def __call__(self,*args,**kw):
method=self.method
if method=='PUT' and len(args)==1 and not kw:
query=[args[0]]
args=()
else:
query=[]
for i in range(len(args)):
try:
k=self.args[i]
if kw.has_key(k): raise TypeError, 'Keyword arg redefined'
kw[k]=args[i]
except IndexError: raise TypeError, 'Too many arguments'
headers={}
for k, v in self.headers.items(): headers[translate(k,dashtrans)]=v
method=self.method
if headers.has_key('Content-Type'):
content_type=headers['Content-Type']
if content_type=='multipart/form-data':
return self._mp_call(kw)
else:
content_type=None
if not method or method=='POST':
for v in kw.values():
if hasattr(v,'read'): return self._mp_call(kw)
can_marshal=type2marshal.has_key
for k,v in kw.items():
t=type(v)
if can_marshal(t): q=type2marshal[t](k,v)
else: q='%s=%s' % (k,quote(v))
query.append(q)
url=self.rurl
if query:
query='&'.join(query)
method=method or 'POST'
if method == 'PUT':
headers['Content-Length']=str(len(query))
if method != 'POST':
url="%s?%s" % (url,query)
query=''
elif not content_type:
headers['Content-Type']='application/x-www-form-urlencoded'
headers['Content-Length']=str(len(query))
else: method=method or 'GET'
if (self.username and self.password and
not headers.has_key('Authorization')):
headers['Authorization']=(
"Basic %s" %
encodestring('%s:%s' % (self.username,self.password)).replace(
'\012','')
)
try:
h=HTTP(self.host, self.port)
h.putrequest(method, self.rurl)
for hn,hv in headers.items():
h.putheader(translate(hn,dashtrans),hv)
h.endheaders()
if query: h.send(query)
ec,em,headers=h.getreply()
response =h.getfile().read()
except:
raise NotAvailable, RemoteException(
NotAvailable,sys.exc_info()[1],self.url,query)
if (ec - (ec % 100)) == 200:
return (headers,response)
self.handleError(query, ec, em, headers, response)
示例12: str
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
('Accept-Language', 'en'),
('Pragma', 'no-cache'),
('Cache-Control', 'no-cache'),
('User-Agent', 'Lynx/2.6 libwww-FM/2.14'),
('From', '"a-fan" <[email protected]>'),
('Referer', 'http://www.comcentral.com/mst/mstpoll.htm'),
('Content-type', 'application/x-www-form-urlencoded'),
('Content-length', '8')]
text='vote=' + str(episode)
n = n - 1
h = HTTP('www.comcentral.com')
h.debuglevel = 1
h.putrequest('POST', '/cgi-bin/rbox/pollboy.pl')
for (hn, hv) in headers:
if (hn == 'From'):
hv = 'user' + str(n) + '@blah.com'
h.putheader(hn, hv)
#print "hn:", hn, "hv:", hv
h.endheaders()
h.send(text)
errcode, errmsg, headers = h.getreply()
if errcode == 200:
f = h.getfile()
print f.read() # Print the raw HTML
示例13: splithost
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
import sys
from urllib import splithost
from httplib import HTTP
if os.path.exists("/dev/shm"):
TMPDIR="/dev/shm"
else:
TMPDIR="/tmp"
TMPDIR += "/hda-analyzer"
print "Using temporary directory: %s" % TMPDIR
print "You may remove this directory when finished or if you like to"
print "download the most recent copy of hda-analyzer tool."
if not os.path.exists(TMPDIR):
os.mkdir(TMPDIR)
for f in FILES:
dest = TMPDIR + '/' + f
if os.path.exists(dest):
print "File cached " + dest
continue
print "Downloading file %s" % f
host, selector = splithost(URL[5:])
h = HTTP(host)
h.putrequest('GET', URL + f)
h.endheaders()
h.getreply()
contents = h.getfile().read(2*1024*1024)
h.close()
open(dest, "w+").write(contents)
print "Downloaded all files, executing %s" % FILES[0]
os.system("python %s" % TMPDIR + '/' + FILES[0] + ' ' + ' '.join(sys.argv[1:]))
示例14: __call__
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
def __call__(self, *args, **kw):
method = self.method
if method == "PUT" and len(args) == 1 and not kw:
query = [args[0]]
args = ()
else:
query = []
for i in range(len(args)):
try:
k = self.args[i]
if kw.has_key(k):
raise TypeError, "Keyword arg redefined"
kw[k] = args[i]
except IndexError:
raise TypeError, "Too many arguments"
headers = {}
for k, v in self.headers.items():
headers[translate(k, dashtrans)] = v
method = self.method
if headers.has_key("Content-Type"):
content_type = headers["Content-Type"]
if content_type == "multipart/form-data":
return self._mp_call(kw)
else:
content_type = None
if not method or method == "POST":
for v in kw.values():
if hasattr(v, "read"):
return self._mp_call(kw)
can_marshal = type2marshal.has_key
for k, v in kw.items():
t = type(v)
if can_marshal(t):
q = type2marshal[t](k, v)
else:
q = "%s=%s" % (k, quote(v))
query.append(q)
url = self.rurl
if query:
query = join(query, "&")
method = method or "POST"
if method == "PUT":
headers["Content-Length"] = str(len(query))
if method != "POST":
url = "%s?%s" % (url, query)
query = ""
elif not content_type:
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Content-Length"] = str(len(query))
else:
method = method or "GET"
if self.username and self.password and not headers.has_key("Authorization"):
headers["Authorization"] = "Basic %s" % gsub(
"\012", "", encodestring("%s:%s" % (self.username, self.password))
)
try:
h = HTTP()
h.connect(self.host, self.port)
h.putrequest(method, self.rurl)
for hn, hv in headers.items():
h.putheader(translate(hn, dashtrans), hv)
h.endheaders()
if query:
h.send(query)
ec, em, headers = h.getreply()
response = h.getfile().read()
except:
raise NotAvailable, RemoteException(NotAvailable, sys.exc_value, self.url, query)
if ec == 200:
return (headers, response)
self.handleError(query, ec, em, headers, response)
示例15: compile
# 需要导入模块: from httplib import HTTP [as 别名]
# 或者: from httplib.HTTP import getfile [as 别名]
errcode, errmsg, headers = http.getreply()
if errcode != 200:
print "Content-Type: text/html"
print
print "<html><body>Failed to load URL: %d</body></html>" % errcode
else:
if headers.has_key("Content-Type"):
print "Content-Type: " + headers["Content-Type"]
else:
print "Content-Type: text/plain"
print
file = http.getfile()
whole_body_re = compile("(?P<before>.*)(?P<body>\\<[bB][oO][dD][yY]( [^>]*)?\\>)(?P<after>.*)")
begin_body_re = compile("(?P<before>.*)(?P<body>\\<[bB][oO][dD][yY])(?P<after>.*)")
end_body_re = compile("(?P<before>.*)(?P<body>\\>)(?P<after>.*)")
whole_head_re = compile("(?P<before>.*)(?P<head>\\<[hH][eE][aA][dD]( [^>]*)?\\>)(?P<after>.*)")
begin_head_re = compile("(?P<before>.*)(?P<head>\\<[hH][eE][aA][dD])(?P<after>.*)")
end_head_re = compile("(?P<before>.*)(?P<head>\\>)(?P<after>.*)")
base_href_re = compile("(http://([^/]*/)*)[^/]*")
body_not_found = 1
body_begin_found = 0
head_not_found = 1
head_begin_found = 0
script = "<script id=\"inspector-script\" src=\"http://YOUR-HOST-HERE/PATH/inspector.js\"></script>"
base = "<base href=\"" + base_href_re.match(form["url"].value).group(1) + "\">"