_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q271400
RestSession.request
test
def request(self, method, url, erc, **kwargs): """Abstract base method for making requests to the Webex Teams APIs. This base method: * Expands the API endpoint URL to an absolute URL * Makes the actual HTTP request to the API endpoint * Provides support for Webex Teams rate-limiting * Inspects response codes and raises exceptions as appropriate Args: method(basestring): The request-method type ('GET', 'POST', etc.). url(basestring): The URL of the API endpoint to be called. erc(int): The expected response code that should be returned by the Webex Teams API endpoint to indicate success. **kwargs: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ # Ensure the url is an absolute URL abs_url = self.abs_url(url) # Update request kwargs with session defaults kwargs.setdefault('timeout', self.single_request_timeout) while True: # Make the HTTP request to the API endpoint response = self._req_session.request(method, abs_url, **kwargs) try: # Check the response code for error conditions check_response_code(response, erc) except RateLimitError as e: # Catch rate-limit errors # Wait and retry if automatic rate-limit handling is enabled if self.wait_on_rate_limit: warnings.warn(RateLimitWarning(response)) time.sleep(e.retry_after) continue else: # Re-raise the RateLimitError raise else: return response
python
{ "resource": "" }
q271401
RestSession.get
test
def get(self, url, params=None, **kwargs): """Sends a GET request. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) check_type(params, dict) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET']) response = self.request('GET', url, erc, params=params, **kwargs) return extract_and_parse_json(response)
python
{ "resource": "" }
q271402
RestSession.get_pages
test
def get_pages(self, url, params=None, **kwargs): """Return a generator that GETs and yields pages of data. Provides native support for RFC5988 Web Linking. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) check_type(params, dict) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET']) # First request response = self.request('GET', url, erc, params=params, **kwargs) while True: yield extract_and_parse_json(response) if response.links.get('next'): next_url = response.links.get('next').get('url') # Patch for Webex Teams 'max=null' in next URL bug. # Testing shows that patch is no longer needed; raising a # warnning if it is still taking effect; # considering for future removal next_url = _fix_next_url(next_url) # Subsequent requests response = self.request('GET', next_url, erc, **kwargs) else: break
python
{ "resource": "" }
q271403
RestSession.get_items
test
def get_items(self, url, params=None, **kwargs): """Return a generator that GETs and yields individual JSON `items`. Yields individual `items` from Webex Teams's top-level {'items': [...]} JSON objects. Provides native support for RFC5988 Web Linking. The generator will request additional pages as needed until all items have been returned. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. MalformedResponse: If the returned response does not contain a top-level dictionary with an 'items' key. """ # Get generator for pages of JSON data pages = self.get_pages(url, params=params, **kwargs) for json_page in pages: assert isinstance(json_page, dict) items = json_page.get('items') if items is None: error_message = "'items' key not found in JSON data: " \ "{!r}".format(json_page) raise MalformedResponse(error_message) else: for item in items: yield item
python
{ "resource": "" }
q271404
RestSession.put
test
def put(self, url, json=None, data=None, **kwargs): """Sends a PUT request. Args: url(basestring): The URL of the API endpoint. json: Data to be sent in JSON format in tbe body of the request. data: Data to be sent in the body of the request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['PUT']) response = self.request('PUT', url, erc, json=json, data=data, **kwargs) return extract_and_parse_json(response)
python
{ "resource": "" }
q271405
RestSession.delete
test
def delete(self, url, **kwargs): """Sends a DELETE request. Args: url(basestring): The URL of the API endpoint. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['DELETE']) self.request('DELETE', url, erc, **kwargs)
python
{ "resource": "" }
q271406
GuestIssuerAPI.create
test
def create(self, subject, displayName, issuerToken, expiration, secret): """Create a new guest issuer using the provided issuer token. This function returns a guest issuer with an api access token. Args: subject(basestring): Unique and public identifier displayName(basestring): Display Name of the guest user issuerToken(basestring): Issuer token from developer hub expiration(basestring): Expiration time as a unix timestamp secret(basestring): The secret used to sign your guest issuers Returns: GuestIssuerToken: A Guest Issuer with a valid access token. Raises: TypeError: If the parameter types are incorrect ApiError: If the webex teams cloud returns an error. """ check_type(subject, basestring) check_type(displayName, basestring) check_type(issuerToken, basestring) check_type(expiration, basestring) check_type(secret, basestring) payload = { "sub": subject, "name": displayName, "iss": issuerToken, "exp": expiration } key = base64.b64decode(secret) jwt_token = jwt.encode(payload, key, algorithm='HS256') url = self._session.base_url + API_ENDPOINT + "/" + "login" headers = { 'Authorization': "Bearer " + jwt_token.decode('utf-8') } response = requests.post(url, headers=headers) check_response_code(response, EXPECTED_RESPONSE_CODE['GET']) return self._object_factory(OBJECT_TYPE, response.json())
python
{ "resource": "" }
q271407
MessagesAPI.list
test
def list(self, roomId, mentionedPeople=None, before=None, beforeMessage=None, max=None, **request_parameters): """Lists messages in a room. Each message will include content attachments if present. The list API sorts the messages in descending order by creation date. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all messages returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): List messages for a room, by ID. mentionedPeople(basestring): List messages where the caller is mentioned by specifying "me" or the caller `personId`. before(basestring): List messages sent before a date and time, in ISO8601 format. beforeMessage(basestring): List messages sent before a message, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the messages returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) check_type(mentionedPeople, basestring) check_type(before, basestring) check_type(beforeMessage, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, roomId=roomId, mentionedPeople=mentionedPeople, before=before, beforeMessage=beforeMessage, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield message objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
python
{ "resource": "" }
q271408
MessagesAPI.create
test
def create(self, roomId=None, toPersonId=None, toPersonEmail=None, text=None, markdown=None, files=None, **request_parameters): """Post a message, and optionally a attachment, to a room. The files parameter is a list, which accepts multiple values to allow for future expansion, but currently only one file may be included with the message. Args: roomId(basestring): The room ID. toPersonId(basestring): The ID of the recipient when sending a private 1:1 message. toPersonEmail(basestring): The email address of the recipient when sending a private 1:1 message. text(basestring): The message, in plain text. If `markdown` is specified this parameter may be optionally used to provide alternate text for UI clients that do not support rich text. markdown(basestring): The message, in markdown format. files(`list`): A list of public URL(s) or local path(s) to files to be posted into the room. Only one file is allowed per message. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Message: A Message object with the details of the created message. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. ValueError: If the files parameter is a list of length > 1, or if the string in the list (the only element in the list) does not contain a valid URL or path to a local file. """ check_type(roomId, basestring) check_type(toPersonId, basestring) check_type(toPersonEmail, basestring) check_type(text, basestring) check_type(markdown, basestring) check_type(files, list) if files: if len(files) != 1: raise ValueError("The length of the `files` list is greater " "than one (1). The files parameter is a " "list, which accepts multiple values to " "allow for future expansion, but currently " "only one file may be included with the " "message.") check_type(files[0], basestring) post_data = dict_from_items_with_values( request_parameters, roomId=roomId, toPersonId=toPersonId, toPersonEmail=toPersonEmail, text=text, markdown=markdown, files=files, ) # API request if not files or is_web_url(files[0]): # Standard JSON post json_data = self._session.post(API_ENDPOINT, json=post_data) elif is_local_file(files[0]): # Multipart MIME post try: post_data['files'] = open_local_file(files[0]) multipart_data = MultipartEncoder(post_data) headers = {'Content-type': multipart_data.content_type} json_data = self._session.post(API_ENDPOINT, headers=headers, data=multipart_data) finally: post_data['files'].file_object.close() else: raise ValueError("The `files` parameter does not contain a vaild " "URL or path to a local file.") # Return a message object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271409
MessagesAPI.delete
test
def delete(self, messageId): """Delete a message. Args: messageId(basestring): The ID of the message to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(messageId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + messageId)
python
{ "resource": "" }
q271410
PeopleAPI.create
test
def create(self, emails, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Create a new user account for a given organization Only an admin can create a new user account. Args: emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the details of the created person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(emails, list, may_be_none=False) check_type(displayName, basestring) check_type(firstName, basestring) check_type(lastName, basestring) check_type(avatar, basestring) check_type(orgId, basestring) check_type(roles, list) check_type(licenses, list) post_data = dict_from_items_with_values( request_parameters, emails=emails, displayName=displayName, firstName=firstName, lastName=lastName, avatar=avatar, orgId=orgId, roles=roles, licenses=licenses, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a person object created from the returned JSON object return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271411
PeopleAPI.get
test
def get(self, personId): """Get a person's details, by ID. Args: personId(basestring): The ID of the person to be retrieved. Returns: Person: A Person object with the details of the requested person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(personId, basestring, may_be_none=False) # API request json_data = self._session.get(API_ENDPOINT + '/' + personId) # Return a person object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271412
PeopleAPI.update
test
def update(self, personId, emails=None, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Update details for a person, by ID. Only an admin can update a person's details. Email addresses for a person cannot be changed via the Webex Teams API. Include all details for the person. This action expects all user details to be present in the request. A common approach is to first GET the person's details, make changes, then PUT both the changed and unchanged values. Args: personId(basestring): The person ID. emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the updated details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(emails, list) check_type(displayName, basestring) check_type(firstName, basestring) check_type(lastName, basestring) check_type(avatar, basestring) check_type(orgId, basestring) check_type(roles, list) check_type(licenses, list) put_data = dict_from_items_with_values( request_parameters, emails=emails, displayName=displayName, firstName=firstName, lastName=lastName, avatar=avatar, orgId=orgId, roles=roles, licenses=licenses, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + personId, json=put_data) # Return a person object created from the returned JSON object return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271413
PeopleAPI.delete
test
def delete(self, personId): """Remove a person from the system. Only an admin can remove a person. Args: personId(basestring): The ID of the person to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(personId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + personId)
python
{ "resource": "" }
q271414
PeopleAPI.me
test
def me(self): """Get the details of the person accessing the API. Raises: ApiError: If the Webex Teams cloud returns an error. """ # API request json_data = self._session.get(API_ENDPOINT + '/me') # Return a person object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271415
RolesAPI.list
test
def list(self, **request_parameters): """List all roles. Args: **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the roles returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ # API request - get items items = self._session.get_items( API_ENDPOINT, params=request_parameters ) # Yield role objects created from the returned JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
python
{ "resource": "" }
q271416
TeamsAPI.list
test
def list(self, max=None, **request_parameters): """List teams to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all teams returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the teams returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(max, int) params = dict_from_items_with_values( request_parameters, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield team objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
python
{ "resource": "" }
q271417
TeamsAPI.create
test
def create(self, name, **request_parameters): """Create a team. The authenticated user is automatically added as a member of the team. Args: name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the details of the created team. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(name, basestring, may_be_none=False) post_data = dict_from_items_with_values( request_parameters, name=name, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a team object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271418
TeamsAPI.update
test
def update(self, teamId, name=None, **request_parameters): """Update details for a team, by ID. Args: teamId(basestring): The team ID. name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the updated Webex Teams team details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(name, basestring) put_data = dict_from_items_with_values( request_parameters, name=name, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + teamId, json=put_data) # Return a team object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271419
TeamsAPI.delete
test
def delete(self, teamId): """Delete a team. Args: teamId(basestring): The ID of the team to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + teamId)
python
{ "resource": "" }
q271420
EventsAPI.list
test
def list(self, resource=None, type=None, actorId=None, _from=None, to=None, max=None, **request_parameters): """List events. List events in your organization. Several query parameters are available to filter the response. Note: `from` is a keyword in Python and may not be used as a variable name, so we had to use `_from` instead. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all events returned by the query. The generator will automatically request additional 'pages' of responses from Wevex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: resource(basestring): Limit results to a specific resource type. Possible values: "messages", "memberships". type(basestring): Limit results to a specific event type. Possible values: "created", "updated", "deleted". actorId(basestring): Limit results to events performed by this person, by ID. _from(basestring): Limit results to events which occurred after a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). to(basestring): Limit results to events which occurred before a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the events returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(resource, basestring) check_type(type, basestring) check_type(actorId, basestring) check_type(_from, basestring) check_type(to, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, resource=resource, type=type, actorId=actorId, _from=_from, to=to, max=max, ) if _from: params["from"] = params.pop("_from") # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield event objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
python
{ "resource": "" }
q271421
ImmutableData._serialize
test
def _serialize(cls, data): """Serialize data to an frozen tuple.""" if hasattr(data, "__hash__") and callable(data.__hash__): # If the data is already hashable (should be immutable) return it return data elif isinstance(data, list): # Freeze the elements of the list and return as a tuple return tuple((cls._serialize(item) for item in data)) elif isinstance(data, dict): # Freeze the elements of the dictionary, sort them, and return # them as a list of tuples key_value_tuples = [ (key, cls._serialize(value)) for key, value in data.items() ] key_value_tuples.sort() return tuple(key_value_tuples) else: raise TypeError( "Unable to freeze {} data type.".format(type(data)) )
python
{ "resource": "" }
q271422
AccessTokensAPI.get
test
def get(self, client_id, client_secret, code, redirect_uri): """Exchange an Authorization Code for an Access Token. Exchange an Authorization Code for an Access Token that can be used to invoke the APIs. Args: client_id(basestring): Provided when you created your integration. client_secret(basestring): Provided when you created your integration. code(basestring): The Authorization Code provided by the user OAuth process. redirect_uri(basestring): The redirect URI used in the user OAuth process. Returns: AccessToken: An AccessToken object with the access token provided by the Webex Teams cloud. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(client_id, basestring, may_be_none=False) check_type(client_secret, basestring, may_be_none=False) check_type(code, basestring, may_be_none=False) check_type(redirect_uri, basestring, may_be_none=False) post_data = dict_from_items_with_values( grant_type="authorization_code", client_id=client_id, client_secret=client_secret, code=code, redirect_uri=redirect_uri, ) # API request response = requests.post(self._endpoint_url, data=post_data, **self._request_kwargs) check_response_code(response, EXPECTED_RESPONSE_CODE['POST']) json_data = extract_and_parse_json(response) # Return a access_token object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
python
{ "resource": "" }
q271423
PersonBasicPropertiesMixin.lastActivity
test
def lastActivity(self): """The date and time of the person's last activity.""" last_activity = self._json_data.get('lastActivity') if last_activity: return WebexTeamsDateTime.strptime(last_activity) else: return None
python
{ "resource": "" }
q271424
post_events_service
test
def post_events_service(request): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json log.info("\n") log.info("WEBHOOK POST RECEIVED:") log.info(json_data) log.info("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) log.info("NEW MESSAGE IN ROOM '{}'".format(room.title)) log.info("FROM '{}'".format(person.displayName)) log.info("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return {'Message': 'OK'} else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: log.info("FOUND '/CAT'") # Get a cat fact catfact = get_catfact() log.info("SENDING CAT FACT'{}'".format(catfact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=catfact) return {'Message': 'OK'}
python
{ "resource": "" }
q271425
get_ngrok_public_url
test
def get_ngrok_public_url(): """Get the ngrok public HTTP URL from the local client API.""" try: response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels", headers={'content-type': 'application/json'}) response.raise_for_status() except requests.exceptions.RequestException: print("Could not connect to the ngrok client API; " "assuming not running.") return None else: for tunnel in response.json()["tunnels"]: if tunnel.get("public_url", "").startswith("http://"): print("Found ngrok public HTTP URL:", tunnel["public_url"]) return tunnel["public_url"]
python
{ "resource": "" }
q271426
delete_webhooks_with_name
test
def delete_webhooks_with_name(api, name): """Find a webhook by name.""" for webhook in api.webhooks.list(): if webhook.name == name: print("Deleting Webhook:", webhook.name, webhook.targetUrl) api.webhooks.delete(webhook.id)
python
{ "resource": "" }
q271427
create_ngrok_webhook
test
def create_ngrok_webhook(api, ngrok_public_url): """Create a Webex Teams webhook pointing to the public ngrok URL.""" print("Creating Webhook...") webhook = api.webhooks.create( name=WEBHOOK_NAME, targetUrl=urljoin(ngrok_public_url, WEBHOOK_URL_SUFFIX), resource=WEBHOOK_RESOURCE, event=WEBHOOK_EVENT, ) print(webhook) print("Webhook successfully created.") return webhook
python
{ "resource": "" }
q271428
main
test
def main(): """Delete previous webhooks. If local ngrok tunnel, create a webhook.""" api = WebexTeamsAPI() delete_webhooks_with_name(api, name=WEBHOOK_NAME) public_url = get_ngrok_public_url() if public_url is not None: create_ngrok_webhook(api, public_url)
python
{ "resource": "" }
q271429
console
test
def console(): """Output DSMR data to console.""" parser = argparse.ArgumentParser(description=console.__doc__) parser.add_argument('--device', default='/dev/ttyUSB0', help='port to read DSMR data from') parser.add_argument('--host', default=None, help='alternatively connect using TCP host.') parser.add_argument('--port', default=None, help='TCP port to use for connection') parser.add_argument('--version', default='2.2', choices=['2.2', '4'], help='DSMR version (2.2, 4)') parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.ERROR logging.basicConfig(level=level) loop = asyncio.get_event_loop() def print_callback(telegram): """Callback that prints telegram values.""" for obiref, obj in telegram.items(): if obj: print(obj.value, obj.unit) print() # create tcp or serial connection depending on args if args.host and args.port: create_connection = partial(create_tcp_dsmr_reader, args.host, args.port, args.version, print_callback, loop=loop) else: create_connection = partial(create_dsmr_reader, args.device, args.version, print_callback, loop=loop) try: # connect and keep connected until interrupted by ctrl-c while True: # create serial or tcp connection conn = create_connection() transport, protocol = loop.run_until_complete(conn) # wait until connection it closed loop.run_until_complete(protocol.wait_closed()) # wait 5 seconds before attempting reconnect loop.run_until_complete(asyncio.sleep(5)) except KeyboardInterrupt: # cleanup connection after user initiated shutdown transport.close() loop.run_until_complete(asyncio.sleep(0)) finally: loop.close()
python
{ "resource": "" }
q271430
SerialReader.read
test
def read(self): """ Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's :rtype: generator """ with serial.Serial(**self.serial_settings) as serial_handle: while True: data = serial_handle.readline() self.telegram_buffer.append(data.decode('ascii')) for telegram in self.telegram_buffer.get_all(): try: yield self.telegram_parser.parse(telegram) except InvalidChecksumError as e: logger.warning(str(e)) except ParseError as e: logger.error('Failed to parse telegram: %s', e)
python
{ "resource": "" }
q271431
AsyncSerialReader.read
test
def read(self, queue): """ Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's. Instead of being a generator, values are pushed to provided queue for asynchronous processing. :rtype: None """ # create Serial StreamReader conn = serial_asyncio.open_serial_connection(**self.serial_settings) reader, _ = yield from conn while True: # Read line if available or give control back to loop until new # data has arrived. data = yield from reader.readline() self.telegram_buffer.append(data.decode('ascii')) for telegram in self.telegram_buffer.get_all(): try: # Push new parsed telegram onto queue. queue.put_nowait( self.telegram_parser.parse(telegram) ) except ParseError as e: logger.warning('Failed to parse telegram: %s', e)
python
{ "resource": "" }
q271432
create_dsmr_protocol
test
def create_dsmr_protocol(dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol.""" if dsmr_version == '2.2': specification = telegram_specifications.V2_2 serial_settings = SERIAL_SETTINGS_V2_2 elif dsmr_version == '4': specification = telegram_specifications.V4 serial_settings = SERIAL_SETTINGS_V4 elif dsmr_version == '5': specification = telegram_specifications.V5 serial_settings = SERIAL_SETTINGS_V5 else: raise NotImplementedError("No telegram parser found for version: %s", dsmr_version) protocol = partial(DSMRProtocol, loop, TelegramParser(specification), telegram_callback=telegram_callback) return protocol, serial_settings
python
{ "resource": "" }
q271433
create_dsmr_reader
test
def create_dsmr_reader(port, dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol coroutine using serial port.""" protocol, serial_settings = create_dsmr_protocol( dsmr_version, telegram_callback, loop=None) serial_settings['url'] = port conn = create_serial_connection(loop, protocol, **serial_settings) return conn
python
{ "resource": "" }
q271434
create_tcp_dsmr_reader
test
def create_tcp_dsmr_reader(host, port, dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol coroutine using TCP connection.""" protocol, _ = create_dsmr_protocol( dsmr_version, telegram_callback, loop=None) conn = loop.create_connection(protocol, host, port) return conn
python
{ "resource": "" }
q271435
DSMRProtocol.data_received
test
def data_received(self, data): """Add incoming data to buffer.""" data = data.decode('ascii') self.log.debug('received data: %s', data) self.telegram_buffer.append(data) for telegram in self.telegram_buffer.get_all(): self.handle_telegram(telegram)
python
{ "resource": "" }
q271436
DSMRProtocol.connection_lost
test
def connection_lost(self, exc): """Stop when connection is lost.""" if exc: self.log.exception('disconnected due to exception') else: self.log.info('disconnected because of close/abort.') self._closed.set()
python
{ "resource": "" }
q271437
DSMRProtocol.handle_telegram
test
def handle_telegram(self, telegram): """Send off parsed telegram to handling callback.""" self.log.debug('got telegram: %s', telegram) try: parsed_telegram = self.telegram_parser.parse(telegram) except InvalidChecksumError as e: self.log.warning(str(e)) except ParseError: self.log.exception("failed to parse telegram") else: self.telegram_callback(parsed_telegram)
python
{ "resource": "" }
q271438
TelegramParser.parse
test
def parse(self, telegram_data): """ Parse telegram from string to dict. The telegram str type makes python 2.x integration easier. :param str telegram_data: full telegram from start ('/') to checksum ('!ABCD') including line endings in between the telegram's lines :rtype: dict :returns: Shortened example: { .. r'\d-\d:96\.1\.1.+?\r\n': <CosemObject>, # EQUIPMENT_IDENTIFIER r'\d-\d:1\.8\.1.+?\r\n': <CosemObject>, # ELECTRICITY_USED_TARIFF_1 r'\d-\d:24\.3\.0.+?\r\n.+?\r\n': <MBusObject>, # GAS_METER_READING .. } :raises ParseError: :raises InvalidChecksumError: """ if self.apply_checksum_validation \ and self.telegram_specification['checksum_support']: self.validate_checksum(telegram_data) telegram = {} for signature, parser in self.telegram_specification['objects'].items(): match = re.search(signature, telegram_data, re.DOTALL) # Some signatures are optional and may not be present, # so only parse lines that match if match: telegram[signature] = parser.parse(match.group(0)) return telegram
python
{ "resource": "" }
q271439
get_version
test
def get_version(file, name='__version__'): """Get the version of the package from the given file by executing it and extracting the given `name`. """ path = os.path.realpath(file) version_ns = {} with io.open(path, encoding="utf8") as f: exec(f.read(), {}, version_ns) return version_ns[name]
python
{ "resource": "" }
q271440
ensure_python
test
def ensure_python(specs): """Given a list of range specifiers for python, ensure compatibility. """ if not isinstance(specs, (list, tuple)): specs = [specs] v = sys.version_info part = '%s.%s' % (v.major, v.minor) for spec in specs: if part == spec: return try: if eval(part + spec): return except SyntaxError: pass raise ValueError('Python version %s unsupported' % part)
python
{ "resource": "" }
q271441
find_packages
test
def find_packages(top=HERE): """ Find all of the packages. """ packages = [] for d, dirs, _ in os.walk(top, followlinks=True): if os.path.exists(pjoin(d, '__init__.py')): packages.append(os.path.relpath(d, top).replace(os.path.sep, '.')) elif d != top: # Do not look for packages in subfolders if current is not a package dirs[:] = [] return packages
python
{ "resource": "" }
q271442
create_cmdclass
test
def create_cmdclass(prerelease_cmd=None, package_data_spec=None, data_files_spec=None): """Create a command class with the given optional prerelease class. Parameters ---------- prerelease_cmd: (name, Command) tuple, optional The command to run before releasing. package_data_spec: dict, optional A dictionary whose keys are the dotted package names and whose values are a list of glob patterns. data_files_spec: list, optional A list of (path, dname, pattern) tuples where the path is the `data_files` install path, dname is the source directory, and the pattern is a glob pattern. Notes ----- We use specs so that we can find the files *after* the build command has run. The package data glob patterns should be relative paths from the package folder containing the __init__.py file, which is given as the package name. e.g. `dict(foo=['./bar/*', './baz/**'])` The data files directories should be absolute paths or relative paths from the root directory of the repository. Data files are specified differently from `package_data` because we need a separate path entry for each nested folder in `data_files`, and this makes it easier to parse. e.g. `('share/foo/bar', 'pkgname/bizz, '*')` """ wrapped = [prerelease_cmd] if prerelease_cmd else [] if package_data_spec or data_files_spec: wrapped.append('handle_files') wrapper = functools.partial(_wrap_command, wrapped) handle_files = _get_file_handler(package_data_spec, data_files_spec) if 'bdist_egg' in sys.argv: egg = wrapper(bdist_egg, strict=True) else: egg = bdist_egg_disabled cmdclass = dict( build_py=wrapper(build_py, strict=is_repo), bdist_egg=egg, sdist=wrapper(sdist, strict=True), handle_files=handle_files, ) if bdist_wheel: cmdclass['bdist_wheel'] = wrapper(bdist_wheel, strict=True) cmdclass['develop'] = wrapper(develop, strict=True) return cmdclass
python
{ "resource": "" }
q271443
command_for_func
test
def command_for_func(func): """Create a command that calls the given function.""" class FuncCommand(BaseCommand): def run(self): func() update_package_data(self.distribution) return FuncCommand
python
{ "resource": "" }
q271444
run
test
def run(cmd, **kwargs): """Echo a command before running it. Defaults to repo as cwd""" log.info('> ' + list2cmdline(cmd)) kwargs.setdefault('cwd', HERE) kwargs.setdefault('shell', os.name == 'nt') if not isinstance(cmd, (list, tuple)) and os.name != 'nt': cmd = shlex.split(cmd) cmd[0] = which(cmd[0]) return subprocess.check_call(cmd, **kwargs)
python
{ "resource": "" }
q271445
ensure_targets
test
def ensure_targets(targets): """Return a Command that checks that certain files exist. Raises a ValueError if any of the files are missing. Note: The check is skipped if the `--skip-npm` flag is used. """ class TargetsCheck(BaseCommand): def run(self): if skip_npm: log.info('Skipping target checks') return missing = [t for t in targets if not os.path.exists(t)] if missing: raise ValueError(('missing files: %s' % missing)) return TargetsCheck
python
{ "resource": "" }
q271446
_wrap_command
test
def _wrap_command(cmds, cls, strict=True): """Wrap a setup command Parameters ---------- cmds: list(str) The names of the other commands to run prior to the command. strict: boolean, optional Whether to raise errors when a pre-command fails. """ class WrappedCommand(cls): def run(self): if not getattr(self, 'uninstall', None): try: [self.run_command(cmd) for cmd in cmds] except Exception: if strict: raise else: pass # update package data update_package_data(self.distribution) result = cls.run(self) return result return WrappedCommand
python
{ "resource": "" }
q271447
_get_file_handler
test
def _get_file_handler(package_data_spec, data_files_spec): """Get a package_data and data_files handler command. """ class FileHandler(BaseCommand): def run(self): package_data = self.distribution.package_data package_spec = package_data_spec or dict() for (key, patterns) in package_spec.items(): package_data[key] = _get_package_data(key, patterns) self.distribution.data_files = _get_data_files( data_files_spec, self.distribution.data_files ) return FileHandler
python
{ "resource": "" }
q271448
_get_data_files
test
def _get_data_files(data_specs, existing): """Expand data file specs into valid data files metadata. Parameters ---------- data_specs: list of tuples See [createcmdclass] for description. existing: list of tuples The existing distribution data_files metadata. Returns ------- A valid list of data_files items. """ # Extract the existing data files into a staging object. file_data = defaultdict(list) for (path, files) in existing or []: file_data[path] = files # Extract the files and assign them to the proper data # files path. for (path, dname, pattern) in data_specs or []: dname = dname.replace(os.sep, '/') offset = len(dname) + 1 files = _get_files(pjoin(dname, pattern)) for fname in files: # Normalize the path. root = os.path.dirname(fname) full_path = '/'.join([path, root[offset:]]) if full_path.endswith('/'): full_path = full_path[:-1] file_data[full_path].append(fname) # Construct the data files spec. data_files = [] for (path, files) in file_data.items(): data_files.append((path, files)) return data_files
python
{ "resource": "" }
q271449
_get_package_data
test
def _get_package_data(root, file_patterns=None): """Expand file patterns to a list of `package_data` paths. Parameters ----------- root: str The relative path to the package root from `HERE`. file_patterns: list or str, optional A list of glob patterns for the data file locations. The globs can be recursive if they include a `**`. They should be relative paths from the root or absolute paths. If not given, all files will be used. Note: Files in `node_modules` are ignored. """ if file_patterns is None: file_patterns = ['*'] return _get_files(file_patterns, pjoin(HERE, root))
python
{ "resource": "" }
q271450
_compile_pattern
test
def _compile_pattern(pat, ignore_case=True): """Translate and compile a glob pattern to a regular expression matcher.""" if isinstance(pat, bytes): pat_str = pat.decode('ISO-8859-1') res_str = _translate_glob(pat_str) res = res_str.encode('ISO-8859-1') else: res = _translate_glob(pat) flags = re.IGNORECASE if ignore_case else 0 return re.compile(res, flags=flags).match
python
{ "resource": "" }
q271451
_iexplode_path
test
def _iexplode_path(path): """Iterate over all the parts of a path. Splits path recursively with os.path.split(). """ (head, tail) = os.path.split(path) if not head or (not tail and head == path): if head: yield head if tail or not head: yield tail return for p in _iexplode_path(head): yield p yield tail
python
{ "resource": "" }
q271452
_translate_glob
test
def _translate_glob(pat): """Translate a glob PATTERN to a regular expression.""" translated_parts = [] for part in _iexplode_path(pat): translated_parts.append(_translate_glob_part(part)) os_sep_class = '[%s]' % re.escape(SEPARATORS) res = _join_translated(translated_parts, os_sep_class) return '{res}\\Z(?ms)'.format(res=res)
python
{ "resource": "" }
q271453
_join_translated
test
def _join_translated(translated_parts, os_sep_class): """Join translated glob pattern parts. This is different from a simple join, as care need to be taken to allow ** to match ZERO or more directories. """ res = '' for part in translated_parts[:-1]: if part == '.*': # drop separator, since it is optional # (** matches ZERO or more dirs) res += part else: res += part + os_sep_class if translated_parts[-1] == '.*': # Final part is ** res += '.+' # Follow stdlib/git convention of matching all sub files/directories: res += '({os_sep_class}?.*)?'.format(os_sep_class=os_sep_class) else: res += translated_parts[-1] return res
python
{ "resource": "" }
q271454
_translate_glob_part
test
def _translate_glob_part(pat): """Translate a glob PATTERN PART to a regular expression.""" # Code modified from Python 3 standard lib fnmatch: if pat == '**': return '.*' i, n = 0, len(pat) res = [] while i < n: c = pat[i] i = i + 1 if c == '*': # Match anything but path separators: res.append('[^%s]*' % SEPARATORS) elif c == '?': res.append('[^%s]?' % SEPARATORS) elif c == '[': j = i if j < n and pat[j] == '!': j = j + 1 if j < n and pat[j] == ']': j = j + 1 while j < n and pat[j] != ']': j = j + 1 if j >= n: res.append('\\[') else: stuff = pat[i:j].replace('\\', '\\\\') i = j + 1 if stuff[0] == '!': stuff = '^' + stuff[1:] elif stuff[0] == '^': stuff = '\\' + stuff res.append('[%s]' % stuff) else: res.append(re.escape(c)) return ''.join(res)
python
{ "resource": "" }
q271455
PostgresDbWriter.truncate
test
def truncate(self, table): """Send DDL to truncate the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ truncate_sql, serial_key_sql = super(PostgresDbWriter, self).truncate(table) self.execute(truncate_sql) if serial_key_sql: self.execute(serial_key_sql)
python
{ "resource": "" }
q271456
PostgresDbWriter.write_table
test
def write_table(self, table): """Send DDL to create the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ table_sql, serial_key_sql = super(PostgresDbWriter, self).write_table(table) for sql in serial_key_sql + table_sql: self.execute(sql)
python
{ "resource": "" }
q271457
PostgresDbWriter.write_indexes
test
def write_indexes(self, table): """Send DDL to create the specified `table` indexes :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ index_sql = super(PostgresDbWriter, self).write_indexes(table) for sql in index_sql: self.execute(sql)
python
{ "resource": "" }
q271458
PostgresDbWriter.write_triggers
test
def write_triggers(self, table): """Send DDL to create the specified `table` triggers :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ index_sql = super(PostgresDbWriter, self).write_triggers(table) for sql in index_sql: self.execute(sql)
python
{ "resource": "" }
q271459
PostgresDbWriter.write_constraints
test
def write_constraints(self, table): """Send DDL to create the specified `table` constraints :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ constraint_sql = super(PostgresDbWriter, self).write_constraints(table) for sql in constraint_sql: self.execute(sql)
python
{ "resource": "" }
q271460
PostgresDbWriter.write_contents
test
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader` object that allows reading from the data source. Returns None """ f = self.FileObjFaker(table, reader.read(table), self.process_row, self.verbose) self.copy_from(f, '"%s"' % table.name, ['"%s"' % c['name'] for c in table.columns])
python
{ "resource": "" }
q271461
PostgresWriter.process_row
test
def process_row(self, table, row): """Examines row data from MySQL and alters the values when necessary to be compatible with sending to PostgreSQL via the copy command """ for index, column in enumerate(table.columns): hash_key = hash(frozenset(column.items())) column_type = self.column_types[hash_key] if hash_key in self.column_types else self.column_type(column) if row[index] == None and ('timestamp' not in column_type or not column['default']): row[index] = '\N' elif row[index] == None and column['default']: if self.tz: row[index] = '1970-01-01T00:00:00.000000' + self.tz_offset else: row[index] = '1970-01-01 00:00:00' elif 'bit' in column_type: row[index] = bin(ord(row[index]))[2:] elif isinstance(row[index], (str, unicode, basestring)): if column_type == 'bytea': row[index] = Binary(row[index]).getquoted()[1:-8] if row[index] else row[index] elif 'text[' in column_type: row[index] = '{%s}' % ','.join('"%s"' % v.replace('"', r'\"') for v in row[index].split(',')) else: row[index] = row[index].replace('\\', r'\\').replace('\n', r'\n').replace( '\t', r'\t').replace('\r', r'\r').replace('\0', '') elif column_type == 'boolean': # We got here because you used a tinyint(1), if you didn't want a bool, don't use that type row[index] = 't' if row[index] not in (None, 0) else 'f' if row[index] == 0 else row[index] elif isinstance(row[index], (date, datetime)): if isinstance(row[index], datetime) and self.tz: try: if row[index].tzinfo: row[index] = row[index].astimezone(self.tz).isoformat() else: row[index] = datetime(*row[index].timetuple()[:6], tzinfo=self.tz).isoformat() except Exception as e: print e.message else: row[index] = row[index].isoformat() elif isinstance(row[index], timedelta): row[index] = datetime.utcfromtimestamp(_get_total_seconds(row[index])).time().isoformat() else: row[index] = AsIs(row[index]).getquoted()
python
{ "resource": "" }
q271462
PostgresFileWriter.write_indexes
test
def write_indexes(self, table): """Write DDL of `table` indexes to the output file :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ self.f.write('\n'.join(super(PostgresFileWriter, self).write_indexes(table)))
python
{ "resource": "" }
q271463
PostgresFileWriter.write_constraints
test
def write_constraints(self, table): """Write DDL of `table` constraints to the output file :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ self.f.write('\n'.join(super(PostgresFileWriter, self).write_constraints(table)))
python
{ "resource": "" }
q271464
PostgresFileWriter.write_triggers
test
def write_triggers(self, table): """Write TRIGGERs existing on `table` to the output file :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ self.f.write('\n'.join(super(PostgresFileWriter, self).write_triggers(table)))
python
{ "resource": "" }
q271465
SQLStepQueue.qsize
test
def qsize(self, extra_predicate=None): """ Return an approximate number of queued tasks in the queue. """ count = self._query_queued('COUNT(*) AS count', extra_predicate=extra_predicate) return count[0].count
python
{ "resource": "" }
q271466
SQLStepQueue.enqueue
test
def enqueue(self, data): """ Enqueue task with specified data. """ jsonified_data = json.dumps(data) with self._db_conn() as conn: return conn.execute( 'INSERT INTO %s (created, data) VALUES (%%(created)s, %%(data)s)' % self.table_name, created=datetime.utcnow(), data=jsonified_data )
python
{ "resource": "" }
q271467
SQLStepQueue.start
test
def start(self, block=False, timeout=None, retry_interval=0.5, extra_predicate=None): """ Retrieve a task handler from the queue. If block is True, this function will block until it is able to retrieve a task. If block is True and timeout is a number it will block for at most <timeout> seconds. retry_interval is the maximum time in seconds between successive retries. extra_predicate If extra_predicate is defined, it should be a tuple of (raw_predicate, predicate_args) raw_predicate will be prefixed by AND, and inserted into the WHERE condition in the queries. predicate_args will be sql escaped and formatted into raw_predicate. """ start = time.time() while 1: task_handler = self._dequeue_task(extra_predicate) if task_handler is None and block: if timeout is not None and (time.time() - start) > timeout: break time.sleep(retry_interval * (random.random() + 0.1)) else: break return task_handler
python
{ "resource": "" }
q271468
SQLStepQueue._build_extra_predicate
test
def _build_extra_predicate(self, extra_predicate): """ This method is a good one to extend if you want to create a queue which always applies an extra predicate. """ if extra_predicate is None: return '' # if they don't have a supported format seq, wrap it for them if not isinstance(extra_predicate[1], (list, dict, tuple)): extra_predicate = [extra_predicate[0], (extra_predicate[1], )] extra_predicate = database.escape_query(*extra_predicate) return 'AND (' + extra_predicate + ')'
python
{ "resource": "" }
q271469
simplejson_datetime_serializer
test
def simplejson_datetime_serializer(obj): """ Designed to be passed as the default kwarg in simplejson.dumps. Serializes dates and datetimes to ISO strings. """ if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError('Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj)))
python
{ "resource": "" }
q271470
Connection.reconnect
test
def reconnect(self): """Closes the existing database connection and re-opens it.""" conn = _mysql.connect(**self._db_args) if conn is not None: self.close() self._db = conn
python
{ "resource": "" }
q271471
Connection.get
test
def get(self, query, *parameters, **kwparameters): """Returns the first row returned for the given query.""" rows = self._query(query, parameters, kwparameters) if not rows: return None elif not isinstance(rows, list): raise MySQLError("Query is not a select query") elif len(rows) > 1: raise MySQLError("Multiple rows returned for Database.get() query") else: return rows[0]
python
{ "resource": "" }
q271472
get_connection
test
def get_connection(db=DATABASE): """ Returns a new connection to the database. """ return database.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, database=db)
python
{ "resource": "" }
q271473
run_benchmark
test
def run_benchmark(): """ Run a set of InsertWorkers and record their performance. """ stopping = threading.Event() workers = [ InsertWorker(stopping) for _ in range(NUM_WORKERS) ] print('Launching %d workers' % NUM_WORKERS) [ worker.start() for worker in workers ] time.sleep(WORKLOAD_TIME) print('Stopping workload') stopping.set() [ worker.join() for worker in workers ] with get_connection() as conn: count = conn.get("SELECT COUNT(*) AS count FROM %s" % TABLE).count print("%d rows inserted using %d workers" % (count, NUM_WORKERS)) print("%.1f rows per second" % (count / float(WORKLOAD_TIME)))
python
{ "resource": "" }
q271474
RandomAggregatorPool._connect
test
def _connect(self): """ Returns an aggregator connection. """ with self._lock: if self._aggregator: try: return self._pool_connect(self._aggregator) except PoolConnectionException: self._aggregator = None if not len(self._aggregators): with self._pool_connect(self._primary_aggregator) as conn: self._update_aggregator_list(conn) conn.expire() random.shuffle(self._aggregators) last_exception = None for aggregator in self._aggregators: self.logger.debug('Attempting connection with %s:%s' % (aggregator[0], aggregator[1])) try: conn = self._pool_connect(aggregator) # connection successful! self._aggregator = aggregator return conn except PoolConnectionException as e: # connection error last_exception = e else: # bad news bears... try again later self._aggregator = None self._aggregators = [] raise last_exception
python
{ "resource": "" }
q271475
lookup_by_number
test
def lookup_by_number(errno): """ Used for development only """ for key, val in globals().items(): if errno == val: print(key)
python
{ "resource": "" }
q271476
ConnectionPool.size
test
def size(self): """ Returns the number of connections cached by the pool. """ return sum(q.qsize() for q in self._connections.values()) + len(self._fairies)
python
{ "resource": "" }
q271477
_PoolConnectionFairy.__potential_connection_failure
test
def __potential_connection_failure(self, e): """ OperationalError's are emitted by the _mysql library for almost every error code emitted by MySQL. Because of this we verify that the error is actually a connection error before terminating the connection and firing off a PoolConnectionException """ try: self._conn.query('SELECT 1') except (IOError, _mysql.OperationalError): # ok, it's actually an issue. self.__handle_connection_failure(e) else: # seems ok, probably programmer error raise _mysql.DatabaseError(*e.args)
python
{ "resource": "" }
q271478
simple_expression
test
def simple_expression(joiner=', ', **fields): """ Build a simple expression ready to be added onto another query. >>> simple_expression(joiner=' AND ', name='bob', role='admin') "`name`=%(_QB_name)s AND `name`=%(_QB_role)s", { '_QB_name': 'bob', '_QB_role': 'admin' } """ expression, params = [], {} for field_name, value in sorted(fields.items(), key=lambda kv: kv[0]): key = '_QB_%s' % field_name expression.append('`%s`=%%(%s)s' % (field_name, key)) params[key] = value return joiner.join(expression), params
python
{ "resource": "" }
q271479
update
test
def update(table_name, **fields): """ Build a update query. >>> update('foo_table', a=5, b=2) "UPDATE `foo_table` SET `a`=%(_QB_a)s, `b`=%(_QB_b)s", { '_QB_a': 5, '_QB_b': 2 } """ prefix = "UPDATE `%s` SET " % table_name sets, params = simple_expression(', ', **fields) return prefix + sets, params
python
{ "resource": "" }
q271480
SQLUtility.connect
test
def connect(self, host='127.0.0.1', port=3306, user='root', password='', database=None): """ Connect to the database specified """ if database is None: raise exceptions.RequiresDatabase() self._db_args = { 'host': host, 'port': port, 'user': user, 'password': password, 'database': database } with self._db_conn() as conn: conn.query('SELECT 1') return self
python
{ "resource": "" }
q271481
SQLUtility.setup
test
def setup(self): """ Initialize the required tables in the database """ with self._db_conn() as conn: for table_defn in self._tables.values(): conn.execute(table_defn) return self
python
{ "resource": "" }
q271482
SQLUtility.destroy
test
def destroy(self): """ Destroy the SQLStepQueue tables in the database """ with self._db_conn() as conn: for table_name in self._tables: conn.execute('DROP TABLE IF EXISTS %s' % table_name) return self
python
{ "resource": "" }
q271483
TaskHandler.start_step
test
def start_step(self, step_name): """ Start a step. """ if self.finished is not None: raise AlreadyFinished() step_data = self._get_step(step_name) if step_data is not None: if 'stop' in step_data: raise StepAlreadyFinished() else: raise StepAlreadyStarted() steps = copy.deepcopy(self.steps) steps.append({ "start": datetime.utcnow(), "name": step_name }) self._save(steps=steps)
python
{ "resource": "" }
q271484
TaskHandler.stop_step
test
def stop_step(self, step_name): """ Stop a step. """ if self.finished is not None: raise AlreadyFinished() steps = copy.deepcopy(self.steps) step_data = self._get_step(step_name, steps=steps) if step_data is None: raise StepNotStarted() elif 'stop' in step_data: raise StepAlreadyFinished() step_data['stop'] = datetime.utcnow() step_data['duration'] = util.timedelta_total_seconds(step_data['stop'] - step_data['start']) self._save(steps=steps)
python
{ "resource": "" }
q271485
TaskHandler._load_steps
test
def _load_steps(self, raw_steps): """ load steps -> basically load all the datetime isoformats into datetimes """ for step in raw_steps: if 'start' in step: step['start'] = parser.parse(step['start']) if 'stop' in step: step['stop'] = parser.parse(step['stop']) return raw_steps
python
{ "resource": "" }
q271486
WebSocketConnection.disconnect
test
def disconnect(self): """Disconnects from the websocket connection and joins the Thread. :return: """ self.log.debug("disconnect(): Disconnecting from API..") self.reconnect_required.clear() self.disconnect_called.set() if self.socket: self.socket.close() self.join(timeout=1)
python
{ "resource": "" }
q271487
WebSocketConnection.reconnect
test
def reconnect(self): """Issues a reconnection by setting the reconnect_required event. :return: """ # Reconnect attempt at self.reconnect_interval self.log.debug("reconnect(): Initialzion reconnect sequence..") self.connected.clear() self.reconnect_required.set() if self.socket: self.socket.close()
python
{ "resource": "" }
q271488
WebSocketConnection._connect
test
def _connect(self): """Creates a websocket connection. :return: """ self.log.debug("_connect(): Initializing Connection..") self.socket = websocket.WebSocketApp( self.url, on_open=self._on_open, on_message=self._on_message, on_error=self._on_error, on_close=self._on_close ) if 'ca_certs' not in self.sslopt.keys(): ssl_defaults = ssl.get_default_verify_paths() self.sslopt['ca_certs'] = ssl_defaults.cafile self.log.debug("_connect(): Starting Connection..") self.socket.run_forever(sslopt=self.sslopt, http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, http_proxy_auth=self.http_proxy_auth, http_no_proxy=self.http_no_proxy) # stop outstanding ping/pong timers self._stop_timers() while self.reconnect_required.is_set(): if not self.disconnect_called.is_set(): self.log.info("Attempting to connect again in %s seconds." % self.reconnect_interval) self.state = "unavailable" time.sleep(self.reconnect_interval) # We need to set this flag since closing the socket will # set it to False self.socket.keep_running = True self.socket.sock = None self.socket.run_forever(sslopt=self.sslopt, http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, http_proxy_auth=self.http_proxy_auth, http_no_proxy=self.http_no_proxy) else: break
python
{ "resource": "" }
q271489
WebSocketConnection._on_message
test
def _on_message(self, ws, message): """Handles and passes received data to the appropriate handlers. :return: """ self._stop_timers() raw, received_at = message, time.time() self.log.debug("_on_message(): Received new message %s at %s", raw, received_at) try: data = json.loads(raw) except json.JSONDecodeError: # Something wrong with this data, log and discard return # Handle data if isinstance(data, dict): # This is a system message self._system_handler(data, received_at) else: # This is a list of data if data[1] == 'hb': self._heartbeat_handler() else: self._data_handler(data, received_at) # We've received data, reset timers self._start_timers()
python
{ "resource": "" }
q271490
WebSocketConnection._stop_timers
test
def _stop_timers(self): """Stops ping, pong and connection timers. :return: """ if self.ping_timer: self.ping_timer.cancel() if self.connection_timer: self.connection_timer.cancel() if self.pong_timer: self.pong_timer.cancel() self.log.debug("_stop_timers(): Timers stopped.")
python
{ "resource": "" }
q271491
WebSocketConnection.send_ping
test
def send_ping(self): """Sends a ping message to the API and starts pong timers. :return: """ self.log.debug("send_ping(): Sending ping to API..") self.socket.send(json.dumps({'event': 'ping'})) self.pong_timer = Timer(self.pong_timeout, self._check_pong) self.pong_timer.start()
python
{ "resource": "" }
q271492
WebSocketConnection._check_pong
test
def _check_pong(self): """Checks if a Pong message was received. :return: """ self.pong_timer.cancel() if self.pong_received: self.log.debug("_check_pong(): Pong received in time.") self.pong_received = False else: # reconnect self.log.debug("_check_pong(): Pong not received in time." "Issuing reconnect..") self.reconnect()
python
{ "resource": "" }
q271493
WebSocketConnection.send
test
def send(self, api_key=None, secret=None, list_data=None, auth=False, **kwargs): """Sends the given Payload to the API via the websocket connection. :param kwargs: payload paarameters as key=value pairs :return: """ if auth: nonce = str(int(time.time() * 10000000)) auth_string = 'AUTH' + nonce auth_sig = hmac.new(secret.encode(), auth_string.encode(), hashlib.sha384).hexdigest() payload = {'event': 'auth', 'apiKey': api_key, 'authSig': auth_sig, 'authPayload': auth_string, 'authNonce': nonce} payload = json.dumps(payload) elif list_data: payload = json.dumps(list_data) else: payload = json.dumps(kwargs) self.log.debug("send(): Sending payload to API: %s", payload) try: self.socket.send(payload) except websocket.WebSocketConnectionClosedException: self.log.error("send(): Did not send out payload %s - client not connected. ", kwargs)
python
{ "resource": "" }
q271494
WebSocketConnection._unpause
test
def _unpause(self): """Unpauses the connection. Send a message up to client that he should re-subscribe to all channels. :return: """ self.log.debug("_unpause(): Clearing paused() Flag!") self.paused.clear() self.log.debug("_unpause(): Re-subscribing softly..") self._resubscribe(soft=True)
python
{ "resource": "" }
q271495
WebSocketConnection._system_handler
test
def _system_handler(self, data, ts): """Distributes system messages to the appropriate handler. System messages include everything that arrives as a dict, or a list containing a heartbeat. :param data: :param ts: :return: """ self.log.debug("_system_handler(): Received a system message: %s", data) # Unpack the data event = data.pop('event') if event == 'pong': self.log.debug("_system_handler(): Distributing %s to _pong_handler..", data) self._pong_handler() elif event == 'info': self.log.debug("_system_handler(): Distributing %s to _info_handler..", data) self._info_handler(data) elif event == 'error': self.log.debug("_system_handler(): Distributing %s to _error_handler..", data) self._error_handler(data) elif event in ('subscribed', 'unsubscribed', 'conf', 'auth', 'unauth'): self.log.debug("_system_handler(): Distributing %s to " "_response_handler..", data) self._response_handler(event, data, ts) else: self.log.error("Unhandled event: %s, data: %s", event, data)
python
{ "resource": "" }
q271496
WebSocketConnection._info_handler
test
def _info_handler(self, data): """ Handle INFO messages from the API and issues relevant actions. :param data: :param ts: """ def raise_exception(): """Log info code as error and raise a ValueError.""" self.log.error("%s: %s", data['code'], info_message[data['code']]) raise ValueError("%s: %s" % (data['code'], info_message[data['code']])) if 'code' not in data and 'version' in data: self.log.info('Initialized Client on API Version %s', data['version']) return info_message = {20000: 'Invalid User given! Please make sure the given ID is correct!', 20051: 'Stop/Restart websocket server ' '(please try to reconnect)', 20060: 'Refreshing data from the trading engine; ' 'please pause any acivity.', 20061: 'Done refreshing data from the trading engine.' ' Re-subscription advised.'} codes = {20051: self.reconnect, 20060: self._pause, 20061: self._unpause} if 'version' in data: self.log.info("API version: %i", data['version']) return try: self.log.info(info_message[data['code']]) codes[data['code']]() except KeyError as e: self.log.exception(e) self.log.error("Unknown Info code %s!", data['code']) raise
python
{ "resource": "" }
q271497
WebSocketConnection._error_handler
test
def _error_handler(self, data): """ Handle Error messages and log them accordingly. :param data: :param ts: """ errors = {10000: 'Unknown event', 10001: 'Generic error', 10008: 'Concurrency error', 10020: 'Request parameters error', 10050: 'Configuration setup failed', 10100: 'Failed authentication', 10111: 'Error in authentication request payload', 10112: 'Error in authentication request signature', 10113: 'Error in authentication request encryption', 10114: 'Error in authentication request nonce', 10200: 'Error in un-authentication request', 10300: 'Subscription Failed (generic)', 10301: 'Already Subscribed', 10302: 'Unknown channel', 10400: 'Subscription Failed (generic)', 10401: 'Not subscribed', 11000: 'Not ready, try again later', 20000: 'User is invalid!', 20051: 'Websocket server stopping', 20060: 'Websocket server resyncing', 20061: 'Websocket server resync complete' } try: self.log.error(errors[data['code']]) except KeyError: self.log.error("Received unknown error Code in message %s! " "Reconnecting..", data)
python
{ "resource": "" }
q271498
WebSocketConnection._data_handler
test
def _data_handler(self, data, ts): """Handles data messages by passing them up to the client. :param data: :param ts: :return: """ # Pass the data up to the Client self.log.debug("_data_handler(): Passing %s to client..", data) self.pass_to_client('data', data, ts)
python
{ "resource": "" }
q271499
WebSocketConnection._resubscribe
test
def _resubscribe(self, soft=False): """Resubscribes to all channels found in self.channel_configs. :param soft: if True, unsubscribes first. :return: None """ # Restore non-default Bitfinex websocket configuration if self.bitfinex_config: self.send(**self.bitfinex_config) q_list = [] while True: try: identifier, q = self.channel_configs.popitem(last=True if soft else False) except KeyError: break q_list.append((identifier, q.copy())) if identifier == 'auth': self.send(**q, auth=True) continue if soft: q['event'] = 'unsubscribe' self.send(**q) # Resubscribe for soft start. if soft: for identifier, q in reversed(q_list): self.channel_configs[identifier] = q self.send(**q) else: for identifier, q in q_list: self.channel_configs[identifier] = q
python
{ "resource": "" }