本文整理匯總了Python中twisted.web.client.CookieAgent類的典型用法代碼示例。如果您正苦於以下問題:Python CookieAgent類的具體用法?Python CookieAgent怎麽用?Python CookieAgent使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了CookieAgent類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: updateShared_cb
def updateShared_cb(iv):
print "Updating file..."
args = ("updateshared", str(self.ccid), os.path.basename(s[3]), s[2])
salt = self.processCookie("/shares")
dataq = []
dataq.append( self.client_id.genHashArgs(args, salt))
dataq.append( iv )
# print "debugging:ticket, iv updatefile"
# print dataq[0]
# print dataq[1]
# print len(dataq[1])
print "Uploading file..."
agent = CookieAgent(Agent(reactor), self.cookie_jar)
enc_file = open("enc_fileout", 'r')
body = _FileProducer(enc_file ,dataq)
headers = http_headers.Headers()
d = agent.request(
'POST',
'http://localhost:8000/shares/?method=updateshared&ccid='
+ self.ccid + "&name=" + os.path.basename(s[3]) + "&fileid=" + s[2] ,
headers,
body)
d.addCallback(self.printPutReply_cb)
return NOT_DONE_YET
示例2: handleGetMData
def handleGetMData(self, data):
#data = (method, tgtccid)
pprint(data)
def handleGetMData_cb(response):
defer = Deferred()
defer.addCallback(data[0])
response.deliverBody(DataPrinter(defer, "getmdata"))
return NOT_DONE_YET
args = ("get_mdata", str(self.ccid), data[1])
salt = self.processCookie("/pboxes")
body = FileBodyProducer(StringIO(self.client_id.genHashArgs(args, salt)))
agent = CookieAgent(Agent(reactor), self.cookie_jar)
headers = http_headers.Headers()
d = agent.request(
'GET',
'http://localhost:8000/pboxes/?method=get_mdata&ccid='
+ self.ccid + "&tgtccid=" + data[1],
headers,
body)
d.addCallback(handleGetMData_cb)
return NOT_DONE_YET
示例3: handlePutFile
def handlePutFile(self, line):
print "Encrypting file..."
s = line.split()
file = open(s[2], 'r')
enc_file = open("enc_fileout", 'w')
crd = self.client_id.encryptFileSym(file, enc_file)
args = ("putfile", str(self.ccid), os.path.basename(s[2]))
salt = self.processCookie("/files")
dataq = []
dataq.append( self.client_id.genHashArgs(args, salt))
dataq.append( self.client_id.encryptData(crd[0], self.client_id.pub_key))
dataq.append( self.client_id.encryptData(crd[1]) )
agent = CookieAgent(Agent(reactor), self.cookie_jar)
#print crd[1]
# print "debugging:key, iv putfile"
# print dataq[1]
# print len(dataq[1])
# print dataq[2]
# print len(dataq[2])
print "Uploading file..."
enc_file = open("enc_fileout", 'r')
body = _FileProducer(enc_file ,dataq)
headers = http_headers.Headers()
d = agent.request(
'PUT',
'http://localhost:8000/files/?method=putfile&ccid='
+ self.ccid + "&name=" + os.path.basename(s[2]),
headers,
body)
d.addCallback(self.printPutReply_cb)
return NOT_DONE_YET
示例4: handleGetShared
def handleGetShared(self, s):
def handleGetShared_cb(response, f):
finished = Deferred()
finished.addCallback(self.writeFile_cb, s)
cons = FileConsumer(f)
response.deliverBody(FileDownload(finished, cons))
print "Downloading file..."
return finished
fileId = s[2]
args = ("getshared", str(self.ccid), str(fileId))
salt = self.processCookie("/shares")
body = FileBodyProducer(StringIO(self.client_id.genHashArgs(args, salt)))
agent = CookieAgent(Agent(reactor), self.cookie_jar)
headers = http_headers.Headers()
d = agent.request(
'GET',
'http://localhost:8000/shares/?method=getshared&ccid=' + self.ccid
+ '&fileid=' + fileId,
headers,
body)
f = open(fileId, "w")
d.addCallback(handleGetShared_cb, f)
return NOT_DONE_YET
示例5: main
def main():
cookieJar = CookieJar()
agent = CookieAgent(Agent(reactor), cookieJar)
d = agent.request('GET', 'http://www.google.com/')
d.addCallback(displayCookies, cookieJar)
d.addErrback(log.err)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()
示例6: http_request
def http_request(method, url, params={}, data=None, headers={}, cookies=None, timeout=30, ignore_errors=True):
# Urlencode does not accept unicode, so convert to str first
url = url.encode('utf-8') if isinstance(url, unicode) else url
for k, v in params.items():
params[k] = v.encode('utf-8') if isinstance(v, unicode) else v
for k, v in headers.items():
headers[k] = v.encode('utf-8') if isinstance(v, unicode) else v
# Add any additional params to the url
url_parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urllib.urlencode(query, doseq=True)
url = urlparse.urlunparse(url_parts)
# Handle cookies
if isinstance(cookies, cookielib.CookieJar):
cookiejar = cookies
else:
cookiejar = cookielib.CookieJar()
for name, value in (cookies or {}).iteritems():
cookiejar.set_cookie(create_cookie(name=name, value=value))
# Urlencode the data, if needed
if isinstance(data, dict):
data = urllib.urlencode(data)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
agent = Agent(reactor, connectTimeout=timeout)
cookie_agent = CookieAgent(agent, cookiejar)
body = FileBodyProducer(StringIO(data)) if data else None
d = cookie_agent.request(method, url, Headers({k: [v] for k, v in headers.iteritems()}), body)
def handle_response(response, cookiejar):
if 'audio/mpeg' in response.headers.getRawHeaders('content-type')[-1]:
# Don't download any multimedia files
raise Exception('reponse contains a multimedia file')
d = defer.Deferred()
response.deliverBody(BodyReceiver(response.code,
dict(response.headers.getAllRawHeaders()),
cookiejar,
d))
return d
def handle_error(error):
if isinstance(error, _WrapperException):
reason = ', '.join(error.reasons)
else:
reason = error.getErrorMessage()
logger = logging.getLogger(__name__)
logger.error('Failed to GET %s (reason: %s)', url, reason)
return Response(0, {}, cookielib.CookieJar(), '')
d.addCallback(handle_response, cookiejar)
if ignore_errors:
d.addErrback(handle_error)
return d
示例7: BaseCarRider
class BaseCarRider(object):
"""Базовый протокол такси-клиента"""
def __init__(self, host, port):
self.host = host
self.port = port
self.url = 'http://{0}:{1}/'.format(self.host, self.port)
self.agent = CookieAgent(Agent(reactor), CookieJar())
@defer.inlineCallbacks
def login(self):
response = yield self.agent.request('GET', self.url + "login")
assert response.code == 200
body = yield readBody(response)
data = json.loads(body)
assert data["result"] == "ok"
log.msg("Loggin in")
@defer.inlineCallbacks
def logout(self):
response = yield self.agent.request('GET', self.url + "logout")
assert response.code == 200
body = yield readBody(response)
data = json.loads(body)
assert data["result"] == "ok"
log.msg("Logged out")
@defer.inlineCallbacks
def send_location(self, latitude, longitude):
url = self.url + "data?latitude={0:.6f}&longitude={1:.6f}".format(latitude, longitude)
response = yield self.agent.request('GET', url)
assert response.code == 200
body = yield readBody(response)
data = json.loads(body)
assert data["result"] == "ok"
log.msg("Location update success!")
@defer.inlineCallbacks
def work(self):
yield task.deferLater(reactor, 0, self.login)
w = 56835567
l = 60590891
while True:
w += random.randint(-10000000, 10000000)/1000.0
l += random.randint(-10000000, 10000000)/1000.0
if w < 56838388:
w = 56838388
if w > 56839803:
w = 56839803
if l < 60552843:
l = 60552843
if l > 60574815:
l = 60574815
yield task.deferLater(reactor, 0, self.send_location,
w/1000000.0, l/1000000.0)
yield sleep(settings.WORKER_SLEEP_TIME)
yield task.deferLater(reactor, 0, self.logout)
示例8: HTTPClient
class HTTPClient(_HTTPClient):
def __init__(self, uuid, token, cert_file):
agent = Agent(uuid, token, cert_file)
jar = CookieJar()
self._agent = CookieAgent(agent, jar)
super(self.__class__, self).__init__(self._agent)
def set_token(self, token):
self._agent.set_token(token)
示例9: startSession_cb
def startSession_cb((signedNonce, nonceid)):
agent = CookieAgent(Agent(reactor), self.cookie_jar)
dataq = []
dataq.append(signedNonce)
body = _FileProducer(StringIO(self.client_id.encryptData(self.client_id.password)) ,dataq)
headers = http_headers.Headers()
d = agent.request(
'PUT',
'http://localhost:8000/session/?method=startsession&ccid='
+ self.ccid + '&nonceid=' + str(nonceid),
headers,
body)
d.addCallback(procResponse_cb)
return NOT_DONE_YET
示例10: register_cb
def register_cb((signedNonce, nonceid)):
agent = CookieAgent(Agent(reactor), self.cookie_jar)
dataq = []
dataq.append(signedNonce)
dataq.append(self.client_id.encryptData(self.client_id.password))
# Sending the Certificate and the Sub CA to the server
if self.pin is None:
print "ERROR! Check the pin!"
reactor.stop()
cert = cc.get_certificate(cc.CERT_LABEL, self.pin)
#print type(cert.as_pem())
#print cert.as_pem()
if cert is None:
print "ERROR! Check the pin"
reactor.stop()
subca = cc.get_certificate(cc.SUBCA_LABEL, self.pin)
#print type(subca.as_pem())
#print subca.as_pem()
if subca is None:
print "ERROR! Check the pin"
reactor.stop()
enc_cert = b64encode(cert.as_pem())
#print "cert len: ", len(enc_cert)
dataq.append(enc_cert)
enc_subca = b64encode(subca.as_pem())
#print "sub ca len: ", len(enc_subca)
dataq.append(enc_subca)
dataq.append(self.client_id.pub_key.exportKey('PEM'))
ext_key = self.client_id.pub_key.exportKey('PEM')
if self.pin is None:
print "ERROR! Check the pin or the CC"
reactor.stop()
signed_ext_key = cc.sign(ext_key, cc.KEY_LABEL, self.pin)
enc_sek = b64encode(signed_ext_key)
#print "encoded ext key: ", enc_sek
#print "len encoded: ", len(enc_sek)
dataq.append(enc_sek)
body = FileProducer2(dataq)
headers = http_headers.Headers()
#print "Password:", self.client_id.encryptData(self.client_id.password)
#print "LEN:", len(self.client_id.encryptData(self.client_id.password))
d = agent.request(
'PUT',
'http://localhost:8000/pboxes/?method=register'
+ '&nonceid=' + str(nonceid),
headers,
body)
d.addCallback(procResponse_cb, checkClientReg_cb)
示例11: handleListShares
def handleListShares(self):
args = ("list", str(self.ccid))
salt = self.processCookie("/shares")
body = FileBodyProducer(StringIO(self.client_id.genHashArgs(args, salt)))
agent = CookieAgent(Agent(reactor), self.cookie_jar)
headers = http_headers.Headers()
d = agent.request(
'GET',
'http://localhost:8000/shares/?method=list&ccid='
+ self.ccid,
headers,
body)
d.addCallback(self.handleList_cb)
return NOT_DONE_YET
示例12: authenticate
def authenticate(self):
#self.session_id = cb_authenticate(self.auth_url)
self.logger.info("Authenticating")
cookieJar = CookieJar()
agent = CookieAgent(Agent(self.reactor), cookieJar)
data = '{"key": "' + self.auth_key + '"}'
print "self.auth_url is", self.auth_url
d = agent.request(
'POST',
self.auth_url,
Headers({'User-Agent': ['Twisted Web Client Example'],
'content-type': ['application/json']}),
StringProducer(data))
d.addCallback(self.handleAuthResponse, cookieJar)
d.addErrback(self.handleAuthFailed)
示例13: deleteShare_cb
def deleteShare_cb():
args = ("delete", str(self.ccid), s[2], s[3])
salt = self.processCookie("/shares")
body = FileBodyProducer(StringIO(self.client_id.genHashArgs(args, salt)))
agent = CookieAgent(Agent(reactor), self.cookie_jar)
headers = http_headers.Headers()
d = agent.request(
'DELETE',
'http://localhost:8000/shares/?method=delete&ccid='
+ self.ccid + "&fileid=" + s[2] + "&rccid=" + s[3],
headers,
body)
d.addCallback(printDeleteReply_cb)
示例14: handleUpdateSharePerm
def handleUpdateSharePerm(self, s):
args = ("updateshareperm", str(self.ccid), s[3], s[2], s[4])
salt = self.processCookie("/shares")
body = FileBodyProducer(StringIO(self.client_id.genHashArgs(args, salt)))
agent = CookieAgent(Agent(reactor), self.cookie_jar)
headers = http_headers.Headers()
d = agent.request(
'POST',
'http://localhost:8000/shares/?method=updateshareperm&ccid='
+ self.ccid + "&rccid=" + s[3] + "&fileid=" + s[2] + "&writeable=" + s[4] ,
headers,
body)
d.addCallback(self.printPutReply_cb)
return NOT_DONE_YET
示例15: main
def main():
c = Cookie(None, 'sid', '157272379', '443', '443', "10.0.199.8", None, None, '/', None, False, False, 'TestCookie', None, None, None)
cj = CookieJar()
cj.set_cookie(c)
print ">>> cj:", cj
contextFactory = WebClientContextFactory()
agent = CookieAgent(RedirectAgent(Agent(reactor, contextFactory)), cj)
d = agent.request('GET', 'https://10.0.199.8/datetime_get_request_periodic')
d.addCallbacks(getBody, log.err)
d.addCallback(lambda x: reactor.stop())
reactor.run()