本文整理汇总了Python中urllib2.Request.get_data方法的典型用法代码示例。如果您正苦于以下问题:Python Request.get_data方法的具体用法?Python Request.get_data怎么用?Python Request.get_data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib2.Request
的用法示例。
在下文中一共展示了Request.get_data方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: hit_endpoint
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_data [as 别名]
def hit_endpoint(self, url, data_dict={}, http_method='GET'):
"""
A reusable method that actually performs the request to the specified Atlas API endpoint.
"""
if self.verbose == 'true':
print "HIT_ENDPOINT"
data_dict.update({ "access_token" : self.access_token })
if self.verbose == 'true':
print " Added access_token to data_dict (inside hit_endpoint)"
if self.verbose == 'true':
print " Constructing request URL"
request = Request(url, urllib.urlencode(data_dict))
if self.verbose == 'true':
print " Setting request http_method: %s" % http_method
request.get_method = lambda: http_method
try:
if self.verbose == 'true':
print " Opening Request URL: %s?%s" % (request.get_full_url(),request.get_data())
response = urlopen(request)
except URLError, e:
raise SystemExit(e)
示例2: post
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_data [as 别名]
def post(self, baseurl, body, ssl=False):
if not ssl:
url = baseurl
else:
url = sub('http://', 'https://', baseurl)
print url
key = {'key': open(os.path.expanduser('~/.tdld/state')).read()}
data = sub(r'\'', '"', sub(r'\s', '', unquote_plus(urlencode(dict(key, **body)))))
try:
request = Request(url = url,
data = data)
print request.get_data()
response = urlopen(request)
except IOError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
示例3: getNextAgent
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_data [as 别名]
def getNextAgent(self,msg):
from urllib import urlencode
from urllib2 import urlopen, Request
from config import IVRSettings as SETTINGS
#get next available agent
log.info("in CallCenterVectorManager.getNextAgent()")
#get message contents
loadedMessage = simplejson.loads(msg.body)
ccxmlSessionID = loadedMessage['session']
ccxmlUniqueID = loadedMessage['id']
#get available agents
#returns <Agent Instance>
agents = self.agentGateway.getAvailableAgentsByIdleTime()
#use our selected UCD_MIA algorithm to select the next agent
agentWithMostIdleTime = self.algo.getNextAgent(agents)
if agentWithMostIdleTime:
#create call with agent
call = self.callGateway.addCall(agent=agentWithMostIdleTime)
#update agent phone status
agentWithMostIdleTime=self.agentGateway.updateAgentPhoneStatus(agentWithMostIdleTime,1)
#inject event into ccxml session
data = urlencode({SETTINGS.IVR_SESSION_KEY:ccxmlSessionID, SETTINGS.IVR_EVENT_KEY:SETTINGS.IVR_EVENT_VALUE, \
SETTINGS.IVR_UNIQUE_ID_KEY:ccxmlUniqueID, SETTINGS.IVR_AGENT_ANI_KEY:agentWithMostIdleTime.ani, \
SETTINGS.IVR_DESTINATION_TYPE_KEY: agentWithMostIdleTime.determineANIType(), \
SETTINGS.IVR_CALL_ID_KEY: call.call_id})
url = SETTINGS.IVR_URL
request = Request(url, data)
log.info("ccxml url: " + request.get_full_url() + request.get_data())
response = urlopen(request)
if response:
log.info("Agent assigned to call sucessfully")
else:
log.info("Agent assigned to call unsucessfully")
else:
#No agent was found
#send call back to queue
publisher_args = {MQConfig.DEFAULT_ROUTING_KEY_KEY: MQConfig.DEFAULT_ROUTING_KEY_VALUE,
MQConfig.DEFAULT_DELIVERY_MODE_KEY: MQConfig.DEFAULT_DELIVERY_MODE,
MQConfig.DEFAULT_EXCHANGE_VALUE_KEY: MQConfig.DEFAULT_EXCHANGE_VALUE
}
publisher = CallCenterVectorPublisher(**publisher_args)
#setup message
msg = simplejson.dumps({'session': ccxmlSessionID , 'id': ccxmlUniqueID})
log.info("message dumped as json")
publisher.publish_to_queue(msg)
log.info("message pushed to queue")
publisher.close()
示例4: form_valid
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_data [as 别名]
def form_valid(self, form):
"""
Override form_valid functionality to send message via GCM to Android
devices with new TourConfig
"""
self.object = form.save(commit=False)
push_ids = self.get_push_ids()
headers = {}
headers[settings.GCM_API_KEY_HEADER] = 'key='+settings.GCM_API_KEY
headers['Content-Type'] = 'application/json'
data = {}
data['registration_ids'] = push_ids
# Hack-y fix to get just the fields from the TourConfig instance
newconfig = json.loads(serializers.serialize('json', [self.object]))[0]['fields']
# Multiple the unix times stored in the database by 1000 because Android
# uses milliseconds
newconfig['start_time'] = newconfig['start_time']*1000
newconfig['max_tour_time'] = newconfig['max_tour_time']*1000
newconfig['max_tour_time'] = newconfig['max_tour_time'] - newconfig['start_time']
data['data'] = {}
data['data'][settings.JSON_KEYS['TOUR_CONFIG']] = newconfig
# Comment out the following line to actually send messages
#data['dry_run'] = True
req = Request(settings.GCM_SEND_URL, json.dumps(data), headers)
if len(push_ids) > 0:
logger.debug('Sending request to GCM server:\n%s' % req.get_data())
resp = urlopen(req)
# TODO
# Display a message on failure to send GCM message
else:
logger.debug('No push_ids registered; not sending updated config.')
self.object = form.save()
messages.success(self.request, 'Tour updated successfully.')
set_server_polling_rate()
return HttpResponseRedirect(self.get_success_url())
示例5: odoo_write
# 需要导入模块: from urllib2 import Request [as 别名]
# 或者: from urllib2.Request import get_data [as 别名]
#.........这里部分代码省略.........
- The XML file uploaded is not exactly the standard XML of frePPLe, but a
slight variation that fits odoo better.
- This code doesn't interprete any of the results. An odoo addon module
will need to read the content, and take appropriate actions in odoo:
such as creating purchase orders, manufacturing orders, work orders,
project tasks, etc...
'''
odoo_user = Parameter.getValue("odoo.user", db)
odoo_password = Parameter.getValue("odoo.password", db)
odoo_db = Parameter.getValue("odoo.db", db)
odoo_url = Parameter.getValue("odoo.url", db)
odoo_company = Parameter.getValue("odoo.company", db)
ok = True
if not odoo_user:
print("Missing or invalid parameter odoo.user")
ok = False
if not odoo_password:
print("Missing or invalid parameter odoo.password")
ok = False
if not odoo_db:
print("Missing or invalid parameter odoo.db")
ok = False
if not odoo_url:
print("Missing or invalid parameter odoo.url")
ok = False
if not odoo_company:
print("Missing or invalid parameter odoo.company")
ok = False
odoo_language = Parameter.getValue("odoo.language", db, 'en_US')
if not ok:
raise Exception("Odoo connector not configured correctly")
boundary = email.generator._make_boundary()
# Generator function
# We generate output in the multipart/form-data format.
# We send the connection parameters as well as a file with the planning
# results in XML-format.
def publishPlan():
yield '--%s\r' % boundary
yield 'Content-Disposition: form-data; name="database"\r'
yield '\r'
yield '%s\r' % odoo_db
yield '--%s\r' % boundary
yield 'Content-Disposition: form-data; name="language"\r'
yield '\r'
yield '%s\r' % odoo_language
yield '--%s\r' % boundary
yield 'Content-Disposition: form-data; name="company"\r'
yield '\r'
yield '%s\r' % odoo_company
yield '--%s\r' % boundary
yield 'Content-Disposition: file; name="frePPLe plan"; filename="frepple_plan.xml"\r'
yield 'Content-Type: application/xml\r'
yield '\r'
yield '<?xml version="1.0" encoding="UTF-8" ?>'
yield '<plan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
# Export relevant operationplans
yield '<operationplans>'
for i in frepple.operationplans():
b = None
for j in i.flowplans:
if j.quantity > 0:
b = j.flow.buffer
if not b or b.source != 'odoo' or i.locked:
continue
yield '<operationplan id="%s" operation=%s start="%s" end="%s" quantity="%s" location=%s item=%s criticality="%d"/>' % (
i.id, quoteattr(i.operation.name),
i.start, i.end, i.quantity,
quoteattr(b.location.subcategory), quoteattr(b.item.subcategory),
int(i.criticality)
)
yield '</operationplans>'
yield '</plan>'
yield '--%s--\r' % boundary
yield '\r'
# Connect to the odoo URL to POST data
try:
req = Request("%s/frepple/xml/" % odoo_url.encode('ascii'))
body = '\n'.join(publishPlan()).encode('utf-8')
size = len(body)
encoded = base64.encodestring('%s:%s' % (odoo_user, odoo_password)).replace('\n', '')
req.add_header("Authorization", "Basic %s" % encoded)
req.add_header("Content-Type", 'multipart/form-data; boundary=%s' % boundary)
req.add_header('Content-length', size)
req.add_data(body)
# Posting the data
print("Uploading %d bytes of planning results to odoo" % size)
req.get_data()
# Display the server response, which can contain error messages
print("Odoo response:")
for i in urlopen(req):
print(i, end="")
print("")
except HTTPError as e:
print("Error connecting to odoo", e.read())
raise e