本文整理汇总了Python中connection.Connection.request方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.request方法的具体用法?Python Connection.request怎么用?Python Connection.request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.request方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import request [as 别名]
def send(self, secure=True):
"""Sends the generated query off to encoding.com, returning the result
:param secure: Use encoding.com's HTTPS service if true
:type secure: bool
:returns: xml.etree.ElementTree.Element, the XML result from encoding.com
:raises: ActionAlrestSentError
"""
if self.already_sent:
raise ActionAlreadySentError()
else:
c = Connection(secure)
result = c.request(self.query)
self.alredy_sent = True
return result
示例2: Client
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import request [as 别名]
class Client(object):
'''
A client to access the Grok HTTP API.
* [key] - Grok API Key
* [baseURL] - Grok server request target
* [connection] - An instance of the grokpy.Connection class. Used mainly for
testing.
* [headers] - Overrides for auth and user agent headers. Used mainly for
testing.
* [proxies] - Dict - e.g. {"http": "10.10.1.10:3128", "https": "10.10.1.10:1080"}
'''
def __init__(self, key = None,
baseURL = None,
connection = None,
headers = None,
proxies = None):
if headers is None:
headers = {}
# Create a connection to the API
if not connection:
if baseURL:
self.c = Connection(key, baseURL, headers = headers, proxies = proxies)
else:
self.c = Connection(key, headers = headers, proxies = proxies)
else:
self.c = connection
# Test the connection works and get the User info
self.user = self.getUser()
#############################################################################
# User Methods
def getUser(self, userId = None):
'''
Returns a User object. By default returns the first user associated with
this API key.
* [userId]
'''
url = '/users'
rv = self.c.request('GET', url)
# By default return the first user.
if not userId:
user = User(rv['users'][0])
return user
# Otherwise return the first user with a matching Id
else:
for userDict in rv['users']:
if userDict['id'] == userId:
return User(userDict)
# We didn't find the user
raise GrokError('There were no users, or the userId you specified was not '
'found.')
#############################################################################
# Model Methods
def createModel(self, spec, parent = None, url = None):
'''
Returns a Model object.
* spec - A configuration for this model. Can be EITHER a file path to a
JSON document OR a Python dict
* [parent] - A Project object which associates this model with a specific
parent project.
* [url] - The target for creating this model. Automatically specified
when calling project.createModel() rather than client.createModel().
'''
# Process the given spec
modelSpec = self._handelAmbiguousSpec(spec)
if not parent:
parent = self
if not url:
url = self.user.modelsUrl
requestDef = {'model': modelSpec}
result = self.c.request('POST', url, requestDef)
if grokpy.DEBUG:
print result
return Model(parent, result['model'])
def getModel(self, modelId, url = None):
'''
Returns a Model object corresponding to the given modelId
* modelId
* [url] - Usually only specified when calling the equivalent method on a
project.
#.........这里部分代码省略.........
示例3: raw_ssl_request
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import request [as 别名]
def raw_ssl_request(method, endpoint, body, headers=None):
connection = Connection(endpoint)
return connection.request(method, body, headers)
示例4: MixpanelQueryClient
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import request [as 别名]
class MixpanelQueryClient(object):
"""
Connects to the `Mixpanel Data Export API`
and provides an interface to query data based on the project
specified with your api credentials.
Full API Docs: https://mixpanel.com/docs/api-documentation/data-export-api
"""
ENDPOINT = 'http://mixpanel.com/api'
VERSION = '2.0'
UNIT_MINUTE = 'minute'
UNIT_HOUR = 'hour'
UNIT_DAY = 'day'
UNIT_WEEK = 'week'
UNIT_MONTH = 'month'
VALID_UNITS = (UNIT_MINUTE, UNIT_HOUR, UNIT_DAY, UNIT_WEEK, UNIT_MONTH)
FORMAT_JSON = 'json'
FORMAT_CSV = 'csv'
VALID_RESPONSE_FORMATS = (FORMAT_JSON, FORMAT_CSV)
DATA_TYPE_GENERAL = 'general'
DATA_TYPE_AVERAGE = 'average'
DATA_TYPE_UNIQUE = 'unique'
VALID_DATA_TYPES = (DATA_TYPE_GENERAL, DATA_TYPE_AVERAGE, DATA_TYPE_UNIQUE)
def __init__(self, api_key, api_secret, timeout=None, auth_class=SignatureAuth):
self.api_key = _totext(api_key)
self.api_secret = _totext(api_secret)
self.timeout = timeout
self.connection = Connection(self)
self.auth = auth_class(self)
# Annotation methods ##############
def annotations_list(self, start_date, end_date, response_format=FORMAT_JSON):
"""
List the annotations for the given date range.
Args:
`start_date`: [str] The beginning of the date range to get annotations for in yyyy-mm-dd
format. This date is inclusive.
[sample]: "2014-04-01"
`end_date`: [str] The end of the date range to get annotations for in yyyy-mm-dd format.
This date is inclusive.
[sample]: "2014-04-01"
`response_format`: [string (optional)]: The data return format.
[sample]: "json" or "csv"
Response format:
{
'annotations': [
{'date': '2014-05-23 00:00:00', 'project_id': 23880, 'id': 148, 'description': 'Launched v2.0 of product'},
{'date': '2014-05-29 00:00:00', 'project_id': 23880, 'id': 150, 'description': 'Streamlined registration process'}
],
'error': false
}
"""
start_date_obj = self._validate_date(start_date)
end_date_obj = self._validate_date(end_date)
# Check the actual dates
if start_date_obj > end_date_obj:
raise exceptions.InvalidDateException('The `start_date` specified after the `end_date`; you will not receive any annotations.')
return self.connection.request(
'annotations',
{
'from_date': start_date,
'to_date': end_date,
},
response_format=response_format
)
def annotation_create(self, date, description, response_format=FORMAT_JSON):
"""
Create a new annotation at the specified time.
Args:
`date`: [str] The time in yyyy-mm-hh HH:MM:SS when you want to create the annotation at.
[sample]: "2014-04-01 02:12:44"
`description`: [str] The annotation description.
[sample]: "Something happened on this date."
`response_format`: [string (optional)]: The data return format.
[sample]: "json" or "csv"
Response format:
{
'error': false
}
"""
date_obj = self._validate_date(date)
return self.connection.request(
'annotations/create',
{
'date': date_obj.strftime('%Y-%m-%d %H:%M:%S'),
'description': description,
},
response_format=response_format
)
def annotation_update(self, annotation_id, date, description, response_format=FORMAT_JSON):
"""
Update an existing annotation with a new description.
Args:
#.........这里部分代码省略.........
示例5: Api
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import request [as 别名]
class Api(object):
def __init__(self, username=None, password=None, options=None):
if not options:
options = {}
self.options = options
if not username or not password:
# if not login specified, register a new account
user = self._random_register()
username = user.get('email')
password = user.get('password')
self.username = username
self.password = password
self.connection = Connection(self.username, self.password)
self.connection.proxy = options.get('proxy')
self.routes = self.populate_routes()
def populate_routes(self):
# TODO routes class populate
xml_resp = self.connection.request(xml=None, type=RequestType.routes)
routes = xmltodict.parse(xml_resp)
if not routes.get('xaresponse'):
raise Exception('Could not populate routes, malformed API response')
return routes.get('xaresponse').get('entitylist').get('userroutepricing')
def _get_route_id(self, number):
# get the user route id for the current number
# changes based on country of recipient
user_route_id = None
for route in self.routes:
try:
if number.startswith(route.get('countryCode')):
user_route_id = route.get('userRouteId')
break
except Exception:
user_route_id = self.routes.get('userRouteId')
if not user_route_id:
raise Exception('Could not determine user route id')
return user_route_id
def send(self, originator, recipient, message):
route_id = self._get_route_id(recipient)
data = {
'originator': originator,
'recipient': recipient,
'body': message,
'reference': utils.random_number(),
'routeId': route_id,
}
xml_resp = self.connection.request(xml=data, type=RequestType.single_message)
resp = xmltodict.parse(xml_resp)
if not resp.get('xaresponse').get('message').get('id'):
raise Exception('Message send failed')
return True
def _random_register(self):
url = 'http://www.mobivate.com/do_signup.php'
email = utils.random_number() + '@mailinator.com'
password = utils.random_salt()
data = {
'company': '',
'currency': 'USD', # must be USD or API will return less routes
'email': email,
'fullname': utils.random_salt(),
'mobile': '447' + utils.random_number(),
'password': password,
'password2': password,
}
r = requests.post(url, data=data)
json_resp = json.loads(r.text)
if json_resp.get('ok'): # registration successful
user = {
'email': email,
'password': password,
}
return user
else: # registration failed
return {}