repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.search
python
def search(self, type, **args): if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args)
https://developers.facebook.com/docs/places/search
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L146-L154
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.get_connections
python
def get_connections(self, id, connection_name, **args): return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args )
Fetches the connections for given object.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L156-L160
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.get_all_connections
python
def get_all_connections(self, id, connection_name, **args): while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"]
Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L162-L176
[ "def get_connections(self, id, connection_name, **args):\n \"\"\"Fetches the connections for given object.\"\"\"\n return self.request(\n \"{0}/{1}/{2}\".format(self.version, id, connection_name), args\n )\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.put_object
python
def put_object(self, parent_object, connection_name, **data): assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", )
Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L178-L202
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.delete_object
python
def delete_object(self, id): return self.request( "{0}/{1}".format(self.version, id), method="DELETE" )
Deletes the object with the given ID from the graph.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L212-L216
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.delete_request
python
def delete_request(self, user_id, request_id): return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" )
Deletes the Request with the given ID for the given user.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L218-L222
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.put_photo
python
def put_photo(self, image, album_path="me/photos", **kwargs): return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", )
Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L224-L237
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.get_version
python
def get_version(self): args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available")
Fetches the current version number of the Graph API being used.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L239-L259
null
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.request
python
def request( self, path, args=None, post_args=None, files=None, method=None ): if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result
Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L261-L323
null
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.get_app_access_token
python
def get_app_access_token(self, app_id, app_secret, offline=False): if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"]
Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens>
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L325-L344
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.get_access_token_from_code
python
def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args )
Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable).
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L346-L364
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.extend_access_token
python
def extend_access_token(self, app_id, app_secret): args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )
Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension>
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L366-L382
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.debug_access_token
python
def debug_access_token(self, token, app_id, app_secret): args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args)
Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens>
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L384-L399
[ "def request(\n self, path, args=None, post_args=None, files=None, method=None\n):\n \"\"\"Fetches the given path in the Graph API.\n\n We translate args to a valid query string. If post_args is\n given, we send a POST request to the given path with the given\n arguments.\n\n \"\"\"\n if args is None:\n args = dict()\n if post_args is not None:\n method = \"POST\"\n\n # Add `access_token` to post_args or args if it has not already been\n # included.\n if self.access_token:\n # If post_args exists, we assume that args either does not exists\n # or it does not need `access_token`.\n if post_args and \"access_token\" not in post_args:\n post_args[\"access_token\"] = self.access_token\n elif \"access_token\" not in args:\n args[\"access_token\"] = self.access_token\n\n try:\n response = self.session.request(\n method or \"GET\",\n FACEBOOK_GRAPH_URL + path,\n timeout=self.timeout,\n params=args,\n data=post_args,\n proxies=self.proxies,\n files=files,\n )\n except requests.HTTPError as e:\n response = json.loads(e.read())\n raise GraphAPIError(response)\n\n headers = response.headers\n if \"json\" in headers[\"content-type\"]:\n result = response.json()\n elif \"image/\" in headers[\"content-type\"]:\n mimetype = headers[\"content-type\"]\n result = {\n \"data\": response.content,\n \"mime-type\": mimetype,\n \"url\": response.url,\n }\n elif \"access_token\" in parse_qs(response.text):\n query_str = parse_qs(response.text)\n if \"access_token\" in query_str:\n result = {\"access_token\": query_str[\"access_token\"][0]}\n if \"expires\" in query_str:\n result[\"expires\"] = query_str[\"expires\"][0]\n else:\n raise GraphAPIError(response.json())\n else:\n raise GraphAPIError(\"Maintype was not text, image, or querystring\")\n\n if result and isinstance(result, dict) and result.get(\"error\"):\n raise GraphAPIError(result)\n return result\n" ]
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): """Build a URL to create an OAuth dialog.""" url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
mobolic/facebook-sdk
facebook/__init__.py
GraphAPI.get_auth_url
python
def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs): url = "{0}{1}/{2}".format( FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH ) args = {"client_id": app_id, "redirect_uri": canvas_url} if perms: args["scope"] = ",".join(perms) args.update(kwargs) return url + urlencode(args)
Build a URL to create an OAuth dialog.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L401-L411
null
class GraphAPI(object): """A client for the Facebook Graph API. https://developers.facebook.com/docs/graph-api The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at https://developers.facebook.com/docs/graph-api/reference/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See https://developers.facebook.com/docs/facebook-login for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__( self, access_token=None, timeout=None, version=None, proxies=None, session=None, ): # The default version is only used if the version kwarg does not exist. default_version = VALID_API_VERSIONS[0] self.access_token = access_token self.timeout = timeout self.proxies = proxies self.session = session or requests.Session() if version: version_regex = re.compile("^\d\.\d{1,2}$") match = version_regex.search(str(version)) if match is not None: if str(version) not in VALID_API_VERSIONS: raise GraphAPIError( "Valid API versions are " + str(VALID_API_VERSIONS).strip("[]") ) else: self.version = "v" + str(version) else: raise GraphAPIError( "Version number should be in the" " following format: #.# (e.g. 2.0)." ) else: self.version = "v" + default_version def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"} def get_object(self, id, **args): """Fetches the given object from the graph.""" return self.request("{0}/{1}".format(self.version, id), args) def get_objects(self, ids, **args): """Fetches all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request(self.version + "/", args) def search(self, type, **args): """https://developers.facebook.com/docs/places/search""" if type not in VALID_SEARCH_TYPES: raise GraphAPIError( "Valid types are: %s" % ", ".join(VALID_SEARCH_TYPES) ) args["type"] = type return self.request(self.version + "/search/", args) def get_connections(self, id, connection_name, **args): """Fetches the connections for given object.""" return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args ) def get_all_connections(self, id, connection_name, **args): """Get all pages from a get_connections call This will iterate over all pages returned by a get_connections call and yield the individual items. """ while True: page = self.get_connections(id, connection_name, **args) for post in page["data"]: yield post next = page.get("paging", {}).get("next") if not next: return args = parse_qs(urlparse(next).query) del args["access_token"] def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") Certain operations require extended permissions. See https://developers.facebook.com/docs/facebook-login/permissions for details about permissions. """ assert self.access_token, "Write operations require an access token" return self.request( "{0}/{1}/{2}".format(self.version, parent_object, connection_name), post_args=data, method="POST", ) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" return self.request( "{0}/{1}".format(self.version, id), method="DELETE" ) def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" return self.request( "{0}_{1}".format(request_id, user_id), method="DELETE" ) def put_photo(self, image, album_path="me/photos", **kwargs): """ Upload an image using multipart/form-data. image - A file object representing the image to be uploaded. album_path - A path representing where the image should be uploaded. """ return self.request( "{0}/{1}".format(self.version, album_path), post_args=kwargs, files={"source": image}, method="POST", ) def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args, timeout=self.timeout, proxies=self.proxies, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) try: headers = response.headers version = headers["facebook-api-version"].replace("v", "") return str(version) except Exception: raise GraphAPIError("API version number not available") def request( self, path, args=None, post_args=None, files=None, method=None ): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if args is None: args = dict() if post_args is not None: method = "POST" # Add `access_token` to post_args or args if it has not already been # included. if self.access_token: # If post_args exists, we assume that args either does not exists # or it does not need `access_token`. if post_args and "access_token" not in post_args: post_args["access_token"] = self.access_token elif "access_token" not in args: args["access_token"] = self.access_token try: response = self.session.request( method or "GET", FACEBOOK_GRAPH_URL + path, timeout=self.timeout, params=args, data=post_args, proxies=self.proxies, files=files, ) except requests.HTTPError as e: response = json.loads(e.read()) raise GraphAPIError(response) headers = response.headers if "json" in headers["content-type"]: result = response.json() elif "image/" in headers["content-type"]: mimetype = headers["content-type"] result = { "data": response.content, "mime-type": mimetype, "url": response.url, } elif "access_token" in parse_qs(response.text): query_str = parse_qs(response.text) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] else: raise GraphAPIError(response.json()) else: raise GraphAPIError("Maintype was not text, image, or querystring") if result and isinstance(result, dict) and result.get("error"): raise GraphAPIError(result) return result def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = { "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args=args )["access_token"] def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret ): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } return self.request( "{0}/oauth/access_token".format(self.version), args ) def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/docs/facebook-login/access-tokens/ expiration-and-extension> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } return self.request( "{0}/oauth/access_token".format(self.version), args=args ) def debug_access_token(self, token, app_id, app_secret): """ Gets information about a user access token issued by an app. See <https://developers.facebook.com/docs/facebook-login/ access-tokens/debugging-and-error-handling> We can generate the app access token by concatenating the app id and secret: <https://developers.facebook.com/docs/ facebook-login/access-tokens#apptokens> """ args = { "input_token": token, "access_token": "{0}|{1}".format(app_id, app_secret), } return self.request(self.version + "/" + "debug_token", args=args)
mobolic/facebook-sdk
examples/flask/app/views.py
get_current_user
python
def get_current_user(): # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get("user"): g.user = session.get("user") return # Attempt to get the short term access token for the current user. result = get_user_from_cookie( cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET ) # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. user = User.query.filter(User.id == result["uid"]).first() if not user: # Not an existing user so get info graph = GraphAPI(result["access_token"]) profile = graph.get_object("me") if "link" not in profile: profile["link"] = "" # Create the user and insert it into the database user = User( id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=result["access_token"], ) db.session.add(user) elif user.access_token != result["access_token"]: # If an existing user, update the access token user.access_token = result["access_token"] # Add the user to the current session session["user"] = dict( name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token, ) # Commit changes to the database and set the user as a global g.user db.session.commit() g.user = session.get("user", None)
Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user.
train
https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/examples/flask/app/views.py#L38-L95
[ "def get_user_from_cookie(cookies, app_id, app_secret):\n \"\"\"Parses the cookie set by the official Facebook JavaScript SDK.\n\n cookies should be a dictionary-like object mapping cookie names to\n cookie values.\n\n If the user is logged in via Facebook, we return a dictionary with\n the keys \"uid\" and \"access_token\". The former is the user's\n Facebook ID, and the latter can be used to make authenticated\n requests to the Graph API. If the user is not logged in, we\n return None.\n\n Read more about Facebook authentication at\n https://developers.facebook.com/docs/facebook-login.\n\n \"\"\"\n cookie = cookies.get(\"fbsr_\" + app_id, \"\")\n if not cookie:\n return None\n parsed_request = parse_signed_request(cookie, app_secret)\n if not parsed_request:\n return None\n try:\n result = GraphAPI().get_access_token_from_code(\n parsed_request[\"code\"], \"\", app_id, app_secret\n )\n except GraphAPIError:\n return None\n result[\"uid\"] = parsed_request[\"user_id\"]\n return result\n" ]
from facebook import get_user_from_cookie, GraphAPI from flask import g, render_template, redirect, request, session, url_for from app import app, db from .models import User # Facebook app details FB_APP_ID = "" FB_APP_NAME = "" FB_APP_SECRET = "" @app.route("/") def index(): # If a user was set in the get_current_user function before the request, # the user is logged in. if g.user: return render_template( "index.html", app_id=FB_APP_ID, app_name=FB_APP_NAME, user=g.user ) # Otherwise, a user is not logged in. return render_template("login.html", app_id=FB_APP_ID, name=FB_APP_NAME) @app.route("/logout") def logout(): """Log out the user from the application. Log out the user from the application by removing them from the session. Note: this does not log the user out of Facebook - this is done by the JavaScript SDK. """ session.pop("user", None) return redirect(url_for("index")) @app.before_request
manrajgrover/halo
halo/halo.py
Halo.spinner
python
def spinner(self, spinner=None): self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0
Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L125-L135
[ "def _get_spinner(self, spinner):\n \"\"\"Extracts spinner value from options and returns value\n containing spinner frames and interval, defaults to 'dots' spinner.\n Parameters\n ----------\n spinner : dict, str\n Contains spinner value or type of spinner to be used\n Returns\n -------\n dict\n Contains frames and interval defining spinner\n \"\"\"\n default_spinner = Spinners['dots'].value\n\n if spinner and type(spinner) == dict:\n return spinner\n\n if is_supported():\n if all([is_text_type(spinner), spinner in Spinners.__members__]):\n return Spinners[spinner].value\n else:\n return default_spinner\n else:\n return Spinners['line'].value\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.placement
python
def placement(self, placement): if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement
Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L208-L218
null
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.animation
python
def animation(self, animation): self._animation = animation self._text = self._get_text(self._text['original'])
Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L241-L249
[ "def _get_text(self, text):\n \"\"\"Creates frames based on the selected animation\n Returns\n -------\n self\n \"\"\"\n animation = self._animation\n stripped_text = text.strip()\n\n # Check which frame of the animation is the widest\n max_spinner_length = max([len(i) for i in self._spinner['frames']])\n\n # Subtract to the current terminal size the max spinner length\n # (-1 to leave room for the extra space between spinner and text)\n terminal_width = get_terminal_columns() - max_spinner_length - 1\n text_length = len(stripped_text)\n\n frames = []\n\n if terminal_width < text_length and animation:\n if animation == 'bounce':\n \"\"\"\n Make the text bounce back and forth\n \"\"\"\n for x in range(0, text_length - terminal_width + 1):\n frames.append(stripped_text[x:terminal_width + x])\n frames.extend(list(reversed(frames)))\n elif 'marquee':\n \"\"\"\n Make the text scroll like a marquee\n \"\"\"\n stripped_text = stripped_text + ' ' + stripped_text[:terminal_width]\n for x in range(0, text_length + 1):\n frames.append(stripped_text[x:terminal_width + x])\n elif terminal_width < text_length and not animation:\n # Add ellipsis if text is larger than terminal width and no animation was specified\n frames = [stripped_text[:terminal_width - 6] + ' (...)']\n else:\n frames = [stripped_text]\n\n return {\n 'original': text,\n 'frames': frames\n }\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo._get_spinner
python
def _get_spinner(self, spinner): default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value
Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L251-L274
[ "def is_supported():\n \"\"\"Check whether operating system supports main symbols or not.\n\n Returns\n -------\n boolean\n Whether operating system supports main symbols or not\n \"\"\"\n\n os_arch = platform.system()\n\n if os_arch != 'Windows':\n return True\n\n return False\n", "def is_text_type(text):\n \"\"\"Check if given parameter is a string or not\n\n Parameters\n ----------\n text : *\n Parameter to be checked for text type\n\n Returns\n -------\n bool\n Whether parameter is a string or not\n \"\"\"\n if isinstance(text, six.text_type) or isinstance(text, six.string_types):\n return True\n\n return False\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo._get_text
python
def _get_text(self, text): animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames }
Creates frames based on the selected animation Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L276-L319
[ "def get_terminal_columns():\n \"\"\"Determine the amount of available columns in the terminal\n\n Returns\n -------\n int\n Terminal width\n \"\"\"\n terminal_size = get_terminal_size()\n\n # If column size is 0 either we are not connected\n # to a terminal or something else went wrong. Fallback to 80.\n if terminal_size.columns == 0:\n return 80\n else:\n return terminal_size.columns\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.clear
python
def clear(self): if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self
Clears the line and returns cursor to the start. of line Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L321-L334
null
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo._render_frame
python
def _render_frame(self): frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output))
Renders the frame on the line after clearing it.
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L336-L345
[ "def encode_utf_8_text(text):\n \"\"\"Encodes the text to utf-8 format\n\n Parameters\n ----------\n text : str\n String to be encoded\n\n Returns\n -------\n str\n Encoded string\n \"\"\"\n try:\n return codecs.encode(text, 'utf-8', 'ignore')\n except (TypeError, ValueError):\n return text\n", "def clear(self):\n \"\"\"Clears the line and returns cursor to the start.\n of line\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n self._stream.write('\\r')\n self._stream.write(self.CLEAR_LINE)\n\n return self\n", "def frame(self):\n \"\"\"Builds and returns the frame to be rendered\n Returns\n -------\n self\n \"\"\"\n frames = self._spinner['frames']\n frame = frames[self._frame_index]\n\n if self._color:\n frame = colored_frame(frame, self._color)\n\n self._frame_index += 1\n self._frame_index = self._frame_index % len(frames)\n\n text_frame = self.text_frame()\n return u'{0} {1}'.format(*[\n (text_frame, frame)\n if self._placement == 'right' else\n (frame, text_frame)\n ][0])\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.render
python
def render(self): while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self
Runs the render until thread flag is set. Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L347-L357
null
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.frame
python
def frame(self): frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0])
Builds and returns the frame to be rendered Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L359-L379
[ "def colored_frame(frame, color):\n \"\"\"Color the frame with given color and returns.\n\n Parameters\n ----------\n frame : str\n Frame to be colored\n color : str\n Color to be applied\n\n Returns\n -------\n str\n Colored frame\n \"\"\"\n return colored(frame, color, attrs=['bold'])\n", "def text_frame(self):\n \"\"\"Builds and returns the text frame to be rendered\n Returns\n -------\n self\n \"\"\"\n if len(self._text['frames']) == 1:\n if self._text_color:\n return colored_frame(self._text['frames'][0], self._text_color)\n\n # Return first frame (can't return original text because at this point it might be ellipsed)\n return self._text['frames'][0]\n\n frames = self._text['frames']\n frame = frames[self._text_index]\n\n self._text_index += 1\n self._text_index = self._text_index % len(frames)\n\n if self._text_color:\n return colored_frame(frame, self._text_color)\n\n return frame\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.text_frame
python
def text_frame(self): if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame
Builds and returns the text frame to be rendered Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L381-L403
[ "def colored_frame(frame, color):\n \"\"\"Color the frame with given color and returns.\n\n Parameters\n ----------\n frame : str\n Frame to be colored\n color : str\n Color to be applied\n\n Returns\n -------\n str\n Colored frame\n \"\"\"\n return colored(frame, color, attrs=['bold'])\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.start
python
def start(self, text=None): if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self
Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L405-L431
[ "def _render_frame(self):\n \"\"\"Renders the frame on the line after clearing it.\n \"\"\"\n frame = self.frame()\n output = '\\r{0}'.format(frame)\n self.clear()\n try:\n self._stream.write(output)\n except UnicodeEncodeError:\n self._stream.write(encode_utf_8_text(output))\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.stop
python
def stop(self): if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self
Stops the spinner and clears the line. Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L433-L453
[ "def clear(self):\n \"\"\"Clears the line and returns cursor to the start.\n of line\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n self._stream.write('\\r')\n self._stream.write(self.CLEAR_LINE)\n\n return self\n", "def clear(self):\n if not self._enabled:\n return self\n\n with self.output:\n self.output.outputs += self._output('\\r')\n self.output.outputs += self._output(self.CLEAR_LINE)\n\n self.output.outputs = self._output()\n return self\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.succeed
python
def succeed(self, text=None): return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text)
Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L455-L465
[ "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = u'{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n try:\n self._stream.write(output)\n except UnicodeEncodeError:\n self._stream.write(encode_utf_8_text(output))\n\n return self\n", "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = '\\r{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n with self.output:\n self.output.outputs = self._output(output)\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.fail
python
def fail(self, text=None): return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text)
Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L467-L477
[ "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = u'{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n try:\n self._stream.write(output)\n except UnicodeEncodeError:\n self._stream.write(encode_utf_8_text(output))\n\n return self\n", "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = '\\r{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n with self.output:\n self.output.outputs = self._output(output)\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.warn
python
def warn(self, text=None): return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text)
Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L479-L489
[ "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = u'{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n try:\n self._stream.write(output)\n except UnicodeEncodeError:\n self._stream.write(encode_utf_8_text(output))\n\n return self\n", "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = '\\r{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n with self.output:\n self.output.outputs = self._output(output)\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.info
python
def info(self, text=None): return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text)
Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L491-L501
[ "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = u'{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n try:\n self._stream.write(output)\n except UnicodeEncodeError:\n self._stream.write(encode_utf_8_text(output))\n\n return self\n", "def stop_and_persist(self, symbol=' ', text=None):\n \"\"\"Stops the spinner and persists the final frame to be shown.\n Parameters\n ----------\n symbol : str, optional\n Symbol to be shown in final frame\n text: str, optional\n Text to be shown in final frame\n\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n symbol = decode_utf_8_text(symbol)\n\n if text is not None:\n text = decode_utf_8_text(text)\n else:\n text = self._text['original']\n\n text = text.strip()\n\n if self._text_color:\n text = colored_frame(text, self._text_color)\n\n self.stop()\n\n output = '\\r{0} {1}\\n'.format(*[\n (text, symbol)\n if self._placement == 'right' else\n (symbol, text)\n ][0])\n\n with self.output:\n self.output.outputs = self._output(output)\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self """ if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
manrajgrover/halo
halo/halo.py
Halo.stop_and_persist
python
def stop_and_persist(self, symbol=' ', text=None): if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = u'{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) return self
Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L503-L544
[ "def decode_utf_8_text(text):\n \"\"\"Decode the text from utf-8 format\n\n Parameters\n ----------\n text : str\n String to be decoded\n\n Returns\n -------\n str\n Decoded string\n \"\"\"\n try:\n return codecs.decode(text, 'utf-8')\n except (TypeError, ValueError):\n return text\n", "def encode_utf_8_text(text):\n \"\"\"Encodes the text to utf-8 format\n\n Parameters\n ----------\n text : str\n String to be encoded\n\n Returns\n -------\n str\n Encoded string\n \"\"\"\n try:\n return codecs.encode(text, 'utf-8', 'ignore')\n except (TypeError, ValueError):\n return text\n", "def colored_frame(frame, color):\n \"\"\"Color the frame with given color and returns.\n\n Parameters\n ----------\n frame : str\n Frame to be colored\n color : str\n Color to be applied\n\n Returns\n -------\n str\n Colored frame\n \"\"\"\n return colored(frame, color, attrs=['bold'])\n", "def stop(self):\n \"\"\"Stops the spinner and clears the line.\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n if self._spinner_thread:\n self._stop_spinner.set()\n self._spinner_thread.join()\n\n self._frame_index = 0\n self._spinner_id = None\n self.clear()\n\n if self._stream.isatty():\n cursor.show(stream=self._stream)\n\n return self\n" ]
class Halo(object): """Halo library. Attributes ---------- CLEAR_LINE : str Code to clear the line """ CLEAR_LINE = '\033[K' SPINNER_PLACEMENTS = ('left', 'right',) def __init__(self, text='', color='cyan', text_color=None, spinner=None, animation=None, placement='left', interval=-1, enabled=True, stream=sys.stdout): """Constructs the Halo object. Parameters ---------- text : str, optional Text to display. text_color : str, optional Color of the text. color : str, optional Color of the text to display. spinner : str|dict, optional String or dictionary representing spinner. String can be one of 60+ spinners supported. animation: str, optional Animation to apply if text is too large. Can be one of `bounce`, `marquee`. Defaults to ellipses. placement: str, optional Side of the text to place the spinner on. Can be `left` or `right`. Defaults to `left`. interval : integer, optional Interval between each frame of the spinner in milliseconds. enabled : boolean, optional Spinner enabled or not. stream : io, optional Output. """ self._color = color self._animation = animation self.spinner = spinner self.text = text self._text_color = text_color self._interval = int(interval) if int(interval) > 0 else self._spinner['interval'] self._stream = stream self.placement = placement self._frame_index = 0 self._text_index = 0 self._spinner_thread = None self._stop_spinner = None self._spinner_id = None self._enabled = enabled # Need to check for stream environment = get_environment() def clean_up(): """Handle cell execution""" self.stop() if environment in ('ipython', 'jupyter'): from IPython import get_ipython ip = get_ipython() ip.events.register('post_run_cell', clean_up) else: # default terminal atexit.register(clean_up) def __enter__(self): """Starts the spinner on a separate thread. For use in context managers. Returns ------- self """ return self.start() def __exit__(self, type, value, traceback): """Stops the spinner. For use in context managers.""" self.stop() def __call__(self, f): """Allow the Halo object to be used as a regular function decorator.""" @functools.wraps(f) def wrapped(*args, **kwargs): with self: return f(*args, **kwargs) return wrapped @property def spinner(self): """Getter for spinner property. Returns ------- dict spinner value """ return self._spinner @spinner.setter def spinner(self, spinner=None): """Setter for spinner property. Parameters ---------- spinner : dict, str Defines the spinner value with frame and interval """ self._spinner = self._get_spinner(spinner) self._frame_index = 0 self._text_index = 0 @property def text(self): """Getter for text property. Returns ------- str text value """ return self._text['original'] @text.setter def text(self, text): """Setter for text property. Parameters ---------- text : str Defines the text value for spinner """ self._text = self._get_text(text) @property def text_color(self): """Getter for text color property. Returns ------- str text color value """ return self._text_color @text_color.setter def text_color(self, text_color): """Setter for text color property. Parameters ---------- text_color : str Defines the text color value for spinner """ self._text_color = text_color @property def color(self): """Getter for color property. Returns ------- str color value """ return self._color @color.setter def color(self, color): """Setter for color property. Parameters ---------- color : str Defines the color value for spinner """ self._color = color @property def placement(self): """Getter for placement property. Returns ------- str spinner placement """ return self._placement @placement.setter def placement(self, placement): """Setter for placement property. Parameters ---------- placement: str Defines the placement of the spinner """ if placement not in self.SPINNER_PLACEMENTS: raise ValueError( "Unknown spinner placement '{0}', available are {1}".format(placement, self.SPINNER_PLACEMENTS)) self._placement = placement @property def spinner_id(self): """Getter for spinner id Returns ------- str Spinner id value """ return self._spinner_id @property def animation(self): """Getter for animation property. Returns ------- str Spinner animation """ return self._animation @animation.setter def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original']) def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns ------- dict Contains frames and interval defining spinner """ default_spinner = Spinners['dots'].value if spinner and type(spinner) == dict: return spinner if is_supported(): if all([is_text_type(spinner), spinner in Spinners.__members__]): return Spinners[spinner].value else: return default_spinner else: return Spinners['line'].value def _get_text(self, text): """Creates frames based on the selected animation Returns ------- self """ animation = self._animation stripped_text = text.strip() # Check which frame of the animation is the widest max_spinner_length = max([len(i) for i in self._spinner['frames']]) # Subtract to the current terminal size the max spinner length # (-1 to leave room for the extra space between spinner and text) terminal_width = get_terminal_columns() - max_spinner_length - 1 text_length = len(stripped_text) frames = [] if terminal_width < text_length and animation: if animation == 'bounce': """ Make the text bounce back and forth """ for x in range(0, text_length - terminal_width + 1): frames.append(stripped_text[x:terminal_width + x]) frames.extend(list(reversed(frames))) elif 'marquee': """ Make the text scroll like a marquee """ stripped_text = stripped_text + ' ' + stripped_text[:terminal_width] for x in range(0, text_length + 1): frames.append(stripped_text[x:terminal_width + x]) elif terminal_width < text_length and not animation: # Add ellipsis if text is larger than terminal width and no animation was specified frames = [stripped_text[:terminal_width - 6] + ' (...)'] else: frames = [stripped_text] return { 'original': text, 'frames': frames } def clear(self): """Clears the line and returns cursor to the start. of line Returns ------- self """ if not self._enabled: return self self._stream.write('\r') self._stream.write(self.CLEAR_LINE) return self def _render_frame(self): """Renders the frame on the line after clearing it. """ frame = self.frame() output = '\r{0}'.format(frame) self.clear() try: self._stream.write(output) except UnicodeEncodeError: self._stream.write(encode_utf_8_text(output)) def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self def frame(self): """Builds and returns the frame to be rendered Returns ------- self """ frames = self._spinner['frames'] frame = frames[self._frame_index] if self._color: frame = colored_frame(frame, self._color) self._frame_index += 1 self._frame_index = self._frame_index % len(frames) text_frame = self.text_frame() return u'{0} {1}'.format(*[ (text_frame, frame) if self._placement == 'right' else (frame, text_frame) ][0]) def text_frame(self): """Builds and returns the text frame to be rendered Returns ------- self """ if len(self._text['frames']) == 1: if self._text_color: return colored_frame(self._text['frames'][0], self._text_color) # Return first frame (can't return original text because at this point it might be ellipsed) return self._text['frames'][0] frames = self._text['frames'] frame = frames[self._text_index] self._text_index += 1 self._text_index = self._text_index % len(frames) if self._text_color: return colored_frame(frame, self._text_color) return frame def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self def stop(self): """Stops the spinner and clears the line. Returns ------- self """ if not self._enabled: return self if self._spinner_thread: self._stop_spinner.set() self._spinner_thread.join() self._frame_index = 0 self._spinner_id = None self.clear() if self._stream.isatty(): cursor.show(stream=self._stream) return self def succeed(self, text=None): """Shows and persists success symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside success symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.SUCCESS.value, text=text) def fail(self, text=None): """Shows and persists fail symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside fail symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.ERROR.value, text=text) def warn(self, text=None): """Shows and persists warn symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside warn symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.WARNING.value, text=text) def info(self, text=None): """Shows and persists info symbol and text and exits. Parameters ---------- text : None, optional Text to be shown alongside info symbol. Returns ------- self """ return self.stop_and_persist(symbol=LogSymbols.INFO.value, text=text)
manrajgrover/halo
halo/_utils.py
get_environment
python
def get_environment(): try: from IPython import get_ipython except ImportError: return 'terminal' try: shell = get_ipython().__class__.__name__ if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole return 'jupyter' elif shell == 'TerminalInteractiveShell': # Terminal running IPython return 'ipython' else: return 'terminal' # Other type (?) except NameError: return 'terminal'
Get the environment in which halo is running Returns ------- str Environment name
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/_utils.py#L35-L59
null
# -*- coding: utf-8 -*- """Utilities for Halo library. """ import codecs import platform import six try: from shutil import get_terminal_size except ImportError: from backports.shutil_get_terminal_size import get_terminal_size from colorama import init from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating system supports main symbols or not """ os_arch = platform.system() if os_arch != 'Windows': return True return False def colored_frame(frame, color): """Color the frame with given color and returns. Parameters ---------- frame : str Frame to be colored color : str Color to be applied Returns ------- str Colored frame """ return colored(frame, color, attrs=['bold']) def is_text_type(text): """Check if given parameter is a string or not Parameters ---------- text : * Parameter to be checked for text type Returns ------- bool Whether parameter is a string or not """ if isinstance(text, six.text_type) or isinstance(text, six.string_types): return True return False def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except (TypeError, ValueError): return text def encode_utf_8_text(text): """Encodes the text to utf-8 format Parameters ---------- text : str String to be encoded Returns ------- str Encoded string """ try: return codecs.encode(text, 'utf-8', 'ignore') except (TypeError, ValueError): return text def get_terminal_columns(): """Determine the amount of available columns in the terminal Returns ------- int Terminal width """ terminal_size = get_terminal_size() # If column size is 0 either we are not connected # to a terminal or something else went wrong. Fallback to 80. if terminal_size.columns == 0: return 80 else: return terminal_size.columns
manrajgrover/halo
halo/_utils.py
is_text_type
python
def is_text_type(text): if isinstance(text, six.text_type) or isinstance(text, six.string_types): return True return False
Check if given parameter is a string or not Parameters ---------- text : * Parameter to be checked for text type Returns ------- bool Whether parameter is a string or not
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/_utils.py#L80-L96
null
# -*- coding: utf-8 -*- """Utilities for Halo library. """ import codecs import platform import six try: from shutil import get_terminal_size except ImportError: from backports.shutil_get_terminal_size import get_terminal_size from colorama import init from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating system supports main symbols or not """ os_arch = platform.system() if os_arch != 'Windows': return True return False def get_environment(): """Get the environment in which halo is running Returns ------- str Environment name """ try: from IPython import get_ipython except ImportError: return 'terminal' try: shell = get_ipython().__class__.__name__ if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole return 'jupyter' elif shell == 'TerminalInteractiveShell': # Terminal running IPython return 'ipython' else: return 'terminal' # Other type (?) except NameError: return 'terminal' def colored_frame(frame, color): """Color the frame with given color and returns. Parameters ---------- frame : str Frame to be colored color : str Color to be applied Returns ------- str Colored frame """ return colored(frame, color, attrs=['bold']) def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except (TypeError, ValueError): return text def encode_utf_8_text(text): """Encodes the text to utf-8 format Parameters ---------- text : str String to be encoded Returns ------- str Encoded string """ try: return codecs.encode(text, 'utf-8', 'ignore') except (TypeError, ValueError): return text def get_terminal_columns(): """Determine the amount of available columns in the terminal Returns ------- int Terminal width """ terminal_size = get_terminal_size() # If column size is 0 either we are not connected # to a terminal or something else went wrong. Fallback to 80. if terminal_size.columns == 0: return 80 else: return terminal_size.columns
manrajgrover/halo
halo/halo_notebook.py
HaloNotebook.stop_and_persist
python
def stop_and_persist(self, symbol=' ', text=None): if not self._enabled: return self symbol = decode_utf_8_text(symbol) if text is not None: text = decode_utf_8_text(text) else: text = self._text['original'] text = text.strip() if self._text_color: text = colored_frame(text, self._text_color) self.stop() output = '\r{0} {1}\n'.format(*[ (text, symbol) if self._placement == 'right' else (symbol, text) ][0]) with self.output: self.output.outputs = self._output(output)
Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self
train
https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo_notebook.py#L73-L110
[ "def decode_utf_8_text(text):\n \"\"\"Decode the text from utf-8 format\n\n Parameters\n ----------\n text : str\n String to be decoded\n\n Returns\n -------\n str\n Decoded string\n \"\"\"\n try:\n return codecs.decode(text, 'utf-8')\n except (TypeError, ValueError):\n return text\n", "def colored_frame(frame, color):\n \"\"\"Color the frame with given color and returns.\n\n Parameters\n ----------\n frame : str\n Frame to be colored\n color : str\n Color to be applied\n\n Returns\n -------\n str\n Colored frame\n \"\"\"\n return colored(frame, color, attrs=['bold'])\n", "def stop(self):\n \"\"\"Stops the spinner and clears the line.\n Returns\n -------\n self\n \"\"\"\n if not self._enabled:\n return self\n\n if self._spinner_thread:\n self._stop_spinner.set()\n self._spinner_thread.join()\n\n self._frame_index = 0\n self._spinner_id = None\n self.clear()\n\n if self._stream.isatty():\n cursor.show(stream=self._stream)\n\n return self\n", "def _output(self, text=''):\n return ({'name': 'stdout', 'output_type': 'stream', 'text': text},)\n" ]
class HaloNotebook(Halo): def __init__(self, text='', color='cyan', text_color=None, spinner=None, placement='left', animation=None, interval=-1, enabled=True, stream=sys.stdout): super(HaloNotebook, self).__init__(text=text, color=color, text_color=text_color, spinner=spinner, placement=placement, animation=animation, interval=interval, enabled=enabled, stream=stream) self.output = self._make_output_widget() def _make_output_widget(self): from ipywidgets.widgets import Output return Output() # TODO: using property and setter def _output(self, text=''): return ({'name': 'stdout', 'output_type': 'stream', 'text': text},) def clear(self): if not self._enabled: return self with self.output: self.output.outputs += self._output('\r') self.output.outputs += self._output(self.CLEAR_LINE) self.output.outputs = self._output() return self def _render_frame(self): frame = self.frame() output = '\r{0}'.format(frame) with self.output: self.output.outputs += self._output(output) def start(self, text=None): if text is not None: self.text = text if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide() self.output = self._make_output_widget() from IPython.display import display display(self.output) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self
freakboy3742/pyxero
xero/utils.py
parse_date
python
def parse_date(string, force_datetime=False): matches = DATE.match(string) if not matches: return None values = dict([ ( k, v if v[0] in '+-' else int(v) ) for k,v in matches.groupdict().items() if v and int(v) ]) if 'timestamp' in values: value = datetime.datetime.utcfromtimestamp(0) + datetime.timedelta( hours=int(values.get('offset_h', 0)), minutes=int(values.get('offset_m', 0)), seconds=int(values['timestamp']) / 1000.0 ) return value # I've made an assumption here, that a DateTime value will not # ever be YYYY-MM-DDT00:00:00, which is probably bad. I'm not # really sure how to handle this, other than to hard-code the # names of the field that are actually Date rather than DateTime. if len(values) > 3 or force_datetime: return datetime.datetime(**values) # Sometimes Xero returns Date(0+0000), so we end up with no # values. Return None for this case if not values: return None return datetime.date(**values)
Takes a Xero formatted date, e.g. /Date(1426849200000+1300)/
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/utils.py#L64-L97
null
from __future__ import unicode_literals import datetime import re import six DATE = re.compile( r'^(\/Date\((?P<timestamp>-?\d+)((?P<offset_h>[-+]\d\d)(?P<offset_m>\d\d))?\)\/)' r'|' r'((?P<year>\d{4})-(?P<month>[0-2]\d)-0?(?P<day>[0-3]\d)' r'T' r'(?P<hour>[0-5]\d):(?P<minute>[0-5]\d):(?P<second>[0-6]\d))$' ) OBJECT_NAMES = { "Addresses": "Address", "Attachments": "Attachment", "Accounts": "Account", "BankTransactions": "BankTransaction", "BankTransfers": "BankTransfer", "BrandingThemes": "BrandingTheme", "ContactGroups": "ContactGroup", "ContactPersons": "ContactPerson", "Contacts": "Contact", "CreditNotes": "CreditNote", "Currencies": "Currency", "Employees": "Employee", "ExpenseClaims": "ExpenseClaim", "Invoices": "Invoice", "Items": "Item", "Journals": "Journal", "ManualJournals": "ManualJournal", "Organisation": "Organisation", "Overpayments": "Overpayment", "Payments": "Payment", "PayrollCalendars": "PayrollCalendar", "PayRuns": "PayRun", "Phones": "Phone", "Prepayments": "Prepayment", "Receipts": "Receipt", "RepeatingInvoices": "RepeatingInvoice", "Reports": "Report", "TaxComponents": "TaxComponent", "TaxRates": "TaxRate", "TrackingCategories": "TrackingCategory", "Tracking": "TrackingCategory", "Users": "User", "Associations": "Association", "Files": "File", "Folders": "Folder", "Inbox": "Inbox", "LineItems": "LineItem", "JournalLines": "JournalLine", "PurchaseOrders": "PurchaseOrder", } def isplural(word): return word in OBJECT_NAMES.keys() def singular(word): return OBJECT_NAMES.get(word) def json_load_object_hook(dct): """ Hook for json.parse(...) to parse Xero date formats. """ for key, value in dct.items(): if isinstance(value, six.string_types): value = parse_date(value) if value: dct[key] = value return dct
freakboy3742/pyxero
xero/utils.py
json_load_object_hook
python
def json_load_object_hook(dct): for key, value in dct.items(): if isinstance(value, six.string_types): value = parse_date(value) if value: dct[key] = value return dct
Hook for json.parse(...) to parse Xero date formats.
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/utils.py#L100-L109
[ "def parse_date(string, force_datetime=False):\n \"\"\" Takes a Xero formatted date, e.g. /Date(1426849200000+1300)/\"\"\"\n matches = DATE.match(string)\n if not matches:\n return None\n\n values = dict([\n (\n k,\n v if v[0] in '+-' else int(v)\n ) for k,v in matches.groupdict().items() if v and int(v)\n ])\n\n if 'timestamp' in values:\n value = datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(\n hours=int(values.get('offset_h', 0)),\n minutes=int(values.get('offset_m', 0)),\n seconds=int(values['timestamp']) / 1000.0\n )\n return value\n\n # I've made an assumption here, that a DateTime value will not\n # ever be YYYY-MM-DDT00:00:00, which is probably bad. I'm not\n # really sure how to handle this, other than to hard-code the\n # names of the field that are actually Date rather than DateTime.\n if len(values) > 3 or force_datetime:\n return datetime.datetime(**values)\n\n # Sometimes Xero returns Date(0+0000), so we end up with no\n # values. Return None for this case\n if not values:\n return None\n\n return datetime.date(**values)\n" ]
from __future__ import unicode_literals import datetime import re import six DATE = re.compile( r'^(\/Date\((?P<timestamp>-?\d+)((?P<offset_h>[-+]\d\d)(?P<offset_m>\d\d))?\)\/)' r'|' r'((?P<year>\d{4})-(?P<month>[0-2]\d)-0?(?P<day>[0-3]\d)' r'T' r'(?P<hour>[0-5]\d):(?P<minute>[0-5]\d):(?P<second>[0-6]\d))$' ) OBJECT_NAMES = { "Addresses": "Address", "Attachments": "Attachment", "Accounts": "Account", "BankTransactions": "BankTransaction", "BankTransfers": "BankTransfer", "BrandingThemes": "BrandingTheme", "ContactGroups": "ContactGroup", "ContactPersons": "ContactPerson", "Contacts": "Contact", "CreditNotes": "CreditNote", "Currencies": "Currency", "Employees": "Employee", "ExpenseClaims": "ExpenseClaim", "Invoices": "Invoice", "Items": "Item", "Journals": "Journal", "ManualJournals": "ManualJournal", "Organisation": "Organisation", "Overpayments": "Overpayment", "Payments": "Payment", "PayrollCalendars": "PayrollCalendar", "PayRuns": "PayRun", "Phones": "Phone", "Prepayments": "Prepayment", "Receipts": "Receipt", "RepeatingInvoices": "RepeatingInvoice", "Reports": "Report", "TaxComponents": "TaxComponent", "TaxRates": "TaxRate", "TrackingCategories": "TrackingCategory", "Tracking": "TrackingCategory", "Users": "User", "Associations": "Association", "Files": "File", "Folders": "Folder", "Inbox": "Inbox", "LineItems": "LineItem", "JournalLines": "JournalLine", "PurchaseOrders": "PurchaseOrder", } def isplural(word): return word in OBJECT_NAMES.keys() def singular(word): return OBJECT_NAMES.get(word) def parse_date(string, force_datetime=False): """ Takes a Xero formatted date, e.g. /Date(1426849200000+1300)/""" matches = DATE.match(string) if not matches: return None values = dict([ ( k, v if v[0] in '+-' else int(v) ) for k,v in matches.groupdict().items() if v and int(v) ]) if 'timestamp' in values: value = datetime.datetime.utcfromtimestamp(0) + datetime.timedelta( hours=int(values.get('offset_h', 0)), minutes=int(values.get('offset_m', 0)), seconds=int(values['timestamp']) / 1000.0 ) return value # I've made an assumption here, that a DateTime value will not # ever be YYYY-MM-DDT00:00:00, which is probably bad. I'm not # really sure how to handle this, other than to hard-code the # names of the field that are actually Date rather than DateTime. if len(values) > 3 or force_datetime: return datetime.datetime(**values) # Sometimes Xero returns Date(0+0000), so we end up with no # values. Return None for this case if not values: return None return datetime.date(**values)
freakboy3742/pyxero
xero/basemanager.py
BaseManager._get_data
python
def _get_data(self, func): def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, params, method, body, headers, singleobject = func(*args, **kwargs) if headers is None: headers = {} # Use the JSON API by default, but remember we might request a PDF (application/pdf) # so don't force the Accept header. if 'Accept' not in headers: headers['Accept'] = 'application/json' # Set a user-agent so Xero knows the traffic is coming from pyxero # or individual user/partner headers['User-Agent'] = self.user_agent response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, timeout=timeout) if response.status_code == 200: # If we haven't got XML or JSON, assume we're being returned a binary file if not response.headers['content-type'].startswith('application/json'): return response.content return self._parse_api_response(response, self.name) elif response.status_code == 204: return response.content elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper
This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L165-L232
null
class BaseManager(object): DECORATED_METHODS = ( 'get', 'save', 'filter', 'all', 'put', 'delete', 'get_attachments', 'get_attachment_data', 'put_attachment_data', ) DATETIME_FIELDS = ( 'UpdatedDateUTC', 'Updated', 'FullyPaidOnDate', 'DateTimeUTC', 'CreatedDateUTC' ) DATE_FIELDS = ( 'DueDate', 'Date', 'PaymentDate', 'StartDate', 'EndDate', 'PeriodLockDate', 'DateOfBirth', 'OpeningBalanceDate', 'PaymentDueDate', 'ReportingDate', 'DeliveryDate', 'ExpectedArrivalDate', ) BOOLEAN_FIELDS = ( 'IsSupplier', 'IsCustomer', 'IsDemoCompany', 'PaysTax', 'IsAuthorisedToApproveTimesheets', 'IsAuthorisedToApproveLeave', 'HasHELPDebt', 'AustralianResidentForTaxPurposes', 'TaxFreeThresholdClaimed', 'HasSFSSDebt', 'EligibleToReceiveLeaveLoading', 'IsExemptFromTax', 'IsExemptFromSuper', 'SentToContact', 'IsSubscriber', 'HasAttachments', 'ShowOnCashBasisReports', 'IncludeInEmails', 'SentToContact', 'CanApplyToRevenue', 'IsReconciled', 'EnablePaymentsToAccount', 'ShowInExpenseClaims' ) DECIMAL_FIELDS = ( 'Hours', 'NumberOfUnit', ) INTEGER_FIELDS = ( 'FinancialYearEndDay', 'FinancialYearEndMonth', ) NO_SEND_FIELDS = ( 'UpdatedDateUTC', 'HasValidationErrors', 'IsDiscounted', 'DateString', 'HasErrors', 'DueDateString', ) OPERATOR_MAPPINGS = { 'gt': '>', 'lt': '<', 'lte': '<=', 'gte': '>=', 'ne': '!=' } def __init__(self): pass def dict_to_xml(self, root_elm, data): for key in data.keys(): # Xero will complain if we send back these fields. if key in self.NO_SEND_FIELDS: continue sub_data = data[key] elm = SubElement(root_elm, key) # Key references a dict. Unroll the dict # as it's own XML node with subnodes if isinstance(sub_data, dict): self.dict_to_xml(elm, sub_data) # Key references a list/tuple elif isinstance(sub_data, list) or isinstance(sub_data, tuple): # key name is a plural. This means each item # in the list needs to be wrapped in an XML # node that is a singular version of the list name. if isplural(key): for d in sub_data: self.dict_to_xml(SubElement(elm, singular(key)), d) # key name isn't a plural. Just insert the content # as an XML node with subnodes else: for d in sub_data: self.dict_to_xml(elm, d) # Normal element - just insert the data. else: if key in self.BOOLEAN_FIELDS: val = 'true' if sub_data else 'false' elif key in self.DATE_FIELDS: val = sub_data.strftime('%Y-%m-%dT%H:%M:%S') else: val = six.text_type(sub_data) elm.text = val return root_elm def _prepare_data_for_save(self, data): if isinstance(data, list) or isinstance(data, tuple): root_elm = Element(self.name) for d in data: sub_elm = SubElement(root_elm, self.singular) self.dict_to_xml(sub_elm, d) else: root_elm = self.dict_to_xml(Element(self.singular), data) # In python3 this seems to return a bytestring return six.u(tostring(root_elm)) def _parse_api_response(self, response, resource_name): data = json.loads(response.text, object_hook=json_load_object_hook) assert data['Status'] == 'OK', "Expected the API to say OK but received %s" % data['Status'] try: return data[resource_name] except KeyError: return data def _get(self, id, headers=None, params=None): uri = '/'.join([self.base_url, self.name, id]) uri_params = self.extra_params.copy() uri_params.update(params if params else {}) return uri, uri_params, 'get', None, headers, True def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False def _get_attachment_data(self, id, filename): """ Retrieve the contents of a specific attachment (identified by filename). """ uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) return uri, {}, 'get', None, None, False def get_attachment(self, id, filename, file): """ Retrieve the contents of a specific attachment (identified by filename). Writes data to file object, returns length of data written. """ data = self.get_attachment_data(id, filename) file.write(data) return len(data) def save_or_put(self, data, method='post', headers=None, summarize_errors=True): uri = '/'.join([self.base_url, self.name]) body = {'xml': self._prepare_data_for_save(data)} params = self.extra_params.copy() if not summarize_errors: params['summarizeErrors'] = 'false' return uri, params, method, body, headers, False def _save(self, data): return self.save_or_put(data, method='post') def _put(self, data, summarize_errors=True): return self.save_or_put(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online) def prepare_filtering_date(self, val): if isinstance(val, datetime): val = val.strftime('%a, %d %b %Y %H:%M:%S GMT') else: val = '"%s"' % val return {'If-Modified-Since': val} def _filter(self, **kwargs): params = self.extra_params.copy() headers = None uri = '/'.join([self.base_url, self.name]) if kwargs: if 'since' in kwargs: val = kwargs['since'] headers = self.prepare_filtering_date(val) del kwargs['since'] def get_filter_params(key, value): last_key = key.split('_')[-1] if last_key.upper().endswith('ID'): return 'Guid("%s")' % six.text_type(value) if key in self.BOOLEAN_FIELDS: return 'true' if value else 'false' elif key in self.DATE_FIELDS: return 'DateTime(%s,%s,%s)' % (value.year, value.month, value.day) elif key in self.DATETIME_FIELDS: return value.isoformat() else: return '"%s"' % six.text_type(value) def generate_param(key, value): parts = key.split("__") field = key.replace('_', '.') fmt = '%s==%s' if len(parts) == 2: # support filters: # Name__Contains=John becomes Name.Contains("John") if parts[1] in ["contains", "startswith", "endswith"]: field = parts[0] fmt = ''.join(['%s.', parts[1], '(%s)']) elif parts[1] in self.OPERATOR_MAPPINGS: field = parts[0] key = field fmt = '%s' + self.OPERATOR_MAPPINGS[parts[1]] + '%s' elif parts[1] in ["isnull"]: sign = '=' if value else '!' return '%s%s=null' % (parts[0], sign) field = field.replace('_', '.') return fmt % ( field, get_filter_params(key, value) ) # Move any known parameter names to the query string KNOWN_PARAMETERS = ['order', 'offset', 'page', 'includeArchived'] for param in KNOWN_PARAMETERS: if param in kwargs: params[param] = kwargs.pop(param) filter_params = [] if 'raw' in kwargs: raw = kwargs.pop('raw') filter_params.append(raw) # Treat any remaining arguments as filter predicates # Xero will break if you search without a check for null in the first position: # http://developer.xero.com/documentation/getting-started/http-requests-and-responses/#title3 sortedkwargs = sorted(six.iteritems(kwargs), key=lambda item: -1 if 'isnull' in item[0] else 0) for key, value in sortedkwargs: filter_params.append(generate_param(key, value)) if filter_params: params['where'] = '&&'.join(filter_params) return uri, params, 'get', None, headers, False def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False
freakboy3742/pyxero
xero/basemanager.py
BaseManager._get_attachments
python
def _get_attachments(self, id): uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False
Retrieve a list of attachments associated with this Xero object.
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L240-L243
null
class BaseManager(object): DECORATED_METHODS = ( 'get', 'save', 'filter', 'all', 'put', 'delete', 'get_attachments', 'get_attachment_data', 'put_attachment_data', ) DATETIME_FIELDS = ( 'UpdatedDateUTC', 'Updated', 'FullyPaidOnDate', 'DateTimeUTC', 'CreatedDateUTC' ) DATE_FIELDS = ( 'DueDate', 'Date', 'PaymentDate', 'StartDate', 'EndDate', 'PeriodLockDate', 'DateOfBirth', 'OpeningBalanceDate', 'PaymentDueDate', 'ReportingDate', 'DeliveryDate', 'ExpectedArrivalDate', ) BOOLEAN_FIELDS = ( 'IsSupplier', 'IsCustomer', 'IsDemoCompany', 'PaysTax', 'IsAuthorisedToApproveTimesheets', 'IsAuthorisedToApproveLeave', 'HasHELPDebt', 'AustralianResidentForTaxPurposes', 'TaxFreeThresholdClaimed', 'HasSFSSDebt', 'EligibleToReceiveLeaveLoading', 'IsExemptFromTax', 'IsExemptFromSuper', 'SentToContact', 'IsSubscriber', 'HasAttachments', 'ShowOnCashBasisReports', 'IncludeInEmails', 'SentToContact', 'CanApplyToRevenue', 'IsReconciled', 'EnablePaymentsToAccount', 'ShowInExpenseClaims' ) DECIMAL_FIELDS = ( 'Hours', 'NumberOfUnit', ) INTEGER_FIELDS = ( 'FinancialYearEndDay', 'FinancialYearEndMonth', ) NO_SEND_FIELDS = ( 'UpdatedDateUTC', 'HasValidationErrors', 'IsDiscounted', 'DateString', 'HasErrors', 'DueDateString', ) OPERATOR_MAPPINGS = { 'gt': '>', 'lt': '<', 'lte': '<=', 'gte': '>=', 'ne': '!=' } def __init__(self): pass def dict_to_xml(self, root_elm, data): for key in data.keys(): # Xero will complain if we send back these fields. if key in self.NO_SEND_FIELDS: continue sub_data = data[key] elm = SubElement(root_elm, key) # Key references a dict. Unroll the dict # as it's own XML node with subnodes if isinstance(sub_data, dict): self.dict_to_xml(elm, sub_data) # Key references a list/tuple elif isinstance(sub_data, list) or isinstance(sub_data, tuple): # key name is a plural. This means each item # in the list needs to be wrapped in an XML # node that is a singular version of the list name. if isplural(key): for d in sub_data: self.dict_to_xml(SubElement(elm, singular(key)), d) # key name isn't a plural. Just insert the content # as an XML node with subnodes else: for d in sub_data: self.dict_to_xml(elm, d) # Normal element - just insert the data. else: if key in self.BOOLEAN_FIELDS: val = 'true' if sub_data else 'false' elif key in self.DATE_FIELDS: val = sub_data.strftime('%Y-%m-%dT%H:%M:%S') else: val = six.text_type(sub_data) elm.text = val return root_elm def _prepare_data_for_save(self, data): if isinstance(data, list) or isinstance(data, tuple): root_elm = Element(self.name) for d in data: sub_elm = SubElement(root_elm, self.singular) self.dict_to_xml(sub_elm, d) else: root_elm = self.dict_to_xml(Element(self.singular), data) # In python3 this seems to return a bytestring return six.u(tostring(root_elm)) def _parse_api_response(self, response, resource_name): data = json.loads(response.text, object_hook=json_load_object_hook) assert data['Status'] == 'OK', "Expected the API to say OK but received %s" % data['Status'] try: return data[resource_name] except KeyError: return data def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, params, method, body, headers, singleobject = func(*args, **kwargs) if headers is None: headers = {} # Use the JSON API by default, but remember we might request a PDF (application/pdf) # so don't force the Accept header. if 'Accept' not in headers: headers['Accept'] = 'application/json' # Set a user-agent so Xero knows the traffic is coming from pyxero # or individual user/partner headers['User-Agent'] = self.user_agent response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, timeout=timeout) if response.status_code == 200: # If we haven't got XML or JSON, assume we're being returned a binary file if not response.headers['content-type'].startswith('application/json'): return response.content return self._parse_api_response(response, self.name) elif response.status_code == 204: return response.content elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper def _get(self, id, headers=None, params=None): uri = '/'.join([self.base_url, self.name, id]) uri_params = self.extra_params.copy() uri_params.update(params if params else {}) return uri, uri_params, 'get', None, headers, True def _get_attachment_data(self, id, filename): """ Retrieve the contents of a specific attachment (identified by filename). """ uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) return uri, {}, 'get', None, None, False def get_attachment(self, id, filename, file): """ Retrieve the contents of a specific attachment (identified by filename). Writes data to file object, returns length of data written. """ data = self.get_attachment_data(id, filename) file.write(data) return len(data) def save_or_put(self, data, method='post', headers=None, summarize_errors=True): uri = '/'.join([self.base_url, self.name]) body = {'xml': self._prepare_data_for_save(data)} params = self.extra_params.copy() if not summarize_errors: params['summarizeErrors'] = 'false' return uri, params, method, body, headers, False def _save(self, data): return self.save_or_put(data, method='post') def _put(self, data, summarize_errors=True): return self.save_or_put(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online) def prepare_filtering_date(self, val): if isinstance(val, datetime): val = val.strftime('%a, %d %b %Y %H:%M:%S GMT') else: val = '"%s"' % val return {'If-Modified-Since': val} def _filter(self, **kwargs): params = self.extra_params.copy() headers = None uri = '/'.join([self.base_url, self.name]) if kwargs: if 'since' in kwargs: val = kwargs['since'] headers = self.prepare_filtering_date(val) del kwargs['since'] def get_filter_params(key, value): last_key = key.split('_')[-1] if last_key.upper().endswith('ID'): return 'Guid("%s")' % six.text_type(value) if key in self.BOOLEAN_FIELDS: return 'true' if value else 'false' elif key in self.DATE_FIELDS: return 'DateTime(%s,%s,%s)' % (value.year, value.month, value.day) elif key in self.DATETIME_FIELDS: return value.isoformat() else: return '"%s"' % six.text_type(value) def generate_param(key, value): parts = key.split("__") field = key.replace('_', '.') fmt = '%s==%s' if len(parts) == 2: # support filters: # Name__Contains=John becomes Name.Contains("John") if parts[1] in ["contains", "startswith", "endswith"]: field = parts[0] fmt = ''.join(['%s.', parts[1], '(%s)']) elif parts[1] in self.OPERATOR_MAPPINGS: field = parts[0] key = field fmt = '%s' + self.OPERATOR_MAPPINGS[parts[1]] + '%s' elif parts[1] in ["isnull"]: sign = '=' if value else '!' return '%s%s=null' % (parts[0], sign) field = field.replace('_', '.') return fmt % ( field, get_filter_params(key, value) ) # Move any known parameter names to the query string KNOWN_PARAMETERS = ['order', 'offset', 'page', 'includeArchived'] for param in KNOWN_PARAMETERS: if param in kwargs: params[param] = kwargs.pop(param) filter_params = [] if 'raw' in kwargs: raw = kwargs.pop('raw') filter_params.append(raw) # Treat any remaining arguments as filter predicates # Xero will break if you search without a check for null in the first position: # http://developer.xero.com/documentation/getting-started/http-requests-and-responses/#title3 sortedkwargs = sorted(six.iteritems(kwargs), key=lambda item: -1 if 'isnull' in item[0] else 0) for key, value in sortedkwargs: filter_params.append(generate_param(key, value)) if filter_params: params['where'] = '&&'.join(filter_params) return uri, params, 'get', None, headers, False def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False
freakboy3742/pyxero
xero/basemanager.py
BaseManager._get_attachment_data
python
def _get_attachment_data(self, id, filename): uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) return uri, {}, 'get', None, None, False
Retrieve the contents of a specific attachment (identified by filename).
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L245-L250
null
class BaseManager(object): DECORATED_METHODS = ( 'get', 'save', 'filter', 'all', 'put', 'delete', 'get_attachments', 'get_attachment_data', 'put_attachment_data', ) DATETIME_FIELDS = ( 'UpdatedDateUTC', 'Updated', 'FullyPaidOnDate', 'DateTimeUTC', 'CreatedDateUTC' ) DATE_FIELDS = ( 'DueDate', 'Date', 'PaymentDate', 'StartDate', 'EndDate', 'PeriodLockDate', 'DateOfBirth', 'OpeningBalanceDate', 'PaymentDueDate', 'ReportingDate', 'DeliveryDate', 'ExpectedArrivalDate', ) BOOLEAN_FIELDS = ( 'IsSupplier', 'IsCustomer', 'IsDemoCompany', 'PaysTax', 'IsAuthorisedToApproveTimesheets', 'IsAuthorisedToApproveLeave', 'HasHELPDebt', 'AustralianResidentForTaxPurposes', 'TaxFreeThresholdClaimed', 'HasSFSSDebt', 'EligibleToReceiveLeaveLoading', 'IsExemptFromTax', 'IsExemptFromSuper', 'SentToContact', 'IsSubscriber', 'HasAttachments', 'ShowOnCashBasisReports', 'IncludeInEmails', 'SentToContact', 'CanApplyToRevenue', 'IsReconciled', 'EnablePaymentsToAccount', 'ShowInExpenseClaims' ) DECIMAL_FIELDS = ( 'Hours', 'NumberOfUnit', ) INTEGER_FIELDS = ( 'FinancialYearEndDay', 'FinancialYearEndMonth', ) NO_SEND_FIELDS = ( 'UpdatedDateUTC', 'HasValidationErrors', 'IsDiscounted', 'DateString', 'HasErrors', 'DueDateString', ) OPERATOR_MAPPINGS = { 'gt': '>', 'lt': '<', 'lte': '<=', 'gte': '>=', 'ne': '!=' } def __init__(self): pass def dict_to_xml(self, root_elm, data): for key in data.keys(): # Xero will complain if we send back these fields. if key in self.NO_SEND_FIELDS: continue sub_data = data[key] elm = SubElement(root_elm, key) # Key references a dict. Unroll the dict # as it's own XML node with subnodes if isinstance(sub_data, dict): self.dict_to_xml(elm, sub_data) # Key references a list/tuple elif isinstance(sub_data, list) or isinstance(sub_data, tuple): # key name is a plural. This means each item # in the list needs to be wrapped in an XML # node that is a singular version of the list name. if isplural(key): for d in sub_data: self.dict_to_xml(SubElement(elm, singular(key)), d) # key name isn't a plural. Just insert the content # as an XML node with subnodes else: for d in sub_data: self.dict_to_xml(elm, d) # Normal element - just insert the data. else: if key in self.BOOLEAN_FIELDS: val = 'true' if sub_data else 'false' elif key in self.DATE_FIELDS: val = sub_data.strftime('%Y-%m-%dT%H:%M:%S') else: val = six.text_type(sub_data) elm.text = val return root_elm def _prepare_data_for_save(self, data): if isinstance(data, list) or isinstance(data, tuple): root_elm = Element(self.name) for d in data: sub_elm = SubElement(root_elm, self.singular) self.dict_to_xml(sub_elm, d) else: root_elm = self.dict_to_xml(Element(self.singular), data) # In python3 this seems to return a bytestring return six.u(tostring(root_elm)) def _parse_api_response(self, response, resource_name): data = json.loads(response.text, object_hook=json_load_object_hook) assert data['Status'] == 'OK', "Expected the API to say OK but received %s" % data['Status'] try: return data[resource_name] except KeyError: return data def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, params, method, body, headers, singleobject = func(*args, **kwargs) if headers is None: headers = {} # Use the JSON API by default, but remember we might request a PDF (application/pdf) # so don't force the Accept header. if 'Accept' not in headers: headers['Accept'] = 'application/json' # Set a user-agent so Xero knows the traffic is coming from pyxero # or individual user/partner headers['User-Agent'] = self.user_agent response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, timeout=timeout) if response.status_code == 200: # If we haven't got XML or JSON, assume we're being returned a binary file if not response.headers['content-type'].startswith('application/json'): return response.content return self._parse_api_response(response, self.name) elif response.status_code == 204: return response.content elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper def _get(self, id, headers=None, params=None): uri = '/'.join([self.base_url, self.name, id]) uri_params = self.extra_params.copy() uri_params.update(params if params else {}) return uri, uri_params, 'get', None, headers, True def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False def get_attachment(self, id, filename, file): """ Retrieve the contents of a specific attachment (identified by filename). Writes data to file object, returns length of data written. """ data = self.get_attachment_data(id, filename) file.write(data) return len(data) def save_or_put(self, data, method='post', headers=None, summarize_errors=True): uri = '/'.join([self.base_url, self.name]) body = {'xml': self._prepare_data_for_save(data)} params = self.extra_params.copy() if not summarize_errors: params['summarizeErrors'] = 'false' return uri, params, method, body, headers, False def _save(self, data): return self.save_or_put(data, method='post') def _put(self, data, summarize_errors=True): return self.save_or_put(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online) def prepare_filtering_date(self, val): if isinstance(val, datetime): val = val.strftime('%a, %d %b %Y %H:%M:%S GMT') else: val = '"%s"' % val return {'If-Modified-Since': val} def _filter(self, **kwargs): params = self.extra_params.copy() headers = None uri = '/'.join([self.base_url, self.name]) if kwargs: if 'since' in kwargs: val = kwargs['since'] headers = self.prepare_filtering_date(val) del kwargs['since'] def get_filter_params(key, value): last_key = key.split('_')[-1] if last_key.upper().endswith('ID'): return 'Guid("%s")' % six.text_type(value) if key in self.BOOLEAN_FIELDS: return 'true' if value else 'false' elif key in self.DATE_FIELDS: return 'DateTime(%s,%s,%s)' % (value.year, value.month, value.day) elif key in self.DATETIME_FIELDS: return value.isoformat() else: return '"%s"' % six.text_type(value) def generate_param(key, value): parts = key.split("__") field = key.replace('_', '.') fmt = '%s==%s' if len(parts) == 2: # support filters: # Name__Contains=John becomes Name.Contains("John") if parts[1] in ["contains", "startswith", "endswith"]: field = parts[0] fmt = ''.join(['%s.', parts[1], '(%s)']) elif parts[1] in self.OPERATOR_MAPPINGS: field = parts[0] key = field fmt = '%s' + self.OPERATOR_MAPPINGS[parts[1]] + '%s' elif parts[1] in ["isnull"]: sign = '=' if value else '!' return '%s%s=null' % (parts[0], sign) field = field.replace('_', '.') return fmt % ( field, get_filter_params(key, value) ) # Move any known parameter names to the query string KNOWN_PARAMETERS = ['order', 'offset', 'page', 'includeArchived'] for param in KNOWN_PARAMETERS: if param in kwargs: params[param] = kwargs.pop(param) filter_params = [] if 'raw' in kwargs: raw = kwargs.pop('raw') filter_params.append(raw) # Treat any remaining arguments as filter predicates # Xero will break if you search without a check for null in the first position: # http://developer.xero.com/documentation/getting-started/http-requests-and-responses/#title3 sortedkwargs = sorted(six.iteritems(kwargs), key=lambda item: -1 if 'isnull' in item[0] else 0) for key, value in sortedkwargs: filter_params.append(generate_param(key, value)) if filter_params: params['where'] = '&&'.join(filter_params) return uri, params, 'get', None, headers, False def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False
freakboy3742/pyxero
xero/basemanager.py
BaseManager.get_attachment
python
def get_attachment(self, id, filename, file): data = self.get_attachment_data(id, filename) file.write(data) return len(data)
Retrieve the contents of a specific attachment (identified by filename). Writes data to file object, returns length of data written.
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L252-L260
null
class BaseManager(object): DECORATED_METHODS = ( 'get', 'save', 'filter', 'all', 'put', 'delete', 'get_attachments', 'get_attachment_data', 'put_attachment_data', ) DATETIME_FIELDS = ( 'UpdatedDateUTC', 'Updated', 'FullyPaidOnDate', 'DateTimeUTC', 'CreatedDateUTC' ) DATE_FIELDS = ( 'DueDate', 'Date', 'PaymentDate', 'StartDate', 'EndDate', 'PeriodLockDate', 'DateOfBirth', 'OpeningBalanceDate', 'PaymentDueDate', 'ReportingDate', 'DeliveryDate', 'ExpectedArrivalDate', ) BOOLEAN_FIELDS = ( 'IsSupplier', 'IsCustomer', 'IsDemoCompany', 'PaysTax', 'IsAuthorisedToApproveTimesheets', 'IsAuthorisedToApproveLeave', 'HasHELPDebt', 'AustralianResidentForTaxPurposes', 'TaxFreeThresholdClaimed', 'HasSFSSDebt', 'EligibleToReceiveLeaveLoading', 'IsExemptFromTax', 'IsExemptFromSuper', 'SentToContact', 'IsSubscriber', 'HasAttachments', 'ShowOnCashBasisReports', 'IncludeInEmails', 'SentToContact', 'CanApplyToRevenue', 'IsReconciled', 'EnablePaymentsToAccount', 'ShowInExpenseClaims' ) DECIMAL_FIELDS = ( 'Hours', 'NumberOfUnit', ) INTEGER_FIELDS = ( 'FinancialYearEndDay', 'FinancialYearEndMonth', ) NO_SEND_FIELDS = ( 'UpdatedDateUTC', 'HasValidationErrors', 'IsDiscounted', 'DateString', 'HasErrors', 'DueDateString', ) OPERATOR_MAPPINGS = { 'gt': '>', 'lt': '<', 'lte': '<=', 'gte': '>=', 'ne': '!=' } def __init__(self): pass def dict_to_xml(self, root_elm, data): for key in data.keys(): # Xero will complain if we send back these fields. if key in self.NO_SEND_FIELDS: continue sub_data = data[key] elm = SubElement(root_elm, key) # Key references a dict. Unroll the dict # as it's own XML node with subnodes if isinstance(sub_data, dict): self.dict_to_xml(elm, sub_data) # Key references a list/tuple elif isinstance(sub_data, list) or isinstance(sub_data, tuple): # key name is a plural. This means each item # in the list needs to be wrapped in an XML # node that is a singular version of the list name. if isplural(key): for d in sub_data: self.dict_to_xml(SubElement(elm, singular(key)), d) # key name isn't a plural. Just insert the content # as an XML node with subnodes else: for d in sub_data: self.dict_to_xml(elm, d) # Normal element - just insert the data. else: if key in self.BOOLEAN_FIELDS: val = 'true' if sub_data else 'false' elif key in self.DATE_FIELDS: val = sub_data.strftime('%Y-%m-%dT%H:%M:%S') else: val = six.text_type(sub_data) elm.text = val return root_elm def _prepare_data_for_save(self, data): if isinstance(data, list) or isinstance(data, tuple): root_elm = Element(self.name) for d in data: sub_elm = SubElement(root_elm, self.singular) self.dict_to_xml(sub_elm, d) else: root_elm = self.dict_to_xml(Element(self.singular), data) # In python3 this seems to return a bytestring return six.u(tostring(root_elm)) def _parse_api_response(self, response, resource_name): data = json.loads(response.text, object_hook=json_load_object_hook) assert data['Status'] == 'OK', "Expected the API to say OK but received %s" % data['Status'] try: return data[resource_name] except KeyError: return data def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, params, method, body, headers, singleobject = func(*args, **kwargs) if headers is None: headers = {} # Use the JSON API by default, but remember we might request a PDF (application/pdf) # so don't force the Accept header. if 'Accept' not in headers: headers['Accept'] = 'application/json' # Set a user-agent so Xero knows the traffic is coming from pyxero # or individual user/partner headers['User-Agent'] = self.user_agent response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, timeout=timeout) if response.status_code == 200: # If we haven't got XML or JSON, assume we're being returned a binary file if not response.headers['content-type'].startswith('application/json'): return response.content return self._parse_api_response(response, self.name) elif response.status_code == 204: return response.content elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper def _get(self, id, headers=None, params=None): uri = '/'.join([self.base_url, self.name, id]) uri_params = self.extra_params.copy() uri_params.update(params if params else {}) return uri, uri_params, 'get', None, headers, True def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False def _get_attachment_data(self, id, filename): """ Retrieve the contents of a specific attachment (identified by filename). """ uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) return uri, {}, 'get', None, None, False def save_or_put(self, data, method='post', headers=None, summarize_errors=True): uri = '/'.join([self.base_url, self.name]) body = {'xml': self._prepare_data_for_save(data)} params = self.extra_params.copy() if not summarize_errors: params['summarizeErrors'] = 'false' return uri, params, method, body, headers, False def _save(self, data): return self.save_or_put(data, method='post') def _put(self, data, summarize_errors=True): return self.save_or_put(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online) def prepare_filtering_date(self, val): if isinstance(val, datetime): val = val.strftime('%a, %d %b %Y %H:%M:%S GMT') else: val = '"%s"' % val return {'If-Modified-Since': val} def _filter(self, **kwargs): params = self.extra_params.copy() headers = None uri = '/'.join([self.base_url, self.name]) if kwargs: if 'since' in kwargs: val = kwargs['since'] headers = self.prepare_filtering_date(val) del kwargs['since'] def get_filter_params(key, value): last_key = key.split('_')[-1] if last_key.upper().endswith('ID'): return 'Guid("%s")' % six.text_type(value) if key in self.BOOLEAN_FIELDS: return 'true' if value else 'false' elif key in self.DATE_FIELDS: return 'DateTime(%s,%s,%s)' % (value.year, value.month, value.day) elif key in self.DATETIME_FIELDS: return value.isoformat() else: return '"%s"' % six.text_type(value) def generate_param(key, value): parts = key.split("__") field = key.replace('_', '.') fmt = '%s==%s' if len(parts) == 2: # support filters: # Name__Contains=John becomes Name.Contains("John") if parts[1] in ["contains", "startswith", "endswith"]: field = parts[0] fmt = ''.join(['%s.', parts[1], '(%s)']) elif parts[1] in self.OPERATOR_MAPPINGS: field = parts[0] key = field fmt = '%s' + self.OPERATOR_MAPPINGS[parts[1]] + '%s' elif parts[1] in ["isnull"]: sign = '=' if value else '!' return '%s%s=null' % (parts[0], sign) field = field.replace('_', '.') return fmt % ( field, get_filter_params(key, value) ) # Move any known parameter names to the query string KNOWN_PARAMETERS = ['order', 'offset', 'page', 'includeArchived'] for param in KNOWN_PARAMETERS: if param in kwargs: params[param] = kwargs.pop(param) filter_params = [] if 'raw' in kwargs: raw = kwargs.pop('raw') filter_params.append(raw) # Treat any remaining arguments as filter predicates # Xero will break if you search without a check for null in the first position: # http://developer.xero.com/documentation/getting-started/http-requests-and-responses/#title3 sortedkwargs = sorted(six.iteritems(kwargs), key=lambda item: -1 if 'isnull' in item[0] else 0) for key, value in sortedkwargs: filter_params.append(generate_param(key, value)) if filter_params: params['where'] = '&&'.join(filter_params) return uri, params, 'get', None, headers, False def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False
freakboy3742/pyxero
xero/basemanager.py
BaseManager._put_attachment_data
python
def _put_attachment_data(self, id, filename, data, content_type, include_online=False): uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False
Upload an attachment to the Xero object.
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L280-L285
null
class BaseManager(object): DECORATED_METHODS = ( 'get', 'save', 'filter', 'all', 'put', 'delete', 'get_attachments', 'get_attachment_data', 'put_attachment_data', ) DATETIME_FIELDS = ( 'UpdatedDateUTC', 'Updated', 'FullyPaidOnDate', 'DateTimeUTC', 'CreatedDateUTC' ) DATE_FIELDS = ( 'DueDate', 'Date', 'PaymentDate', 'StartDate', 'EndDate', 'PeriodLockDate', 'DateOfBirth', 'OpeningBalanceDate', 'PaymentDueDate', 'ReportingDate', 'DeliveryDate', 'ExpectedArrivalDate', ) BOOLEAN_FIELDS = ( 'IsSupplier', 'IsCustomer', 'IsDemoCompany', 'PaysTax', 'IsAuthorisedToApproveTimesheets', 'IsAuthorisedToApproveLeave', 'HasHELPDebt', 'AustralianResidentForTaxPurposes', 'TaxFreeThresholdClaimed', 'HasSFSSDebt', 'EligibleToReceiveLeaveLoading', 'IsExemptFromTax', 'IsExemptFromSuper', 'SentToContact', 'IsSubscriber', 'HasAttachments', 'ShowOnCashBasisReports', 'IncludeInEmails', 'SentToContact', 'CanApplyToRevenue', 'IsReconciled', 'EnablePaymentsToAccount', 'ShowInExpenseClaims' ) DECIMAL_FIELDS = ( 'Hours', 'NumberOfUnit', ) INTEGER_FIELDS = ( 'FinancialYearEndDay', 'FinancialYearEndMonth', ) NO_SEND_FIELDS = ( 'UpdatedDateUTC', 'HasValidationErrors', 'IsDiscounted', 'DateString', 'HasErrors', 'DueDateString', ) OPERATOR_MAPPINGS = { 'gt': '>', 'lt': '<', 'lte': '<=', 'gte': '>=', 'ne': '!=' } def __init__(self): pass def dict_to_xml(self, root_elm, data): for key in data.keys(): # Xero will complain if we send back these fields. if key in self.NO_SEND_FIELDS: continue sub_data = data[key] elm = SubElement(root_elm, key) # Key references a dict. Unroll the dict # as it's own XML node with subnodes if isinstance(sub_data, dict): self.dict_to_xml(elm, sub_data) # Key references a list/tuple elif isinstance(sub_data, list) or isinstance(sub_data, tuple): # key name is a plural. This means each item # in the list needs to be wrapped in an XML # node that is a singular version of the list name. if isplural(key): for d in sub_data: self.dict_to_xml(SubElement(elm, singular(key)), d) # key name isn't a plural. Just insert the content # as an XML node with subnodes else: for d in sub_data: self.dict_to_xml(elm, d) # Normal element - just insert the data. else: if key in self.BOOLEAN_FIELDS: val = 'true' if sub_data else 'false' elif key in self.DATE_FIELDS: val = sub_data.strftime('%Y-%m-%dT%H:%M:%S') else: val = six.text_type(sub_data) elm.text = val return root_elm def _prepare_data_for_save(self, data): if isinstance(data, list) or isinstance(data, tuple): root_elm = Element(self.name) for d in data: sub_elm = SubElement(root_elm, self.singular) self.dict_to_xml(sub_elm, d) else: root_elm = self.dict_to_xml(Element(self.singular), data) # In python3 this seems to return a bytestring return six.u(tostring(root_elm)) def _parse_api_response(self, response, resource_name): data = json.loads(response.text, object_hook=json_load_object_hook) assert data['Status'] == 'OK', "Expected the API to say OK but received %s" % data['Status'] try: return data[resource_name] except KeyError: return data def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, params, method, body, headers, singleobject = func(*args, **kwargs) if headers is None: headers = {} # Use the JSON API by default, but remember we might request a PDF (application/pdf) # so don't force the Accept header. if 'Accept' not in headers: headers['Accept'] = 'application/json' # Set a user-agent so Xero knows the traffic is coming from pyxero # or individual user/partner headers['User-Agent'] = self.user_agent response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, timeout=timeout) if response.status_code == 200: # If we haven't got XML or JSON, assume we're being returned a binary file if not response.headers['content-type'].startswith('application/json'): return response.content return self._parse_api_response(response, self.name) elif response.status_code == 204: return response.content elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper def _get(self, id, headers=None, params=None): uri = '/'.join([self.base_url, self.name, id]) uri_params = self.extra_params.copy() uri_params.update(params if params else {}) return uri, uri_params, 'get', None, headers, True def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False def _get_attachment_data(self, id, filename): """ Retrieve the contents of a specific attachment (identified by filename). """ uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) return uri, {}, 'get', None, None, False def get_attachment(self, id, filename, file): """ Retrieve the contents of a specific attachment (identified by filename). Writes data to file object, returns length of data written. """ data = self.get_attachment_data(id, filename) file.write(data) return len(data) def save_or_put(self, data, method='post', headers=None, summarize_errors=True): uri = '/'.join([self.base_url, self.name]) body = {'xml': self._prepare_data_for_save(data)} params = self.extra_params.copy() if not summarize_errors: params['summarizeErrors'] = 'false' return uri, params, method, body, headers, False def _save(self, data): return self.save_or_put(data, method='post') def _put(self, data, summarize_errors=True): return self.save_or_put(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online) def prepare_filtering_date(self, val): if isinstance(val, datetime): val = val.strftime('%a, %d %b %Y %H:%M:%S GMT') else: val = '"%s"' % val return {'If-Modified-Since': val} def _filter(self, **kwargs): params = self.extra_params.copy() headers = None uri = '/'.join([self.base_url, self.name]) if kwargs: if 'since' in kwargs: val = kwargs['since'] headers = self.prepare_filtering_date(val) del kwargs['since'] def get_filter_params(key, value): last_key = key.split('_')[-1] if last_key.upper().endswith('ID'): return 'Guid("%s")' % six.text_type(value) if key in self.BOOLEAN_FIELDS: return 'true' if value else 'false' elif key in self.DATE_FIELDS: return 'DateTime(%s,%s,%s)' % (value.year, value.month, value.day) elif key in self.DATETIME_FIELDS: return value.isoformat() else: return '"%s"' % six.text_type(value) def generate_param(key, value): parts = key.split("__") field = key.replace('_', '.') fmt = '%s==%s' if len(parts) == 2: # support filters: # Name__Contains=John becomes Name.Contains("John") if parts[1] in ["contains", "startswith", "endswith"]: field = parts[0] fmt = ''.join(['%s.', parts[1], '(%s)']) elif parts[1] in self.OPERATOR_MAPPINGS: field = parts[0] key = field fmt = '%s' + self.OPERATOR_MAPPINGS[parts[1]] + '%s' elif parts[1] in ["isnull"]: sign = '=' if value else '!' return '%s%s=null' % (parts[0], sign) field = field.replace('_', '.') return fmt % ( field, get_filter_params(key, value) ) # Move any known parameter names to the query string KNOWN_PARAMETERS = ['order', 'offset', 'page', 'includeArchived'] for param in KNOWN_PARAMETERS: if param in kwargs: params[param] = kwargs.pop(param) filter_params = [] if 'raw' in kwargs: raw = kwargs.pop('raw') filter_params.append(raw) # Treat any remaining arguments as filter predicates # Xero will break if you search without a check for null in the first position: # http://developer.xero.com/documentation/getting-started/http-requests-and-responses/#title3 sortedkwargs = sorted(six.iteritems(kwargs), key=lambda item: -1 if 'isnull' in item[0] else 0) for key, value in sortedkwargs: filter_params.append(generate_param(key, value)) if filter_params: params['where'] = '&&'.join(filter_params) return uri, params, 'get', None, headers, False def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False
freakboy3742/pyxero
xero/basemanager.py
BaseManager.put_attachment
python
def put_attachment(self, id, filename, file, content_type, include_online=False): return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online)
Upload an attachment to the Xero object (from file object).
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L287-L289
null
class BaseManager(object): DECORATED_METHODS = ( 'get', 'save', 'filter', 'all', 'put', 'delete', 'get_attachments', 'get_attachment_data', 'put_attachment_data', ) DATETIME_FIELDS = ( 'UpdatedDateUTC', 'Updated', 'FullyPaidOnDate', 'DateTimeUTC', 'CreatedDateUTC' ) DATE_FIELDS = ( 'DueDate', 'Date', 'PaymentDate', 'StartDate', 'EndDate', 'PeriodLockDate', 'DateOfBirth', 'OpeningBalanceDate', 'PaymentDueDate', 'ReportingDate', 'DeliveryDate', 'ExpectedArrivalDate', ) BOOLEAN_FIELDS = ( 'IsSupplier', 'IsCustomer', 'IsDemoCompany', 'PaysTax', 'IsAuthorisedToApproveTimesheets', 'IsAuthorisedToApproveLeave', 'HasHELPDebt', 'AustralianResidentForTaxPurposes', 'TaxFreeThresholdClaimed', 'HasSFSSDebt', 'EligibleToReceiveLeaveLoading', 'IsExemptFromTax', 'IsExemptFromSuper', 'SentToContact', 'IsSubscriber', 'HasAttachments', 'ShowOnCashBasisReports', 'IncludeInEmails', 'SentToContact', 'CanApplyToRevenue', 'IsReconciled', 'EnablePaymentsToAccount', 'ShowInExpenseClaims' ) DECIMAL_FIELDS = ( 'Hours', 'NumberOfUnit', ) INTEGER_FIELDS = ( 'FinancialYearEndDay', 'FinancialYearEndMonth', ) NO_SEND_FIELDS = ( 'UpdatedDateUTC', 'HasValidationErrors', 'IsDiscounted', 'DateString', 'HasErrors', 'DueDateString', ) OPERATOR_MAPPINGS = { 'gt': '>', 'lt': '<', 'lte': '<=', 'gte': '>=', 'ne': '!=' } def __init__(self): pass def dict_to_xml(self, root_elm, data): for key in data.keys(): # Xero will complain if we send back these fields. if key in self.NO_SEND_FIELDS: continue sub_data = data[key] elm = SubElement(root_elm, key) # Key references a dict. Unroll the dict # as it's own XML node with subnodes if isinstance(sub_data, dict): self.dict_to_xml(elm, sub_data) # Key references a list/tuple elif isinstance(sub_data, list) or isinstance(sub_data, tuple): # key name is a plural. This means each item # in the list needs to be wrapped in an XML # node that is a singular version of the list name. if isplural(key): for d in sub_data: self.dict_to_xml(SubElement(elm, singular(key)), d) # key name isn't a plural. Just insert the content # as an XML node with subnodes else: for d in sub_data: self.dict_to_xml(elm, d) # Normal element - just insert the data. else: if key in self.BOOLEAN_FIELDS: val = 'true' if sub_data else 'false' elif key in self.DATE_FIELDS: val = sub_data.strftime('%Y-%m-%dT%H:%M:%S') else: val = six.text_type(sub_data) elm.text = val return root_elm def _prepare_data_for_save(self, data): if isinstance(data, list) or isinstance(data, tuple): root_elm = Element(self.name) for d in data: sub_elm = SubElement(root_elm, self.singular) self.dict_to_xml(sub_elm, d) else: root_elm = self.dict_to_xml(Element(self.singular), data) # In python3 this seems to return a bytestring return six.u(tostring(root_elm)) def _parse_api_response(self, response, resource_name): data = json.loads(response.text, object_hook=json_load_object_hook) assert data['Status'] == 'OK', "Expected the API to say OK but received %s" % data['Status'] try: return data[resource_name] except KeyError: return data def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, params, method, body, headers, singleobject = func(*args, **kwargs) if headers is None: headers = {} # Use the JSON API by default, but remember we might request a PDF (application/pdf) # so don't force the Accept header. if 'Accept' not in headers: headers['Accept'] = 'application/json' # Set a user-agent so Xero knows the traffic is coming from pyxero # or individual user/partner headers['User-Agent'] = self.user_agent response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, timeout=timeout) if response.status_code == 200: # If we haven't got XML or JSON, assume we're being returned a binary file if not response.headers['content-type'].startswith('application/json'): return response.content return self._parse_api_response(response, self.name) elif response.status_code == 204: return response.content elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper def _get(self, id, headers=None, params=None): uri = '/'.join([self.base_url, self.name, id]) uri_params = self.extra_params.copy() uri_params.update(params if params else {}) return uri, uri_params, 'get', None, headers, True def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False def _get_attachment_data(self, id, filename): """ Retrieve the contents of a specific attachment (identified by filename). """ uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) return uri, {}, 'get', None, None, False def get_attachment(self, id, filename, file): """ Retrieve the contents of a specific attachment (identified by filename). Writes data to file object, returns length of data written. """ data = self.get_attachment_data(id, filename) file.write(data) return len(data) def save_or_put(self, data, method='post', headers=None, summarize_errors=True): uri = '/'.join([self.base_url, self.name]) body = {'xml': self._prepare_data_for_save(data)} params = self.extra_params.copy() if not summarize_errors: params['summarizeErrors'] = 'false' return uri, params, method, body, headers, False def _save(self, data): return self.save_or_put(data, method='post') def _put(self, data, summarize_errors=True): return self.save_or_put(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False def prepare_filtering_date(self, val): if isinstance(val, datetime): val = val.strftime('%a, %d %b %Y %H:%M:%S GMT') else: val = '"%s"' % val return {'If-Modified-Since': val} def _filter(self, **kwargs): params = self.extra_params.copy() headers = None uri = '/'.join([self.base_url, self.name]) if kwargs: if 'since' in kwargs: val = kwargs['since'] headers = self.prepare_filtering_date(val) del kwargs['since'] def get_filter_params(key, value): last_key = key.split('_')[-1] if last_key.upper().endswith('ID'): return 'Guid("%s")' % six.text_type(value) if key in self.BOOLEAN_FIELDS: return 'true' if value else 'false' elif key in self.DATE_FIELDS: return 'DateTime(%s,%s,%s)' % (value.year, value.month, value.day) elif key in self.DATETIME_FIELDS: return value.isoformat() else: return '"%s"' % six.text_type(value) def generate_param(key, value): parts = key.split("__") field = key.replace('_', '.') fmt = '%s==%s' if len(parts) == 2: # support filters: # Name__Contains=John becomes Name.Contains("John") if parts[1] in ["contains", "startswith", "endswith"]: field = parts[0] fmt = ''.join(['%s.', parts[1], '(%s)']) elif parts[1] in self.OPERATOR_MAPPINGS: field = parts[0] key = field fmt = '%s' + self.OPERATOR_MAPPINGS[parts[1]] + '%s' elif parts[1] in ["isnull"]: sign = '=' if value else '!' return '%s%s=null' % (parts[0], sign) field = field.replace('_', '.') return fmt % ( field, get_filter_params(key, value) ) # Move any known parameter names to the query string KNOWN_PARAMETERS = ['order', 'offset', 'page', 'includeArchived'] for param in KNOWN_PARAMETERS: if param in kwargs: params[param] = kwargs.pop(param) filter_params = [] if 'raw' in kwargs: raw = kwargs.pop('raw') filter_params.append(raw) # Treat any remaining arguments as filter predicates # Xero will break if you search without a check for null in the first position: # http://developer.xero.com/documentation/getting-started/http-requests-and-responses/#title3 sortedkwargs = sorted(six.iteritems(kwargs), key=lambda item: -1 if 'isnull' in item[0] else 0) for key, value in sortedkwargs: filter_params.append(generate_param(key, value)) if filter_params: params['where'] = '&&'.join(filter_params) return uri, params, 'get', None, headers, False def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.page_response
python
def page_response(self, title='', body=''): f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close()
Helper to render an html page with dynamic content
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L22-L41
null
class PartnerCredentialsHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers() def do_GET(self): """ Handle GET request """ consumer_key = os.environ.get('XERO_CONSUMER_KEY') consumer_secret = os.environ.get('XERO_CONSUMER_SECRET') private_key_path = os.environ.get('XERO_RSA_CERT_KEY_PATH') if consumer_key is None or consumer_secret is None: raise ValueError( 'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables') if not private_key_path: raise ValueError( 'Use the XERO_RSA_CERT_KEY_PATH env variable to specify the path to your RSA ' 'certificate private key file') with open(private_key_path, 'r') as f: rsa_key = f.read() f.close() print("Serving path: {}".format(self.path)) path = urlparse(self.path) if path.path == '/do-auth': credentials = PartnerCredentials( consumer_key, consumer_secret, rsa_key, callback_uri='http://localhost:8000/oauth') # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) # Redirect to Xero at url provided by credentials generation self.redirect_response(credentials.url) return elif path.path == '/oauth': params = dict(parse_qsl(path.query)) if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params: self.send_error(500, message='Missing parameters required.') return stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) try: credentials.verify(params['oauth_verifier']) # Resave our verified credentials for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return # Once verified, api can be invoked with xero = Xero(credentials) self.redirect_response('/verified') return elif path.path == '/verified': stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) # Partner credentials expire after 30 minutes. Here's how to re-activate on expiry if credentials.expired(): credentials.refresh() try: xero = Xero(credentials) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return page_body = 'Your contacts:<br><br>' contacts = xero.contacts.all() if contacts: page_body += '<br>'.join([str(contact) for contact in contacts]) else: page_body += 'No contacts' self.page_response(title='Xero Contacts', body=page_body) return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.redirect_response
python
def redirect_response(self, url, permanent=False): if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers()
Generate redirect response
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L43-L52
null
class PartnerCredentialsHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close() def do_GET(self): """ Handle GET request """ consumer_key = os.environ.get('XERO_CONSUMER_KEY') consumer_secret = os.environ.get('XERO_CONSUMER_SECRET') private_key_path = os.environ.get('XERO_RSA_CERT_KEY_PATH') if consumer_key is None or consumer_secret is None: raise ValueError( 'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables') if not private_key_path: raise ValueError( 'Use the XERO_RSA_CERT_KEY_PATH env variable to specify the path to your RSA ' 'certificate private key file') with open(private_key_path, 'r') as f: rsa_key = f.read() f.close() print("Serving path: {}".format(self.path)) path = urlparse(self.path) if path.path == '/do-auth': credentials = PartnerCredentials( consumer_key, consumer_secret, rsa_key, callback_uri='http://localhost:8000/oauth') # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) # Redirect to Xero at url provided by credentials generation self.redirect_response(credentials.url) return elif path.path == '/oauth': params = dict(parse_qsl(path.query)) if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params: self.send_error(500, message='Missing parameters required.') return stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) try: credentials.verify(params['oauth_verifier']) # Resave our verified credentials for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return # Once verified, api can be invoked with xero = Xero(credentials) self.redirect_response('/verified') return elif path.path == '/verified': stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) # Partner credentials expire after 30 minutes. Here's how to re-activate on expiry if credentials.expired(): credentials.refresh() try: xero = Xero(credentials) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return page_body = 'Your contacts:<br><br>' contacts = xero.contacts.all() if contacts: page_body += '<br>'.join([str(contact) for contact in contacts]) else: page_body += 'No contacts' self.page_response(title='Xero Contacts', body=page_body) return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.do_GET
python
def do_GET(self): consumer_key = os.environ.get('XERO_CONSUMER_KEY') consumer_secret = os.environ.get('XERO_CONSUMER_SECRET') private_key_path = os.environ.get('XERO_RSA_CERT_KEY_PATH') if consumer_key is None or consumer_secret is None: raise ValueError( 'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables') if not private_key_path: raise ValueError( 'Use the XERO_RSA_CERT_KEY_PATH env variable to specify the path to your RSA ' 'certificate private key file') with open(private_key_path, 'r') as f: rsa_key = f.read() f.close() print("Serving path: {}".format(self.path)) path = urlparse(self.path) if path.path == '/do-auth': credentials = PartnerCredentials( consumer_key, consumer_secret, rsa_key, callback_uri='http://localhost:8000/oauth') # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) # Redirect to Xero at url provided by credentials generation self.redirect_response(credentials.url) return elif path.path == '/oauth': params = dict(parse_qsl(path.query)) if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params: self.send_error(500, message='Missing parameters required.') return stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) try: credentials.verify(params['oauth_verifier']) # Resave our verified credentials for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return # Once verified, api can be invoked with xero = Xero(credentials) self.redirect_response('/verified') return elif path.path == '/verified': stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) # Partner credentials expire after 30 minutes. Here's how to re-activate on expiry if credentials.expired(): credentials.refresh() try: xero = Xero(credentials) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return page_body = 'Your contacts:<br><br>' contacts = xero.contacts.all() if contacts: page_body += '<br>'.join([str(contact) for contact in contacts]) else: page_body += 'No contacts' self.page_response(title='Xero Contacts', body=page_body) return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handle GET request
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L54-L145
[ "def verify(self, verifier):\n \"Verify an OAuth token\"\n\n # Construct the credentials for the verification request\n oauth = OAuth1(\n self.consumer_key,\n client_secret=self.consumer_secret,\n resource_owner_key=self.oauth_token,\n resource_owner_secret=self.oauth_token_secret,\n verifier=verifier,\n rsa_key=self.rsa_key,\n signature_method=self._signature_method\n )\n\n # Make the verification request, gettiung back an access token\n url = self.base_url + ACCESS_TOKEN_URL\n headers = {'User-Agent': self.user_agent}\n response = requests.post(url=url, headers=headers, auth=oauth)\n self._process_oauth_response(response)\n self.verified = True\n", "def expired(self, now=None):\n if now is None:\n now = datetime.datetime.now()\n\n # Credentials states from older versions might not have\n # oauth_expires_at available\n if self.oauth_expires_at is None:\n raise XeroException(None, \"Expiry time is not available\")\n\n # Allow a bit of time for clock differences and round trip times\n # to prevent false negatives. If users want the precise expiry,\n # they can use self.oauth_expires_at\n CONSERVATIVE_SECONDS = 30\n\n return self.oauth_expires_at <= \\\n (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))\n" ]
class PartnerCredentialsHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close() def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers() def do_GET(self): """ Handle GET request """ consumer_key = os.environ.get('XERO_CONSUMER_KEY') consumer_secret = os.environ.get('XERO_CONSUMER_SECRET') private_key_path = os.environ.get('XERO_RSA_CERT_KEY_PATH') if consumer_key is None or consumer_secret is None: raise ValueError( 'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables') if not private_key_path: raise ValueError( 'Use the XERO_RSA_CERT_KEY_PATH env variable to specify the path to your RSA ' 'certificate private key file') with open(private_key_path, 'r') as f: rsa_key = f.read() f.close() print("Serving path: {}".format(self.path)) path = urlparse(self.path) if path.path == '/do-auth': credentials = PartnerCredentials( consumer_key, consumer_secret, rsa_key, callback_uri='http://localhost:8000/oauth') # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) # Redirect to Xero at url provided by credentials generation self.redirect_response(credentials.url) return elif path.path == '/oauth': params = dict(parse_qsl(path.query)) if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params: self.send_error(500, message='Missing parameters required.') return stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) try: credentials.verify(params['oauth_verifier']) # Resave our verified credentials for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return # Once verified, api can be invoked with xero = Xero(credentials) self.redirect_response('/verified') return elif path.path == '/verified': stored_values = OAUTH_PERSISTENT_SERVER_STORAGE stored_values.update({'rsa_key': rsa_key}) credentials = PartnerCredentials(**stored_values) # Partner credentials expire after 30 minutes. Here's how to re-activate on expiry if credentials.expired(): credentials.refresh() try: xero = Xero(credentials) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return page_body = 'Your contacts:<br><br>' contacts = xero.contacts.all() if contacts: page_body += '<br>'.join([str(contact) for contact in contacts]) else: page_body += 'No contacts' self.page_response(title='Xero Contacts', body=page_body) return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
freakboy3742/pyxero
examples/public_oauth_flow/runserver.py
PublicCredentialsHandler.do_GET
python
def do_GET(self): consumer_key = os.environ.get('XERO_CONSUMER_KEY') consumer_secret = os.environ.get('XERO_CONSUMER_SECRET') if consumer_key is None or consumer_secret is None: raise KeyError( 'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables') print("Serving path: {}".format(self.path)) path = urlparse(self.path) if path.path == '/do-auth': credentials = PublicCredentials( consumer_key, consumer_secret, callback_uri='http://localhost:8000/oauth') # Save generated credentials details to persistent storage for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) # Redirect to Xero at url provided by credentials generation self.redirect_response(credentials.url) return elif path.path == '/oauth': params = dict(parse_qsl(path.query)) if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params: self.send_error(500, message='Missing parameters required.') return stored_values = OAUTH_PERSISTENT_SERVER_STORAGE credentials = PublicCredentials(**stored_values) try: credentials.verify(params['oauth_verifier']) # Resave our verified credentials for key, value in credentials.state.items(): OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value}) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return # Once verified, api can be invoked with xero = Xero(credentials) self.redirect_response('/verified') return elif path.path == '/verified': stored_values = OAUTH_PERSISTENT_SERVER_STORAGE credentials = PublicCredentials(**stored_values) try: xero = Xero(credentials) except XeroException as e: self.send_error(500, message='{}: {}'.format(e.__class__, e.message)) return page_body = 'Your contacts:<br><br>' contacts = xero.contacts.all() if contacts: page_body += '<br>'.join([str(contact) for contact in contacts]) else: page_body += 'No contacts' self.page_response(title='Xero Contacts', body=page_body) return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handle GET request
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/public_oauth_flow/runserver.py#L54-L126
[ "def verify(self, verifier):\n \"Verify an OAuth token\"\n\n # Construct the credentials for the verification request\n oauth = OAuth1(\n self.consumer_key,\n client_secret=self.consumer_secret,\n resource_owner_key=self.oauth_token,\n resource_owner_secret=self.oauth_token_secret,\n verifier=verifier,\n rsa_key=self.rsa_key,\n signature_method=self._signature_method\n )\n\n # Make the verification request, gettiung back an access token\n url = self.base_url + ACCESS_TOKEN_URL\n headers = {'User-Agent': self.user_agent}\n response = requests.post(url=url, headers=headers, auth=oauth)\n self._process_oauth_response(response)\n self.verified = True\n" ]
class PublicCredentialsHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html">\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close() def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers()
freakboy3742/pyxero
xero/auth.py
PublicCredentials._init_credentials
python
def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response)
Depending on the state passed in, get self._oauth up and running
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L134-L163
[ "def _init_oauth(self, oauth_token, oauth_token_secret):\n \"Store and initialize a verified set of OAuth credentials\"\n self.oauth_token = oauth_token\n self.oauth_token_secret = oauth_token_secret\n\n self._oauth = OAuth1(\n self.consumer_key,\n client_secret=self.consumer_secret,\n resource_owner_key=self.oauth_token,\n resource_owner_secret=self.oauth_token_secret,\n rsa_key=self.rsa_key,\n signature_method=self._signature_method\n )\n", "def _process_oauth_response(self, response):\n \"Extracts the fields from an oauth response\"\n if response.status_code == 200:\n credentials = parse_qs(response.text)\n\n # Initialize the oauth credentials\n self._init_oauth(\n credentials.get('oauth_token')[0],\n credentials.get('oauth_token_secret')[0]\n )\n\n # If tokens are refreshable, we'll get a session handle\n self.oauth_session_handle = credentials.get(\n 'oauth_session_handle', [None])[0]\n\n # Calculate token/auth expiry\n oauth_expires_in = credentials.get(\n 'oauth_expires_in',\n [OAUTH_EXPIRY_SECONDS])[0]\n oauth_authorisation_expires_in = credentials.get(\n 'oauth_authorization_expires_in',\n [OAUTH_EXPIRY_SECONDS])[0]\n\n self.oauth_expires_at = datetime.datetime.now() + \\\n datetime.timedelta(seconds=int(\n oauth_expires_in))\n self.oauth_authorization_expires_at = \\\n datetime.datetime.now() + \\\n datetime.timedelta(seconds=int(\n oauth_authorisation_expires_in))\n else:\n self._handle_error_response(response)\n" ]
class PublicCredentials(object): """An object wrapping the 3-step OAuth process for Public Xero API access. Usage: 1) Construct a PublicCredentials() instance: >>> from xero import PublicCredentials >>> credentials = PublicCredentials(<consumer_key>, <consumer_secret>) 2) Visit the authentication URL: >>> credentials.url If a callback URI was provided (e.g., https://example.com/oauth), the user will be redirected to a URL of the form: https://example.com/oauth?oauth_token=<token>&oauth_verifier=<verifier>&org=<organization ID> from which the verifier can be extracted. If no callback URI is provided, the verifier will be shown on the screen, and must be manually entered by the user. 3) Verify the instance: >>> credentials.verify(<verifier string>) 4) Use the credentials. >>> from xero import Xero >>> xero = Xero(credentials) >>> xero.contacts.all() ... """ def __init__(self, consumer_key, consumer_secret, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, scope=None, user_agent=None): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self.base_url = XERO_BASE_URL self._signature_method = SIGNATURE_HMAC # These are not strictly used by Public Credentials, but # are reserved for use by other credentials (i.e. Partner) self.rsa_key = None self.oauth_session_handle = None self._init_credentials(oauth_token, oauth_token_secret) def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response) def _handle_error_response(self, response): if response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) @property def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None ) def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True @property def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url @property def oauth(self): "Returns the requests-compatible OAuth object" if self._oauth is None: raise XeroNotVerified("OAuth credentials haven't been verified") return self._oauth def expired(self, now=None): if now is None: now = datetime.datetime.now() # Credentials states from older versions might not have # oauth_expires_at available if self.oauth_expires_at is None: raise XeroException(None, "Expiry time is not available") # Allow a bit of time for clock differences and round trip times # to prevent false negatives. If users want the precise expiry, # they can use self.oauth_expires_at CONSERVATIVE_SECONDS = 30 return self.oauth_expires_at <= \ (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))
freakboy3742/pyxero
xero/auth.py
PublicCredentials._init_oauth
python
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method )
Store and initialize a verified set of OAuth credentials
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L165-L177
null
class PublicCredentials(object): """An object wrapping the 3-step OAuth process for Public Xero API access. Usage: 1) Construct a PublicCredentials() instance: >>> from xero import PublicCredentials >>> credentials = PublicCredentials(<consumer_key>, <consumer_secret>) 2) Visit the authentication URL: >>> credentials.url If a callback URI was provided (e.g., https://example.com/oauth), the user will be redirected to a URL of the form: https://example.com/oauth?oauth_token=<token>&oauth_verifier=<verifier>&org=<organization ID> from which the verifier can be extracted. If no callback URI is provided, the verifier will be shown on the screen, and must be manually entered by the user. 3) Verify the instance: >>> credentials.verify(<verifier string>) 4) Use the credentials. >>> from xero import Xero >>> xero = Xero(credentials) >>> xero.contacts.all() ... """ def __init__(self, consumer_key, consumer_secret, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, scope=None, user_agent=None): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self.base_url = XERO_BASE_URL self._signature_method = SIGNATURE_HMAC # These are not strictly used by Public Credentials, but # are reserved for use by other credentials (i.e. Partner) self.rsa_key = None self.oauth_session_handle = None self._init_credentials(oauth_token, oauth_token_secret) def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response) def _handle_error_response(self, response): if response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) @property def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None ) def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True @property def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url @property def oauth(self): "Returns the requests-compatible OAuth object" if self._oauth is None: raise XeroNotVerified("OAuth credentials haven't been verified") return self._oauth def expired(self, now=None): if now is None: now = datetime.datetime.now() # Credentials states from older versions might not have # oauth_expires_at available if self.oauth_expires_at is None: raise XeroException(None, "Expiry time is not available") # Allow a bit of time for clock differences and round trip times # to prevent false negatives. If users want the precise expiry, # they can use self.oauth_expires_at CONSERVATIVE_SECONDS = 30 return self.oauth_expires_at <= \ (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))
freakboy3742/pyxero
xero/auth.py
PublicCredentials._process_oauth_response
python
def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response)
Extracts the fields from an oauth response
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L179-L210
[ "def _init_oauth(self, oauth_token, oauth_token_secret):\n \"Store and initialize a verified set of OAuth credentials\"\n self.oauth_token = oauth_token\n self.oauth_token_secret = oauth_token_secret\n\n self._oauth = OAuth1(\n self.consumer_key,\n client_secret=self.consumer_secret,\n resource_owner_key=self.oauth_token,\n resource_owner_secret=self.oauth_token_secret,\n rsa_key=self.rsa_key,\n signature_method=self._signature_method\n )\n", "def _handle_error_response(self, response):\n if response.status_code == 400:\n raise XeroBadRequest(response)\n\n elif response.status_code == 401:\n raise XeroUnauthorized(response)\n\n elif response.status_code == 403:\n raise XeroForbidden(response)\n\n elif response.status_code == 404:\n raise XeroNotFound(response)\n\n elif response.status_code == 500:\n raise XeroInternalError(response)\n\n elif response.status_code == 501:\n raise XeroNotImplemented(response)\n\n elif response.status_code == 503:\n # Two 503 responses are possible. Rate limit errors\n # return encoded content; offline errors don't.\n # If you parse the response text and there's nothing\n # encoded, it must be a not-available error.\n payload = parse_qs(response.text)\n if payload:\n raise XeroRateLimitExceeded(response, payload)\n else:\n raise XeroNotAvailable(response)\n else:\n raise XeroExceptionUnknown(response)\n" ]
class PublicCredentials(object): """An object wrapping the 3-step OAuth process for Public Xero API access. Usage: 1) Construct a PublicCredentials() instance: >>> from xero import PublicCredentials >>> credentials = PublicCredentials(<consumer_key>, <consumer_secret>) 2) Visit the authentication URL: >>> credentials.url If a callback URI was provided (e.g., https://example.com/oauth), the user will be redirected to a URL of the form: https://example.com/oauth?oauth_token=<token>&oauth_verifier=<verifier>&org=<organization ID> from which the verifier can be extracted. If no callback URI is provided, the verifier will be shown on the screen, and must be manually entered by the user. 3) Verify the instance: >>> credentials.verify(<verifier string>) 4) Use the credentials. >>> from xero import Xero >>> xero = Xero(credentials) >>> xero.contacts.all() ... """ def __init__(self, consumer_key, consumer_secret, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, scope=None, user_agent=None): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self.base_url = XERO_BASE_URL self._signature_method = SIGNATURE_HMAC # These are not strictly used by Public Credentials, but # are reserved for use by other credentials (i.e. Partner) self.rsa_key = None self.oauth_session_handle = None self._init_credentials(oauth_token, oauth_token_secret) def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) def _handle_error_response(self, response): if response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) @property def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None ) def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True @property def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url @property def oauth(self): "Returns the requests-compatible OAuth object" if self._oauth is None: raise XeroNotVerified("OAuth credentials haven't been verified") return self._oauth def expired(self, now=None): if now is None: now = datetime.datetime.now() # Credentials states from older versions might not have # oauth_expires_at available if self.oauth_expires_at is None: raise XeroException(None, "Expiry time is not available") # Allow a bit of time for clock differences and round trip times # to prevent false negatives. If users want the precise expiry, # they can use self.oauth_expires_at CONSERVATIVE_SECONDS = 30 return self.oauth_expires_at <= \ (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))
freakboy3742/pyxero
xero/auth.py
PublicCredentials.state
python
def state(self): return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None )
Obtain the useful state of this credentials object so that we can reconstruct it independently.
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L245-L258
null
class PublicCredentials(object): """An object wrapping the 3-step OAuth process for Public Xero API access. Usage: 1) Construct a PublicCredentials() instance: >>> from xero import PublicCredentials >>> credentials = PublicCredentials(<consumer_key>, <consumer_secret>) 2) Visit the authentication URL: >>> credentials.url If a callback URI was provided (e.g., https://example.com/oauth), the user will be redirected to a URL of the form: https://example.com/oauth?oauth_token=<token>&oauth_verifier=<verifier>&org=<organization ID> from which the verifier can be extracted. If no callback URI is provided, the verifier will be shown on the screen, and must be manually entered by the user. 3) Verify the instance: >>> credentials.verify(<verifier string>) 4) Use the credentials. >>> from xero import Xero >>> xero = Xero(credentials) >>> xero.contacts.all() ... """ def __init__(self, consumer_key, consumer_secret, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, scope=None, user_agent=None): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self.base_url = XERO_BASE_URL self._signature_method = SIGNATURE_HMAC # These are not strictly used by Public Credentials, but # are reserved for use by other credentials (i.e. Partner) self.rsa_key = None self.oauth_session_handle = None self._init_credentials(oauth_token, oauth_token_secret) def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response) def _handle_error_response(self, response): if response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) @property def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True @property def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url @property def oauth(self): "Returns the requests-compatible OAuth object" if self._oauth is None: raise XeroNotVerified("OAuth credentials haven't been verified") return self._oauth def expired(self, now=None): if now is None: now = datetime.datetime.now() # Credentials states from older versions might not have # oauth_expires_at available if self.oauth_expires_at is None: raise XeroException(None, "Expiry time is not available") # Allow a bit of time for clock differences and round trip times # to prevent false negatives. If users want the precise expiry, # they can use self.oauth_expires_at CONSERVATIVE_SECONDS = 30 return self.oauth_expires_at <= \ (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))
freakboy3742/pyxero
xero/auth.py
PublicCredentials.verify
python
def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True
Verify an OAuth token
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L260-L279
[ "def _process_oauth_response(self, response):\n \"Extracts the fields from an oauth response\"\n if response.status_code == 200:\n credentials = parse_qs(response.text)\n\n # Initialize the oauth credentials\n self._init_oauth(\n credentials.get('oauth_token')[0],\n credentials.get('oauth_token_secret')[0]\n )\n\n # If tokens are refreshable, we'll get a session handle\n self.oauth_session_handle = credentials.get(\n 'oauth_session_handle', [None])[0]\n\n # Calculate token/auth expiry\n oauth_expires_in = credentials.get(\n 'oauth_expires_in',\n [OAUTH_EXPIRY_SECONDS])[0]\n oauth_authorisation_expires_in = credentials.get(\n 'oauth_authorization_expires_in',\n [OAUTH_EXPIRY_SECONDS])[0]\n\n self.oauth_expires_at = datetime.datetime.now() + \\\n datetime.timedelta(seconds=int(\n oauth_expires_in))\n self.oauth_authorization_expires_at = \\\n datetime.datetime.now() + \\\n datetime.timedelta(seconds=int(\n oauth_authorisation_expires_in))\n else:\n self._handle_error_response(response)\n" ]
class PublicCredentials(object): """An object wrapping the 3-step OAuth process for Public Xero API access. Usage: 1) Construct a PublicCredentials() instance: >>> from xero import PublicCredentials >>> credentials = PublicCredentials(<consumer_key>, <consumer_secret>) 2) Visit the authentication URL: >>> credentials.url If a callback URI was provided (e.g., https://example.com/oauth), the user will be redirected to a URL of the form: https://example.com/oauth?oauth_token=<token>&oauth_verifier=<verifier>&org=<organization ID> from which the verifier can be extracted. If no callback URI is provided, the verifier will be shown on the screen, and must be manually entered by the user. 3) Verify the instance: >>> credentials.verify(<verifier string>) 4) Use the credentials. >>> from xero import Xero >>> xero = Xero(credentials) >>> xero.contacts.all() ... """ def __init__(self, consumer_key, consumer_secret, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, scope=None, user_agent=None): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self.base_url = XERO_BASE_URL self._signature_method = SIGNATURE_HMAC # These are not strictly used by Public Credentials, but # are reserved for use by other credentials (i.e. Partner) self.rsa_key = None self.oauth_session_handle = None self._init_credentials(oauth_token, oauth_token_secret) def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response) def _handle_error_response(self, response): if response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) @property def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None ) @property def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url @property def oauth(self): "Returns the requests-compatible OAuth object" if self._oauth is None: raise XeroNotVerified("OAuth credentials haven't been verified") return self._oauth def expired(self, now=None): if now is None: now = datetime.datetime.now() # Credentials states from older versions might not have # oauth_expires_at available if self.oauth_expires_at is None: raise XeroException(None, "Expiry time is not available") # Allow a bit of time for clock differences and round trip times # to prevent false negatives. If users want the precise expiry, # they can use self.oauth_expires_at CONSERVATIVE_SECONDS = 30 return self.oauth_expires_at <= \ (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))
freakboy3742/pyxero
xero/auth.py
PublicCredentials.url
python
def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url
Returns the URL that can be visited to obtain a verifier code
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L282-L292
null
class PublicCredentials(object): """An object wrapping the 3-step OAuth process for Public Xero API access. Usage: 1) Construct a PublicCredentials() instance: >>> from xero import PublicCredentials >>> credentials = PublicCredentials(<consumer_key>, <consumer_secret>) 2) Visit the authentication URL: >>> credentials.url If a callback URI was provided (e.g., https://example.com/oauth), the user will be redirected to a URL of the form: https://example.com/oauth?oauth_token=<token>&oauth_verifier=<verifier>&org=<organization ID> from which the verifier can be extracted. If no callback URI is provided, the verifier will be shown on the screen, and must be manually entered by the user. 3) Verify the instance: >>> credentials.verify(<verifier string>) 4) Use the credentials. >>> from xero import Xero >>> xero = Xero(credentials) >>> xero.contacts.all() ... """ def __init__(self, consumer_key, consumer_secret, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, scope=None, user_agent=None): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self.base_url = XERO_BASE_URL self._signature_method = SIGNATURE_HMAC # These are not strictly used by Public Credentials, but # are reserved for use by other credentials (i.e. Partner) self.rsa_key = None self.oauth_session_handle = None self._init_credentials(oauth_token, oauth_token_secret) def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response) def _handle_error_response(self, response): if response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) @property def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None ) def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True @property @property def oauth(self): "Returns the requests-compatible OAuth object" if self._oauth is None: raise XeroNotVerified("OAuth credentials haven't been verified") return self._oauth def expired(self, now=None): if now is None: now = datetime.datetime.now() # Credentials states from older versions might not have # oauth_expires_at available if self.oauth_expires_at is None: raise XeroException(None, "Expiry time is not available") # Allow a bit of time for clock differences and round trip times # to prevent false negatives. If users want the precise expiry, # they can use self.oauth_expires_at CONSERVATIVE_SECONDS = 30 return self.oauth_expires_at <= \ (now + datetime.timedelta(seconds=CONSERVATIVE_SECONDS))
freakboy3742/pyxero
xero/auth.py
PartnerCredentials.refresh
python
def refresh(self): "Refresh an expired token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, getting back an access token headers = {'User-Agent': self.user_agent} params = {'oauth_session_handle': self.oauth_session_handle} response = requests.post(url=self.base_url + ACCESS_TOKEN_URL, params=params, headers=headers, auth=oauth) self._process_oauth_response(response)
Refresh an expired token
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L375-L393
[ "def _process_oauth_response(self, response):\n \"Extracts the fields from an oauth response\"\n if response.status_code == 200:\n credentials = parse_qs(response.text)\n\n # Initialize the oauth credentials\n self._init_oauth(\n credentials.get('oauth_token')[0],\n credentials.get('oauth_token_secret')[0]\n )\n\n # If tokens are refreshable, we'll get a session handle\n self.oauth_session_handle = credentials.get(\n 'oauth_session_handle', [None])[0]\n\n # Calculate token/auth expiry\n oauth_expires_in = credentials.get(\n 'oauth_expires_in',\n [OAUTH_EXPIRY_SECONDS])[0]\n oauth_authorisation_expires_in = credentials.get(\n 'oauth_authorization_expires_in',\n [OAUTH_EXPIRY_SECONDS])[0]\n\n self.oauth_expires_at = datetime.datetime.now() + \\\n datetime.timedelta(seconds=int(\n oauth_expires_in))\n self.oauth_authorization_expires_at = \\\n datetime.datetime.now() + \\\n datetime.timedelta(seconds=int(\n oauth_authorisation_expires_in))\n else:\n self._handle_error_response(response)\n" ]
class PartnerCredentials(PublicCredentials): """An object wrapping the 3-step OAuth process for Partner Xero API access. Usage is very similar to Public Credentials with the following changes: 1) You'll need to pass the private key for your RSA certificate. >>> rsa_key = "-----BEGIN RSA PRIVATE KEY----- ..." 2) Once a token has expired, you can refresh it to get another 30 mins >>> credentials = PartnerCredentials(**state) >>> if credentials.expired(): credentials.refresh() 3) Authorization expiry and token expiry become different things. oauth_expires_at tells when the current token expires (~30 min window) oauth_authorization_expires_at tells when the overall access permissions expire (~10 year window) """ def __init__(self, consumer_key, consumer_secret, rsa_key, callback_uri=None, verified=False, oauth_token=None, oauth_token_secret=None, oauth_expires_at=None, oauth_authorization_expires_at=None, oauth_session_handle=None, scope=None, user_agent=None, **kwargs): """Construct the auth instance. Must provide the consumer key and secret. A callback URL may be provided as an option. If provided, the Xero verification process will redirect to that URL when """ from xero import __version__ as VERSION self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.callback_uri = callback_uri self.verified = verified self._oauth = None self.oauth_expires_at = oauth_expires_at self.oauth_authorization_expires_at = oauth_authorization_expires_at self.scope = scope if user_agent is None: self.user_agent = 'pyxero/%s ' % VERSION + requests.utils.default_user_agent() else: self.user_agent = user_agent self._signature_method = SIGNATURE_RSA self.base_url = XERO_BASE_URL self.rsa_key = rsa_key self.oauth_session_handle = oauth_session_handle self._init_credentials(oauth_token, oauth_token_secret)
freakboy3742/pyxero
xero/filesmanager.py
FilesManager._get_files
python
def _get_files(self, folderId): uri = '/'.join([self.base_url, self.name, folderId, 'Files']) return uri, {}, 'get', None, None, False, None
Retrieve the list of files contained in a folder
train
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/filesmanager.py#L118-L121
null
class FilesManager(object): DECORATED_METHODS = ( 'get', 'all', 'create', 'save', 'delete', 'get_files', 'upload_file', 'get_association', 'get_associations', 'make_association', 'delete_association', 'get_content', ) def __init__(self, name, credentials): self.credentials = credentials self.name = name self.base_url = credentials.base_url + XERO_FILES_URL for method_name in self.DECORATED_METHODS: method = getattr(self, '_%s' % method_name) setattr(self, method_name, self._get_data(method)) def _get_results(self, data): response = data['Response'] if self.name in response: result = response[self.name] elif 'Attachments' in response: result = response['Attachments'] else: return None if isinstance(result, tuple) or isinstance(result, list): return result if isinstance(result, dict) and self.singular in result: return result[self.singular] def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): uri, params, method, body, headers, singleobject, files = func(*args, **kwargs) response = getattr(requests, method)( uri, data=body, headers=headers, auth=self.credentials.oauth, params=params, files=files) if response.status_code == 200 or response.status_code == 201: if response.headers['content-type'].startswith('application/json'): return response.json() else: # return a byte string without doing any Unicode conversions return response.content #Delete will return a response code of 204 - No Content elif response.status_code == 204: return "Deleted" elif response.status_code == 400: raise XeroBadRequest(response) elif response.status_code == 401: raise XeroUnauthorized(response) elif response.status_code == 403: raise XeroForbidden(response) elif response.status_code == 404: raise XeroNotFound(response) elif response.status_code == 415: raise XeroUnsupportedMediaType(response) elif response.status_code == 500: raise XeroInternalError(response) elif response.status_code == 501: raise XeroNotImplemented(response) elif response.status_code == 503: # Two 503 responses are possible. Rate limit errors # return encoded content; offline errors don't. # If you parse the response text and there's nothing # encoded, it must be a not-available error. payload = parse_qs(response.text) if payload: raise XeroRateLimitExceeded(response, payload) else: raise XeroNotAvailable(response) else: raise XeroExceptionUnknown(response) return wrapper def _get(self, id, headers=None): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'get', None, headers, True, None def _get_associations(self, id): uri = '/'.join([self.base_url, self.name, id, 'Associations']) + '/' return uri, {}, 'get', None, None, False, None def _get_association(self, fileId, objectId): uri = '/'.join([self.base_url, self.name, fileId, 'Associations', objectId]) return uri, {}, 'get', None, None, False, None def _delete_association(self, fileId, objectId): uri = '/'.join([self.base_url, self.name, fileId, 'Associations', objectId]) return uri, {}, 'delete', None, None, False, None def create_or_save(self, data, method='post', headers=None, summarize_errors=True): if not "Id" in data: uri = '/'.join([self.base_url, self.name]) else: uri = '/'.join([self.base_url, self.name, data["Id"]]) body = data if summarize_errors: params = {} else: params = {'summarizeErrors': 'false'} return uri, params, method, body, headers, False, None def _create(self, data): return self.create_or_save(data, method='post') def _save(self, data, summarize_errors=True): return self.create_or_save(data, method='put', summarize_errors=summarize_errors) def _delete(self, id): uri = '/'.join([self.base_url, self.name, id]) return uri, {}, 'delete', None, None, False, None def _upload_file(self, path, folderId=None): if not folderId is None: uri = '/'.join([self.base_url, self.name, folderId]) else: uri = '/'.join([self.base_url, self.name]) filename = self.filename(path) files = dict() files[filename] = open(path, mode="rb") return uri, {}, 'post', None, None, False, files def _get_content(self, fileId): uri = '/'.join([self.base_url, self.name, fileId, "Content"]) return uri, {}, 'get', None, None, False, None def _make_association(self, id, data): uri = '/'.join([self.base_url, self.name, id, 'Associations']) body = data return uri, {}, 'post', body, None, False, None def _all(self): uri = '/'.join([self.base_url, self.name]) return uri, {}, 'get', None, None, False, None def filename(self, path): head, tail = os.path.split(path) return tail or os.path.basename(head)
jjkester/django-auditlog
src/auditlog/middleware.py
AuditlogMiddleware.process_request
python
def process_request(self, request): # Initialize thread local storage threadlocal.auditlog = { 'signal_duid': (self.__class__, time.time()), 'remote_addr': request.META.get('REMOTE_ADDR'), } # In case of proxy, set 'original' address if request.META.get('HTTP_X_FORWARDED_FOR'): threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0] # Connect signal for automatic logging if hasattr(request, 'user') and is_authenticated(request.user): set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid']) pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False)
Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/middleware.py#L29-L47
[ "def is_authenticated(user):\n \"\"\"Return whether or not a User is authenticated.\n\n Function provides compatibility following deprecation of method call to\n `is_authenticated()` in Django 2.0.\n\n This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier),\n as `is_authenticated` was introduced as a property in v1.10.s\n \"\"\"\n if not hasattr(user, 'is_authenticated'):\n return False\n if callable(user.is_authenticated):\n # Will be callable if django.version < 2.0, but is only necessary in\n # v1.9 and earlier due to change introduced in v1.10 making\n # `is_authenticated` a property instead of a callable.\n return user.is_authenticated()\n else:\n return user.is_authenticated\n" ]
class AuditlogMiddleware(MiddlewareMixin): """ Middleware to couple the request's user to log items. This is accomplished by currying the signal receiver with the user from the request (or None if the user is not authenticated). """ def process_response(self, request, response): """ Disconnects the signal receiver to prevent it from staying active. """ if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return response def process_exception(self, request, exception): """ Disconnects the signal receiver to prevent it from staying active in case of an exception. """ if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return None @staticmethod def set_actor(user, sender, instance, signal_duid, **kwargs): """ Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when it is curried with the actor. """ if hasattr(threadlocal, 'auditlog'): if signal_duid != threadlocal.auditlog['signal_duid']: return try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') auth_user_model = apps.get_model(app_label, model_name) except ValueError: auth_user_model = apps.get_model('auth', 'user') if sender == LogEntry and isinstance(user, auth_user_model) and instance.actor is None: instance.actor = user instance.remote_addr = threadlocal.auditlog['remote_addr']
jjkester/django-auditlog
src/auditlog/middleware.py
AuditlogMiddleware.process_response
python
def process_response(self, request, response): if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return response
Disconnects the signal receiver to prevent it from staying active.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/middleware.py#L49-L56
null
class AuditlogMiddleware(MiddlewareMixin): """ Middleware to couple the request's user to log items. This is accomplished by currying the signal receiver with the user from the request (or None if the user is not authenticated). """ def process_request(self, request): """ Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it. """ # Initialize thread local storage threadlocal.auditlog = { 'signal_duid': (self.__class__, time.time()), 'remote_addr': request.META.get('REMOTE_ADDR'), } # In case of proxy, set 'original' address if request.META.get('HTTP_X_FORWARDED_FOR'): threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0] # Connect signal for automatic logging if hasattr(request, 'user') and is_authenticated(request.user): set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid']) pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False) def process_exception(self, request, exception): """ Disconnects the signal receiver to prevent it from staying active in case of an exception. """ if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return None @staticmethod def set_actor(user, sender, instance, signal_duid, **kwargs): """ Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when it is curried with the actor. """ if hasattr(threadlocal, 'auditlog'): if signal_duid != threadlocal.auditlog['signal_duid']: return try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') auth_user_model = apps.get_model(app_label, model_name) except ValueError: auth_user_model = apps.get_model('auth', 'user') if sender == LogEntry and isinstance(user, auth_user_model) and instance.actor is None: instance.actor = user instance.remote_addr = threadlocal.auditlog['remote_addr']
jjkester/django-auditlog
src/auditlog/middleware.py
AuditlogMiddleware.process_exception
python
def process_exception(self, request, exception): if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return None
Disconnects the signal receiver to prevent it from staying active in case of an exception.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/middleware.py#L58-L65
null
class AuditlogMiddleware(MiddlewareMixin): """ Middleware to couple the request's user to log items. This is accomplished by currying the signal receiver with the user from the request (or None if the user is not authenticated). """ def process_request(self, request): """ Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it. """ # Initialize thread local storage threadlocal.auditlog = { 'signal_duid': (self.__class__, time.time()), 'remote_addr': request.META.get('REMOTE_ADDR'), } # In case of proxy, set 'original' address if request.META.get('HTTP_X_FORWARDED_FOR'): threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0] # Connect signal for automatic logging if hasattr(request, 'user') and is_authenticated(request.user): set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid']) pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False) def process_response(self, request, response): """ Disconnects the signal receiver to prevent it from staying active. """ if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return response @staticmethod def set_actor(user, sender, instance, signal_duid, **kwargs): """ Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when it is curried with the actor. """ if hasattr(threadlocal, 'auditlog'): if signal_duid != threadlocal.auditlog['signal_duid']: return try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') auth_user_model = apps.get_model(app_label, model_name) except ValueError: auth_user_model = apps.get_model('auth', 'user') if sender == LogEntry and isinstance(user, auth_user_model) and instance.actor is None: instance.actor = user instance.remote_addr = threadlocal.auditlog['remote_addr']
jjkester/django-auditlog
src/auditlog/middleware.py
AuditlogMiddleware.set_actor
python
def set_actor(user, sender, instance, signal_duid, **kwargs): if hasattr(threadlocal, 'auditlog'): if signal_duid != threadlocal.auditlog['signal_duid']: return try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') auth_user_model = apps.get_model(app_label, model_name) except ValueError: auth_user_model = apps.get_model('auth', 'user') if sender == LogEntry and isinstance(user, auth_user_model) and instance.actor is None: instance.actor = user instance.remote_addr = threadlocal.auditlog['remote_addr']
Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when it is curried with the actor.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/middleware.py#L68-L84
null
class AuditlogMiddleware(MiddlewareMixin): """ Middleware to couple the request's user to log items. This is accomplished by currying the signal receiver with the user from the request (or None if the user is not authenticated). """ def process_request(self, request): """ Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it. """ # Initialize thread local storage threadlocal.auditlog = { 'signal_duid': (self.__class__, time.time()), 'remote_addr': request.META.get('REMOTE_ADDR'), } # In case of proxy, set 'original' address if request.META.get('HTTP_X_FORWARDED_FOR'): threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0] # Connect signal for automatic logging if hasattr(request, 'user') and is_authenticated(request.user): set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid']) pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False) def process_response(self, request, response): """ Disconnects the signal receiver to prevent it from staying active. """ if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return response def process_exception(self, request, exception): """ Disconnects the signal receiver to prevent it from staying active in case of an exception. """ if hasattr(threadlocal, 'auditlog'): pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid']) return None @staticmethod
jjkester/django-auditlog
src/auditlog/diff.py
track_field
python
def track_field(field): from auditlog.models import LogEntry # Do not track many to many relations if field.many_to_many: return False # Do not track relations to LogEntry if getattr(field, 'remote_field', None) is not None and field.remote_field.model == LogEntry: return False # 1.8 check elif getattr(field, 'rel', None) is not None and field.rel.to == LogEntry: return False return True
Returns whether the given field should be tracked by Auditlog. Untracked fields are many-to-many relations and relations to the Auditlog LogEntry model. :param field: The field to check. :type field: Field :return: Whether the given field should be tracked. :rtype: bool
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/diff.py#L10-L34
null
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, NOT_PROVIDED, DateTimeField from django.utils import timezone from django.utils.encoding import smart_text def get_fields_in_model(instance): """ Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: Model :return: The list of fields for the given model (instance) :rtype: list """ assert isinstance(instance, Model) # Check if the Django 1.8 _meta API is available use_api = hasattr(instance._meta, 'get_fields') and callable(instance._meta.get_fields) if use_api: return [f for f in instance._meta.get_fields() if track_field(f)] return instance._meta.fields def get_field_value(obj, field): """ Gets the value of a given model instance field. :param obj: The model instance. :type obj: Model :param field: The field you want to find the value of. :type field: Any :return: The value of the field as a string. :rtype: str """ if isinstance(field, DateTimeField): # DateTimeFields are timezone-aware, so we need to convert the field # to its naive form before we can accuratly compare them for changes. try: value = field.to_python(getattr(obj, field.name, None)) if value is not None and settings.USE_TZ and not timezone.is_naive(value): value = timezone.make_naive(value, timezone=timezone.utc) except ObjectDoesNotExist: value = field.default if field.default is not NOT_PROVIDED else None else: try: value = smart_text(getattr(obj, field.name, None)) except ObjectDoesNotExist: value = field.default if field.default is not NOT_PROVIDED else None return value def model_instance_diff(old, new): """ Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly created model or deleted model). This will cause all fields with a value to have changed (from ``None``). :param old: The old state of the model instance. :type old: Model :param new: The new state of the model instance. :type new: Model :return: A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values as value. :rtype: dict """ from auditlog.registry import auditlog if not(old is None or isinstance(old, Model)): raise TypeError("The supplied old instance is not a valid model instance.") if not(new is None or isinstance(new, Model)): raise TypeError("The supplied new instance is not a valid model instance.") diff = {} if old is not None and new is not None: fields = set(old._meta.fields + new._meta.fields) model_fields = auditlog.get_model_fields(new._meta.model) elif old is not None: fields = set(get_fields_in_model(old)) model_fields = auditlog.get_model_fields(old._meta.model) elif new is not None: fields = set(get_fields_in_model(new)) model_fields = auditlog.get_model_fields(new._meta.model) else: fields = set() model_fields = None # Check if fields must be filtered if model_fields and (model_fields['include_fields'] or model_fields['exclude_fields']) and fields: filtered_fields = [] if model_fields['include_fields']: filtered_fields = [field for field in fields if field.name in model_fields['include_fields']] else: filtered_fields = fields if model_fields['exclude_fields']: filtered_fields = [field for field in filtered_fields if field.name not in model_fields['exclude_fields']] fields = filtered_fields for field in fields: old_value = get_field_value(old, field) new_value = get_field_value(new, field) if old_value != new_value: diff[field.name] = (smart_text(old_value), smart_text(new_value)) if len(diff) == 0: diff = None return diff
jjkester/django-auditlog
src/auditlog/diff.py
get_fields_in_model
python
def get_fields_in_model(instance): assert isinstance(instance, Model) # Check if the Django 1.8 _meta API is available use_api = hasattr(instance._meta, 'get_fields') and callable(instance._meta.get_fields) if use_api: return [f for f in instance._meta.get_fields() if track_field(f)] return instance._meta.fields
Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: Model :return: The list of fields for the given model (instance) :rtype: list
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/diff.py#L37-L54
null
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, NOT_PROVIDED, DateTimeField from django.utils import timezone from django.utils.encoding import smart_text def track_field(field): """ Returns whether the given field should be tracked by Auditlog. Untracked fields are many-to-many relations and relations to the Auditlog LogEntry model. :param field: The field to check. :type field: Field :return: Whether the given field should be tracked. :rtype: bool """ from auditlog.models import LogEntry # Do not track many to many relations if field.many_to_many: return False # Do not track relations to LogEntry if getattr(field, 'remote_field', None) is not None and field.remote_field.model == LogEntry: return False # 1.8 check elif getattr(field, 'rel', None) is not None and field.rel.to == LogEntry: return False return True def get_field_value(obj, field): """ Gets the value of a given model instance field. :param obj: The model instance. :type obj: Model :param field: The field you want to find the value of. :type field: Any :return: The value of the field as a string. :rtype: str """ if isinstance(field, DateTimeField): # DateTimeFields are timezone-aware, so we need to convert the field # to its naive form before we can accuratly compare them for changes. try: value = field.to_python(getattr(obj, field.name, None)) if value is not None and settings.USE_TZ and not timezone.is_naive(value): value = timezone.make_naive(value, timezone=timezone.utc) except ObjectDoesNotExist: value = field.default if field.default is not NOT_PROVIDED else None else: try: value = smart_text(getattr(obj, field.name, None)) except ObjectDoesNotExist: value = field.default if field.default is not NOT_PROVIDED else None return value def model_instance_diff(old, new): """ Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly created model or deleted model). This will cause all fields with a value to have changed (from ``None``). :param old: The old state of the model instance. :type old: Model :param new: The new state of the model instance. :type new: Model :return: A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values as value. :rtype: dict """ from auditlog.registry import auditlog if not(old is None or isinstance(old, Model)): raise TypeError("The supplied old instance is not a valid model instance.") if not(new is None or isinstance(new, Model)): raise TypeError("The supplied new instance is not a valid model instance.") diff = {} if old is not None and new is not None: fields = set(old._meta.fields + new._meta.fields) model_fields = auditlog.get_model_fields(new._meta.model) elif old is not None: fields = set(get_fields_in_model(old)) model_fields = auditlog.get_model_fields(old._meta.model) elif new is not None: fields = set(get_fields_in_model(new)) model_fields = auditlog.get_model_fields(new._meta.model) else: fields = set() model_fields = None # Check if fields must be filtered if model_fields and (model_fields['include_fields'] or model_fields['exclude_fields']) and fields: filtered_fields = [] if model_fields['include_fields']: filtered_fields = [field for field in fields if field.name in model_fields['include_fields']] else: filtered_fields = fields if model_fields['exclude_fields']: filtered_fields = [field for field in filtered_fields if field.name not in model_fields['exclude_fields']] fields = filtered_fields for field in fields: old_value = get_field_value(old, field) new_value = get_field_value(new, field) if old_value != new_value: diff[field.name] = (smart_text(old_value), smart_text(new_value)) if len(diff) == 0: diff = None return diff
jjkester/django-auditlog
src/auditlog/diff.py
model_instance_diff
python
def model_instance_diff(old, new): from auditlog.registry import auditlog if not(old is None or isinstance(old, Model)): raise TypeError("The supplied old instance is not a valid model instance.") if not(new is None or isinstance(new, Model)): raise TypeError("The supplied new instance is not a valid model instance.") diff = {} if old is not None and new is not None: fields = set(old._meta.fields + new._meta.fields) model_fields = auditlog.get_model_fields(new._meta.model) elif old is not None: fields = set(get_fields_in_model(old)) model_fields = auditlog.get_model_fields(old._meta.model) elif new is not None: fields = set(get_fields_in_model(new)) model_fields = auditlog.get_model_fields(new._meta.model) else: fields = set() model_fields = None # Check if fields must be filtered if model_fields and (model_fields['include_fields'] or model_fields['exclude_fields']) and fields: filtered_fields = [] if model_fields['include_fields']: filtered_fields = [field for field in fields if field.name in model_fields['include_fields']] else: filtered_fields = fields if model_fields['exclude_fields']: filtered_fields = [field for field in filtered_fields if field.name not in model_fields['exclude_fields']] fields = filtered_fields for field in fields: old_value = get_field_value(old, field) new_value = get_field_value(new, field) if old_value != new_value: diff[field.name] = (smart_text(old_value), smart_text(new_value)) if len(diff) == 0: diff = None return diff
Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly created model or deleted model). This will cause all fields with a value to have changed (from ``None``). :param old: The old state of the model instance. :type old: Model :param new: The new state of the model instance. :type new: Model :return: A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values as value. :rtype: dict
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/diff.py#L85-L143
[ "def get_fields_in_model(instance):\n \"\"\"\n Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw\n data. This method excludes many to many fields.\n\n :param instance: The model instance to get the fields for\n :type instance: Model\n :return: The list of fields for the given model (instance)\n :rtype: list\n \"\"\"\n assert isinstance(instance, Model)\n\n # Check if the Django 1.8 _meta API is available\n use_api = hasattr(instance._meta, 'get_fields') and callable(instance._meta.get_fields)\n\n if use_api:\n return [f for f in instance._meta.get_fields() if track_field(f)]\n return instance._meta.fields\n", "def get_field_value(obj, field):\n \"\"\"\n Gets the value of a given model instance field.\n :param obj: The model instance.\n :type obj: Model\n :param field: The field you want to find the value of.\n :type field: Any\n :return: The value of the field as a string.\n :rtype: str\n \"\"\"\n if isinstance(field, DateTimeField):\n # DateTimeFields are timezone-aware, so we need to convert the field\n # to its naive form before we can accuratly compare them for changes.\n try:\n value = field.to_python(getattr(obj, field.name, None))\n if value is not None and settings.USE_TZ and not timezone.is_naive(value):\n value = timezone.make_naive(value, timezone=timezone.utc)\n except ObjectDoesNotExist:\n value = field.default if field.default is not NOT_PROVIDED else None\n else:\n try:\n value = smart_text(getattr(obj, field.name, None))\n except ObjectDoesNotExist:\n value = field.default if field.default is not NOT_PROVIDED else None\n\n return value\n", "def get_model_fields(self, model):\n return {\n 'include_fields': self._registry[model]['include_fields'],\n 'exclude_fields': self._registry[model]['exclude_fields'],\n 'mapping_fields': self._registry[model]['mapping_fields'],\n }\n" ]
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, NOT_PROVIDED, DateTimeField from django.utils import timezone from django.utils.encoding import smart_text def track_field(field): """ Returns whether the given field should be tracked by Auditlog. Untracked fields are many-to-many relations and relations to the Auditlog LogEntry model. :param field: The field to check. :type field: Field :return: Whether the given field should be tracked. :rtype: bool """ from auditlog.models import LogEntry # Do not track many to many relations if field.many_to_many: return False # Do not track relations to LogEntry if getattr(field, 'remote_field', None) is not None and field.remote_field.model == LogEntry: return False # 1.8 check elif getattr(field, 'rel', None) is not None and field.rel.to == LogEntry: return False return True def get_fields_in_model(instance): """ Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: Model :return: The list of fields for the given model (instance) :rtype: list """ assert isinstance(instance, Model) # Check if the Django 1.8 _meta API is available use_api = hasattr(instance._meta, 'get_fields') and callable(instance._meta.get_fields) if use_api: return [f for f in instance._meta.get_fields() if track_field(f)] return instance._meta.fields def get_field_value(obj, field): """ Gets the value of a given model instance field. :param obj: The model instance. :type obj: Model :param field: The field you want to find the value of. :type field: Any :return: The value of the field as a string. :rtype: str """ if isinstance(field, DateTimeField): # DateTimeFields are timezone-aware, so we need to convert the field # to its naive form before we can accuratly compare them for changes. try: value = field.to_python(getattr(obj, field.name, None)) if value is not None and settings.USE_TZ and not timezone.is_naive(value): value = timezone.make_naive(value, timezone=timezone.utc) except ObjectDoesNotExist: value = field.default if field.default is not NOT_PROVIDED else None else: try: value = smart_text(getattr(obj, field.name, None)) except ObjectDoesNotExist: value = field.default if field.default is not NOT_PROVIDED else None return value
jjkester/django-auditlog
src/auditlog/compat.py
is_authenticated
python
def is_authenticated(user): if not hasattr(user, 'is_authenticated'): return False if callable(user.is_authenticated): # Will be callable if django.version < 2.0, but is only necessary in # v1.9 and earlier due to change introduced in v1.10 making # `is_authenticated` a property instead of a callable. return user.is_authenticated() else: return user.is_authenticated
Return whether or not a User is authenticated. Function provides compatibility following deprecation of method call to `is_authenticated()` in Django 2.0. This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier), as `is_authenticated` was introduced as a property in v1.10.s
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/compat.py#L3-L20
null
import django
jjkester/django-auditlog
src/auditlog/receivers.py
log_create
python
def log_create(sender, instance, created, **kwargs): if created: changes = model_instance_diff(None, instance) log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.CREATE, changes=json.dumps(changes), )
Signal receiver that creates a log entry when a model instance is first saved to the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/receivers.py#L9-L22
[ "def model_instance_diff(old, new):\n \"\"\"\n Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly\n created model or deleted model). This will cause all fields with a value to have changed (from ``None``).\n\n :param old: The old state of the model instance.\n :type old: Model\n :param new: The new state of the model instance.\n :type new: Model\n :return: A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values\n as value.\n :rtype: dict\n \"\"\"\n from auditlog.registry import auditlog\n\n if not(old is None or isinstance(old, Model)):\n raise TypeError(\"The supplied old instance is not a valid model instance.\")\n if not(new is None or isinstance(new, Model)):\n raise TypeError(\"The supplied new instance is not a valid model instance.\")\n\n diff = {}\n\n if old is not None and new is not None:\n fields = set(old._meta.fields + new._meta.fields)\n model_fields = auditlog.get_model_fields(new._meta.model)\n elif old is not None:\n fields = set(get_fields_in_model(old))\n model_fields = auditlog.get_model_fields(old._meta.model)\n elif new is not None:\n fields = set(get_fields_in_model(new))\n model_fields = auditlog.get_model_fields(new._meta.model)\n else:\n fields = set()\n model_fields = None\n\n # Check if fields must be filtered\n if model_fields and (model_fields['include_fields'] or model_fields['exclude_fields']) and fields:\n filtered_fields = []\n if model_fields['include_fields']:\n filtered_fields = [field for field in fields\n if field.name in model_fields['include_fields']]\n else:\n filtered_fields = fields\n if model_fields['exclude_fields']:\n filtered_fields = [field for field in filtered_fields\n if field.name not in model_fields['exclude_fields']]\n fields = filtered_fields\n\n for field in fields:\n old_value = get_field_value(old, field)\n new_value = get_field_value(new, field)\n\n if old_value != new_value:\n diff[field.name] = (smart_text(old_value), smart_text(new_value))\n\n if len(diff) == 0:\n diff = None\n\n return diff\n" ]
from __future__ import unicode_literals import json from auditlog.diff import model_instance_diff from auditlog.models import LogEntry def log_update(sender, instance, **kwargs): """ Signal receiver that creates a log entry when a model instance is changed and saved to the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ if instance.pk is not None: try: old = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass else: new = instance changes = model_instance_diff(old, new) # Log an entry only if there are changes if changes: log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.UPDATE, changes=json.dumps(changes), ) def log_delete(sender, instance, **kwargs): """ Signal receiver that creates a log entry when a model instance is deleted from the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ if instance.pk is not None: changes = model_instance_diff(instance, None) log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.DELETE, changes=json.dumps(changes), )
jjkester/django-auditlog
src/auditlog/receivers.py
log_update
python
def log_update(sender, instance, **kwargs): if instance.pk is not None: try: old = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass else: new = instance changes = model_instance_diff(old, new) # Log an entry only if there are changes if changes: log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.UPDATE, changes=json.dumps(changes), )
Signal receiver that creates a log entry when a model instance is changed and saved to the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/receivers.py#L25-L47
[ "def model_instance_diff(old, new):\n \"\"\"\n Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly\n created model or deleted model). This will cause all fields with a value to have changed (from ``None``).\n\n :param old: The old state of the model instance.\n :type old: Model\n :param new: The new state of the model instance.\n :type new: Model\n :return: A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values\n as value.\n :rtype: dict\n \"\"\"\n from auditlog.registry import auditlog\n\n if not(old is None or isinstance(old, Model)):\n raise TypeError(\"The supplied old instance is not a valid model instance.\")\n if not(new is None or isinstance(new, Model)):\n raise TypeError(\"The supplied new instance is not a valid model instance.\")\n\n diff = {}\n\n if old is not None and new is not None:\n fields = set(old._meta.fields + new._meta.fields)\n model_fields = auditlog.get_model_fields(new._meta.model)\n elif old is not None:\n fields = set(get_fields_in_model(old))\n model_fields = auditlog.get_model_fields(old._meta.model)\n elif new is not None:\n fields = set(get_fields_in_model(new))\n model_fields = auditlog.get_model_fields(new._meta.model)\n else:\n fields = set()\n model_fields = None\n\n # Check if fields must be filtered\n if model_fields and (model_fields['include_fields'] or model_fields['exclude_fields']) and fields:\n filtered_fields = []\n if model_fields['include_fields']:\n filtered_fields = [field for field in fields\n if field.name in model_fields['include_fields']]\n else:\n filtered_fields = fields\n if model_fields['exclude_fields']:\n filtered_fields = [field for field in filtered_fields\n if field.name not in model_fields['exclude_fields']]\n fields = filtered_fields\n\n for field in fields:\n old_value = get_field_value(old, field)\n new_value = get_field_value(new, field)\n\n if old_value != new_value:\n diff[field.name] = (smart_text(old_value), smart_text(new_value))\n\n if len(diff) == 0:\n diff = None\n\n return diff\n" ]
from __future__ import unicode_literals import json from auditlog.diff import model_instance_diff from auditlog.models import LogEntry def log_create(sender, instance, created, **kwargs): """ Signal receiver that creates a log entry when a model instance is first saved to the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ if created: changes = model_instance_diff(None, instance) log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.CREATE, changes=json.dumps(changes), ) def log_delete(sender, instance, **kwargs): """ Signal receiver that creates a log entry when a model instance is deleted from the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ if instance.pk is not None: changes = model_instance_diff(instance, None) log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.DELETE, changes=json.dumps(changes), )
jjkester/django-auditlog
src/auditlog/receivers.py
log_delete
python
def log_delete(sender, instance, **kwargs): if instance.pk is not None: changes = model_instance_diff(instance, None) log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.DELETE, changes=json.dumps(changes), )
Signal receiver that creates a log entry when a model instance is deleted from the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/receivers.py#L50-L63
[ "def model_instance_diff(old, new):\n \"\"\"\n Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly\n created model or deleted model). This will cause all fields with a value to have changed (from ``None``).\n\n :param old: The old state of the model instance.\n :type old: Model\n :param new: The new state of the model instance.\n :type new: Model\n :return: A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values\n as value.\n :rtype: dict\n \"\"\"\n from auditlog.registry import auditlog\n\n if not(old is None or isinstance(old, Model)):\n raise TypeError(\"The supplied old instance is not a valid model instance.\")\n if not(new is None or isinstance(new, Model)):\n raise TypeError(\"The supplied new instance is not a valid model instance.\")\n\n diff = {}\n\n if old is not None and new is not None:\n fields = set(old._meta.fields + new._meta.fields)\n model_fields = auditlog.get_model_fields(new._meta.model)\n elif old is not None:\n fields = set(get_fields_in_model(old))\n model_fields = auditlog.get_model_fields(old._meta.model)\n elif new is not None:\n fields = set(get_fields_in_model(new))\n model_fields = auditlog.get_model_fields(new._meta.model)\n else:\n fields = set()\n model_fields = None\n\n # Check if fields must be filtered\n if model_fields and (model_fields['include_fields'] or model_fields['exclude_fields']) and fields:\n filtered_fields = []\n if model_fields['include_fields']:\n filtered_fields = [field for field in fields\n if field.name in model_fields['include_fields']]\n else:\n filtered_fields = fields\n if model_fields['exclude_fields']:\n filtered_fields = [field for field in filtered_fields\n if field.name not in model_fields['exclude_fields']]\n fields = filtered_fields\n\n for field in fields:\n old_value = get_field_value(old, field)\n new_value = get_field_value(new, field)\n\n if old_value != new_value:\n diff[field.name] = (smart_text(old_value), smart_text(new_value))\n\n if len(diff) == 0:\n diff = None\n\n return diff\n" ]
from __future__ import unicode_literals import json from auditlog.diff import model_instance_diff from auditlog.models import LogEntry def log_create(sender, instance, created, **kwargs): """ Signal receiver that creates a log entry when a model instance is first saved to the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ if created: changes = model_instance_diff(None, instance) log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.CREATE, changes=json.dumps(changes), ) def log_update(sender, instance, **kwargs): """ Signal receiver that creates a log entry when a model instance is changed and saved to the database. Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ if instance.pk is not None: try: old = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass else: new = instance changes = model_instance_diff(old, new) # Log an entry only if there are changes if changes: log_entry = LogEntry.objects.log_create( instance, action=LogEntry.Action.UPDATE, changes=json.dumps(changes), )
jjkester/django-auditlog
src/auditlog/registry.py
AuditlogModelRegistry.register
python
def register(self, model=None, include_fields=[], exclude_fields=[], mapping_fields={}): def registrar(cls): """Register models for a given class.""" if not issubclass(cls, Model): raise TypeError("Supplied model is not a valid model.") self._registry[cls] = { 'include_fields': include_fields, 'exclude_fields': exclude_fields, 'mapping_fields': mapping_fields, } self._connect_signals(cls) # We need to return the class, as the decorator is basically # syntactic sugar for: # MyClass = auditlog.register(MyClass) return cls if model is None: # If we're being used as a decorator, return a callable with the # wrapper. return lambda cls: registrar(cls) else: # Otherwise, just register the model. registrar(model)
Register a model with auditlog. Auditlog will then track mutations on this model's instances. :param model: The model to register. :type model: Model :param include_fields: The fields to include. Implicitly excludes all other fields. :type include_fields: list :param exclude_fields: The fields to exclude. Overrides the fields to include. :type exclude_fields: list
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/registry.py#L28-L62
[ "def registrar(cls):\n \"\"\"Register models for a given class.\"\"\"\n if not issubclass(cls, Model):\n raise TypeError(\"Supplied model is not a valid model.\")\n\n self._registry[cls] = {\n 'include_fields': include_fields,\n 'exclude_fields': exclude_fields,\n 'mapping_fields': mapping_fields,\n }\n self._connect_signals(cls)\n\n # We need to return the class, as the decorator is basically\n # syntactic sugar for:\n # MyClass = auditlog.register(MyClass)\n return cls\n" ]
class AuditlogModelRegistry(object): """ A registry that keeps track of the models that use Auditlog to track changes. """ def __init__(self, create=True, update=True, delete=True, custom=None): from auditlog.receivers import log_create, log_update, log_delete self._registry = {} self._signals = {} if create: self._signals[post_save] = log_create if update: self._signals[pre_save] = log_update if delete: self._signals[post_delete] = log_delete if custom is not None: self._signals.update(custom) def contains(self, model): """ Check if a model is registered with auditlog. :param model: The model to check. :type model: Model :return: Whether the model has been registered. :rtype: bool """ return model in self._registry def unregister(self, model): """ Unregister a model with auditlog. This will not affect the database. :param model: The model to unregister. :type model: Model """ try: del self._registry[model] except KeyError: pass else: self._disconnect_signals(model) def _connect_signals(self, model): """ Connect signals for the model. """ for signal in self._signals: receiver = self._signals[signal] signal.connect(receiver, sender=model, dispatch_uid=self._dispatch_uid(signal, model)) def _disconnect_signals(self, model): """ Disconnect signals for the model. """ for signal, receiver in self._signals.items(): signal.disconnect(sender=model, dispatch_uid=self._dispatch_uid(signal, model)) def _dispatch_uid(self, signal, model): """ Generate a dispatch_uid. """ return (self.__class__, model, signal) def get_model_fields(self, model): return { 'include_fields': self._registry[model]['include_fields'], 'exclude_fields': self._registry[model]['exclude_fields'], 'mapping_fields': self._registry[model]['mapping_fields'], }
jjkester/django-auditlog
src/auditlog/registry.py
AuditlogModelRegistry._connect_signals
python
def _connect_signals(self, model): for signal in self._signals: receiver = self._signals[signal] signal.connect(receiver, sender=model, dispatch_uid=self._dispatch_uid(signal, model))
Connect signals for the model.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/registry.py#L89-L95
null
class AuditlogModelRegistry(object): """ A registry that keeps track of the models that use Auditlog to track changes. """ def __init__(self, create=True, update=True, delete=True, custom=None): from auditlog.receivers import log_create, log_update, log_delete self._registry = {} self._signals = {} if create: self._signals[post_save] = log_create if update: self._signals[pre_save] = log_update if delete: self._signals[post_delete] = log_delete if custom is not None: self._signals.update(custom) def register(self, model=None, include_fields=[], exclude_fields=[], mapping_fields={}): """ Register a model with auditlog. Auditlog will then track mutations on this model's instances. :param model: The model to register. :type model: Model :param include_fields: The fields to include. Implicitly excludes all other fields. :type include_fields: list :param exclude_fields: The fields to exclude. Overrides the fields to include. :type exclude_fields: list """ def registrar(cls): """Register models for a given class.""" if not issubclass(cls, Model): raise TypeError("Supplied model is not a valid model.") self._registry[cls] = { 'include_fields': include_fields, 'exclude_fields': exclude_fields, 'mapping_fields': mapping_fields, } self._connect_signals(cls) # We need to return the class, as the decorator is basically # syntactic sugar for: # MyClass = auditlog.register(MyClass) return cls if model is None: # If we're being used as a decorator, return a callable with the # wrapper. return lambda cls: registrar(cls) else: # Otherwise, just register the model. registrar(model) def contains(self, model): """ Check if a model is registered with auditlog. :param model: The model to check. :type model: Model :return: Whether the model has been registered. :rtype: bool """ return model in self._registry def unregister(self, model): """ Unregister a model with auditlog. This will not affect the database. :param model: The model to unregister. :type model: Model """ try: del self._registry[model] except KeyError: pass else: self._disconnect_signals(model) def _disconnect_signals(self, model): """ Disconnect signals for the model. """ for signal, receiver in self._signals.items(): signal.disconnect(sender=model, dispatch_uid=self._dispatch_uid(signal, model)) def _dispatch_uid(self, signal, model): """ Generate a dispatch_uid. """ return (self.__class__, model, signal) def get_model_fields(self, model): return { 'include_fields': self._registry[model]['include_fields'], 'exclude_fields': self._registry[model]['exclude_fields'], 'mapping_fields': self._registry[model]['mapping_fields'], }
jjkester/django-auditlog
src/auditlog/registry.py
AuditlogModelRegistry._disconnect_signals
python
def _disconnect_signals(self, model): for signal, receiver in self._signals.items(): signal.disconnect(sender=model, dispatch_uid=self._dispatch_uid(signal, model))
Disconnect signals for the model.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/registry.py#L97-L102
[ "def _dispatch_uid(self, signal, model):\n \"\"\"\n Generate a dispatch_uid.\n \"\"\"\n return (self.__class__, model, signal)\n" ]
class AuditlogModelRegistry(object): """ A registry that keeps track of the models that use Auditlog to track changes. """ def __init__(self, create=True, update=True, delete=True, custom=None): from auditlog.receivers import log_create, log_update, log_delete self._registry = {} self._signals = {} if create: self._signals[post_save] = log_create if update: self._signals[pre_save] = log_update if delete: self._signals[post_delete] = log_delete if custom is not None: self._signals.update(custom) def register(self, model=None, include_fields=[], exclude_fields=[], mapping_fields={}): """ Register a model with auditlog. Auditlog will then track mutations on this model's instances. :param model: The model to register. :type model: Model :param include_fields: The fields to include. Implicitly excludes all other fields. :type include_fields: list :param exclude_fields: The fields to exclude. Overrides the fields to include. :type exclude_fields: list """ def registrar(cls): """Register models for a given class.""" if not issubclass(cls, Model): raise TypeError("Supplied model is not a valid model.") self._registry[cls] = { 'include_fields': include_fields, 'exclude_fields': exclude_fields, 'mapping_fields': mapping_fields, } self._connect_signals(cls) # We need to return the class, as the decorator is basically # syntactic sugar for: # MyClass = auditlog.register(MyClass) return cls if model is None: # If we're being used as a decorator, return a callable with the # wrapper. return lambda cls: registrar(cls) else: # Otherwise, just register the model. registrar(model) def contains(self, model): """ Check if a model is registered with auditlog. :param model: The model to check. :type model: Model :return: Whether the model has been registered. :rtype: bool """ return model in self._registry def unregister(self, model): """ Unregister a model with auditlog. This will not affect the database. :param model: The model to unregister. :type model: Model """ try: del self._registry[model] except KeyError: pass else: self._disconnect_signals(model) def _connect_signals(self, model): """ Connect signals for the model. """ for signal in self._signals: receiver = self._signals[signal] signal.connect(receiver, sender=model, dispatch_uid=self._dispatch_uid(signal, model)) def _dispatch_uid(self, signal, model): """ Generate a dispatch_uid. """ return (self.__class__, model, signal) def get_model_fields(self, model): return { 'include_fields': self._registry[model]['include_fields'], 'exclude_fields': self._registry[model]['exclude_fields'], 'mapping_fields': self._registry[model]['mapping_fields'], }
jjkester/django-auditlog
src/auditlog/models.py
LogEntryManager.log_create
python
def log_create(self, instance, **kwargs): changes = kwargs.get('changes', None) pk = self._get_pk_value(instance) if changes is not None: kwargs.setdefault('content_type', ContentType.objects.get_for_model(instance)) kwargs.setdefault('object_pk', pk) kwargs.setdefault('object_repr', smart_text(instance)) if isinstance(pk, integer_types): kwargs.setdefault('object_id', pk) get_additional_data = getattr(instance, 'get_additional_data', None) if callable(get_additional_data): kwargs.setdefault('additional_data', get_additional_data()) # Delete log entries with the same pk as a newly created model. This should only be necessary when an pk is # used twice. if kwargs.get('action', None) is LogEntry.Action.CREATE: if kwargs.get('object_id', None) is not None and self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).exists(): self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).delete() else: self.filter(content_type=kwargs.get('content_type'), object_pk=kwargs.get('object_pk', '')).delete() # save LogEntry to same database instance is using db = instance._state.db return self.create(**kwargs) if db is None or db == '' else self.using(db).create(**kwargs) return None
Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given. :param instance: The model instance to log a change for. :type instance: Model :param kwargs: Field overrides for the :py:class:`LogEntry` object. :return: The new log entry or `None` if there were no changes. :rtype: LogEntry
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/models.py#L27-L63
[ "def _get_pk_value(self, instance):\n \"\"\"\n Get the primary key field value for a model instance.\n\n :param instance: The model instance to get the primary key for.\n :type instance: Model\n :return: The primary key value of the given model instance.\n \"\"\"\n pk_field = instance._meta.pk.name\n pk = getattr(instance, pk_field, None)\n\n # Check to make sure that we got an pk not a model object.\n if isinstance(pk, models.Model):\n pk = self._get_pk_value(pk)\n return pk\n" ]
class LogEntryManager(models.Manager): """ Custom manager for the :py:class:`LogEntry` model. """ def get_for_object(self, instance): """ Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet """ # Return empty queryset if the given model instance is not a model instance. if not isinstance(instance, models.Model): return self.none() content_type = ContentType.objects.get_for_model(instance.__class__) pk = self._get_pk_value(instance) if isinstance(pk, integer_types): return self.filter(content_type=content_type, object_id=pk) else: return self.filter(content_type=content_type, object_pk=smart_text(pk)) def get_for_objects(self, queryset): """ Get log entries for the objects in the specified queryset. :param queryset: The queryset to get the log entries for. :type queryset: QuerySet :return: The LogEntry objects for the objects in the given queryset. :rtype: QuerySet """ if not isinstance(queryset, QuerySet) or queryset.count() == 0: return self.none() content_type = ContentType.objects.get_for_model(queryset.model) primary_keys = list(queryset.values_list(queryset.model._meta.pk.name, flat=True)) if isinstance(primary_keys[0], integer_types): return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct() elif isinstance(queryset.model._meta.pk, models.UUIDField): primary_keys = [smart_text(pk) for pk in primary_keys] return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() else: return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() def get_for_model(self, model): """ Get log entries for all objects of a specified type. :param model: The model to get log entries for. :type model: class :return: QuerySet of log entries for the given model. :rtype: QuerySet """ # Return empty queryset if the given object is not valid. if not issubclass(model, models.Model): return self.none() content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type) def _get_pk_value(self, instance): """ Get the primary key field value for a model instance. :param instance: The model instance to get the primary key for. :type instance: Model :return: The primary key value of the given model instance. """ pk_field = instance._meta.pk.name pk = getattr(instance, pk_field, None) # Check to make sure that we got an pk not a model object. if isinstance(pk, models.Model): pk = self._get_pk_value(pk) return pk
jjkester/django-auditlog
src/auditlog/models.py
LogEntryManager.get_for_object
python
def get_for_object(self, instance): # Return empty queryset if the given model instance is not a model instance. if not isinstance(instance, models.Model): return self.none() content_type = ContentType.objects.get_for_model(instance.__class__) pk = self._get_pk_value(instance) if isinstance(pk, integer_types): return self.filter(content_type=content_type, object_id=pk) else: return self.filter(content_type=content_type, object_pk=smart_text(pk))
Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/models.py#L65-L84
[ "def _get_pk_value(self, instance):\n \"\"\"\n Get the primary key field value for a model instance.\n\n :param instance: The model instance to get the primary key for.\n :type instance: Model\n :return: The primary key value of the given model instance.\n \"\"\"\n pk_field = instance._meta.pk.name\n pk = getattr(instance, pk_field, None)\n\n # Check to make sure that we got an pk not a model object.\n if isinstance(pk, models.Model):\n pk = self._get_pk_value(pk)\n return pk\n" ]
class LogEntryManager(models.Manager): """ Custom manager for the :py:class:`LogEntry` model. """ def log_create(self, instance, **kwargs): """ Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given. :param instance: The model instance to log a change for. :type instance: Model :param kwargs: Field overrides for the :py:class:`LogEntry` object. :return: The new log entry or `None` if there were no changes. :rtype: LogEntry """ changes = kwargs.get('changes', None) pk = self._get_pk_value(instance) if changes is not None: kwargs.setdefault('content_type', ContentType.objects.get_for_model(instance)) kwargs.setdefault('object_pk', pk) kwargs.setdefault('object_repr', smart_text(instance)) if isinstance(pk, integer_types): kwargs.setdefault('object_id', pk) get_additional_data = getattr(instance, 'get_additional_data', None) if callable(get_additional_data): kwargs.setdefault('additional_data', get_additional_data()) # Delete log entries with the same pk as a newly created model. This should only be necessary when an pk is # used twice. if kwargs.get('action', None) is LogEntry.Action.CREATE: if kwargs.get('object_id', None) is not None and self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).exists(): self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).delete() else: self.filter(content_type=kwargs.get('content_type'), object_pk=kwargs.get('object_pk', '')).delete() # save LogEntry to same database instance is using db = instance._state.db return self.create(**kwargs) if db is None or db == '' else self.using(db).create(**kwargs) return None def get_for_objects(self, queryset): """ Get log entries for the objects in the specified queryset. :param queryset: The queryset to get the log entries for. :type queryset: QuerySet :return: The LogEntry objects for the objects in the given queryset. :rtype: QuerySet """ if not isinstance(queryset, QuerySet) or queryset.count() == 0: return self.none() content_type = ContentType.objects.get_for_model(queryset.model) primary_keys = list(queryset.values_list(queryset.model._meta.pk.name, flat=True)) if isinstance(primary_keys[0], integer_types): return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct() elif isinstance(queryset.model._meta.pk, models.UUIDField): primary_keys = [smart_text(pk) for pk in primary_keys] return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() else: return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() def get_for_model(self, model): """ Get log entries for all objects of a specified type. :param model: The model to get log entries for. :type model: class :return: QuerySet of log entries for the given model. :rtype: QuerySet """ # Return empty queryset if the given object is not valid. if not issubclass(model, models.Model): return self.none() content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type) def _get_pk_value(self, instance): """ Get the primary key field value for a model instance. :param instance: The model instance to get the primary key for. :type instance: Model :return: The primary key value of the given model instance. """ pk_field = instance._meta.pk.name pk = getattr(instance, pk_field, None) # Check to make sure that we got an pk not a model object. if isinstance(pk, models.Model): pk = self._get_pk_value(pk) return pk
jjkester/django-auditlog
src/auditlog/models.py
LogEntryManager.get_for_objects
python
def get_for_objects(self, queryset): if not isinstance(queryset, QuerySet) or queryset.count() == 0: return self.none() content_type = ContentType.objects.get_for_model(queryset.model) primary_keys = list(queryset.values_list(queryset.model._meta.pk.name, flat=True)) if isinstance(primary_keys[0], integer_types): return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct() elif isinstance(queryset.model._meta.pk, models.UUIDField): primary_keys = [smart_text(pk) for pk in primary_keys] return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() else: return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct()
Get log entries for the objects in the specified queryset. :param queryset: The queryset to get the log entries for. :type queryset: QuerySet :return: The LogEntry objects for the objects in the given queryset. :rtype: QuerySet
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/models.py#L86-L107
null
class LogEntryManager(models.Manager): """ Custom manager for the :py:class:`LogEntry` model. """ def log_create(self, instance, **kwargs): """ Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given. :param instance: The model instance to log a change for. :type instance: Model :param kwargs: Field overrides for the :py:class:`LogEntry` object. :return: The new log entry or `None` if there were no changes. :rtype: LogEntry """ changes = kwargs.get('changes', None) pk = self._get_pk_value(instance) if changes is not None: kwargs.setdefault('content_type', ContentType.objects.get_for_model(instance)) kwargs.setdefault('object_pk', pk) kwargs.setdefault('object_repr', smart_text(instance)) if isinstance(pk, integer_types): kwargs.setdefault('object_id', pk) get_additional_data = getattr(instance, 'get_additional_data', None) if callable(get_additional_data): kwargs.setdefault('additional_data', get_additional_data()) # Delete log entries with the same pk as a newly created model. This should only be necessary when an pk is # used twice. if kwargs.get('action', None) is LogEntry.Action.CREATE: if kwargs.get('object_id', None) is not None and self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).exists(): self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).delete() else: self.filter(content_type=kwargs.get('content_type'), object_pk=kwargs.get('object_pk', '')).delete() # save LogEntry to same database instance is using db = instance._state.db return self.create(**kwargs) if db is None or db == '' else self.using(db).create(**kwargs) return None def get_for_object(self, instance): """ Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet """ # Return empty queryset if the given model instance is not a model instance. if not isinstance(instance, models.Model): return self.none() content_type = ContentType.objects.get_for_model(instance.__class__) pk = self._get_pk_value(instance) if isinstance(pk, integer_types): return self.filter(content_type=content_type, object_id=pk) else: return self.filter(content_type=content_type, object_pk=smart_text(pk)) def get_for_model(self, model): """ Get log entries for all objects of a specified type. :param model: The model to get log entries for. :type model: class :return: QuerySet of log entries for the given model. :rtype: QuerySet """ # Return empty queryset if the given object is not valid. if not issubclass(model, models.Model): return self.none() content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type) def _get_pk_value(self, instance): """ Get the primary key field value for a model instance. :param instance: The model instance to get the primary key for. :type instance: Model :return: The primary key value of the given model instance. """ pk_field = instance._meta.pk.name pk = getattr(instance, pk_field, None) # Check to make sure that we got an pk not a model object. if isinstance(pk, models.Model): pk = self._get_pk_value(pk) return pk
jjkester/django-auditlog
src/auditlog/models.py
LogEntryManager.get_for_model
python
def get_for_model(self, model): # Return empty queryset if the given object is not valid. if not issubclass(model, models.Model): return self.none() content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type)
Get log entries for all objects of a specified type. :param model: The model to get log entries for. :type model: class :return: QuerySet of log entries for the given model. :rtype: QuerySet
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/models.py#L109-L124
null
class LogEntryManager(models.Manager): """ Custom manager for the :py:class:`LogEntry` model. """ def log_create(self, instance, **kwargs): """ Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given. :param instance: The model instance to log a change for. :type instance: Model :param kwargs: Field overrides for the :py:class:`LogEntry` object. :return: The new log entry or `None` if there were no changes. :rtype: LogEntry """ changes = kwargs.get('changes', None) pk = self._get_pk_value(instance) if changes is not None: kwargs.setdefault('content_type', ContentType.objects.get_for_model(instance)) kwargs.setdefault('object_pk', pk) kwargs.setdefault('object_repr', smart_text(instance)) if isinstance(pk, integer_types): kwargs.setdefault('object_id', pk) get_additional_data = getattr(instance, 'get_additional_data', None) if callable(get_additional_data): kwargs.setdefault('additional_data', get_additional_data()) # Delete log entries with the same pk as a newly created model. This should only be necessary when an pk is # used twice. if kwargs.get('action', None) is LogEntry.Action.CREATE: if kwargs.get('object_id', None) is not None and self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).exists(): self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).delete() else: self.filter(content_type=kwargs.get('content_type'), object_pk=kwargs.get('object_pk', '')).delete() # save LogEntry to same database instance is using db = instance._state.db return self.create(**kwargs) if db is None or db == '' else self.using(db).create(**kwargs) return None def get_for_object(self, instance): """ Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet """ # Return empty queryset if the given model instance is not a model instance. if not isinstance(instance, models.Model): return self.none() content_type = ContentType.objects.get_for_model(instance.__class__) pk = self._get_pk_value(instance) if isinstance(pk, integer_types): return self.filter(content_type=content_type, object_id=pk) else: return self.filter(content_type=content_type, object_pk=smart_text(pk)) def get_for_objects(self, queryset): """ Get log entries for the objects in the specified queryset. :param queryset: The queryset to get the log entries for. :type queryset: QuerySet :return: The LogEntry objects for the objects in the given queryset. :rtype: QuerySet """ if not isinstance(queryset, QuerySet) or queryset.count() == 0: return self.none() content_type = ContentType.objects.get_for_model(queryset.model) primary_keys = list(queryset.values_list(queryset.model._meta.pk.name, flat=True)) if isinstance(primary_keys[0], integer_types): return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct() elif isinstance(queryset.model._meta.pk, models.UUIDField): primary_keys = [smart_text(pk) for pk in primary_keys] return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() else: return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() def _get_pk_value(self, instance): """ Get the primary key field value for a model instance. :param instance: The model instance to get the primary key for. :type instance: Model :return: The primary key value of the given model instance. """ pk_field = instance._meta.pk.name pk = getattr(instance, pk_field, None) # Check to make sure that we got an pk not a model object. if isinstance(pk, models.Model): pk = self._get_pk_value(pk) return pk
jjkester/django-auditlog
src/auditlog/models.py
LogEntryManager._get_pk_value
python
def _get_pk_value(self, instance): pk_field = instance._meta.pk.name pk = getattr(instance, pk_field, None) # Check to make sure that we got an pk not a model object. if isinstance(pk, models.Model): pk = self._get_pk_value(pk) return pk
Get the primary key field value for a model instance. :param instance: The model instance to get the primary key for. :type instance: Model :return: The primary key value of the given model instance.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/models.py#L126-L140
[ "def _get_pk_value(self, instance):\n \"\"\"\n Get the primary key field value for a model instance.\n\n :param instance: The model instance to get the primary key for.\n :type instance: Model\n :return: The primary key value of the given model instance.\n \"\"\"\n pk_field = instance._meta.pk.name\n pk = getattr(instance, pk_field, None)\n\n # Check to make sure that we got an pk not a model object.\n if isinstance(pk, models.Model):\n pk = self._get_pk_value(pk)\n return pk\n" ]
class LogEntryManager(models.Manager): """ Custom manager for the :py:class:`LogEntry` model. """ def log_create(self, instance, **kwargs): """ Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given. :param instance: The model instance to log a change for. :type instance: Model :param kwargs: Field overrides for the :py:class:`LogEntry` object. :return: The new log entry or `None` if there were no changes. :rtype: LogEntry """ changes = kwargs.get('changes', None) pk = self._get_pk_value(instance) if changes is not None: kwargs.setdefault('content_type', ContentType.objects.get_for_model(instance)) kwargs.setdefault('object_pk', pk) kwargs.setdefault('object_repr', smart_text(instance)) if isinstance(pk, integer_types): kwargs.setdefault('object_id', pk) get_additional_data = getattr(instance, 'get_additional_data', None) if callable(get_additional_data): kwargs.setdefault('additional_data', get_additional_data()) # Delete log entries with the same pk as a newly created model. This should only be necessary when an pk is # used twice. if kwargs.get('action', None) is LogEntry.Action.CREATE: if kwargs.get('object_id', None) is not None and self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).exists(): self.filter(content_type=kwargs.get('content_type'), object_id=kwargs.get('object_id')).delete() else: self.filter(content_type=kwargs.get('content_type'), object_pk=kwargs.get('object_pk', '')).delete() # save LogEntry to same database instance is using db = instance._state.db return self.create(**kwargs) if db is None or db == '' else self.using(db).create(**kwargs) return None def get_for_object(self, instance): """ Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet """ # Return empty queryset if the given model instance is not a model instance. if not isinstance(instance, models.Model): return self.none() content_type = ContentType.objects.get_for_model(instance.__class__) pk = self._get_pk_value(instance) if isinstance(pk, integer_types): return self.filter(content_type=content_type, object_id=pk) else: return self.filter(content_type=content_type, object_pk=smart_text(pk)) def get_for_objects(self, queryset): """ Get log entries for the objects in the specified queryset. :param queryset: The queryset to get the log entries for. :type queryset: QuerySet :return: The LogEntry objects for the objects in the given queryset. :rtype: QuerySet """ if not isinstance(queryset, QuerySet) or queryset.count() == 0: return self.none() content_type = ContentType.objects.get_for_model(queryset.model) primary_keys = list(queryset.values_list(queryset.model._meta.pk.name, flat=True)) if isinstance(primary_keys[0], integer_types): return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct() elif isinstance(queryset.model._meta.pk, models.UUIDField): primary_keys = [smart_text(pk) for pk in primary_keys] return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() else: return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() def get_for_model(self, model): """ Get log entries for all objects of a specified type. :param model: The model to get log entries for. :type model: class :return: QuerySet of log entries for the given model. :rtype: QuerySet """ # Return empty queryset if the given object is not valid. if not issubclass(model, models.Model): return self.none() content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type)
jjkester/django-auditlog
src/auditlog/models.py
AuditlogHistoryField.bulk_related_objects
python
def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): if self.delete_related: return super(AuditlogHistoryField, self).bulk_related_objects(objs, using) # When deleting, Collector.collect() finds related objects using this # method. However, because we don't want to delete these related # objects, we simply return an empty list. return []
Return all objects related to ``objs`` via this ``GenericRelation``.
train
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/models.py#L342-L352
null
class AuditlogHistoryField(GenericRelation): """ A subclass of py:class:`django.contrib.contenttypes.fields.GenericRelation` that sets some default variables. This makes it easier to access Auditlog's log entries, for example in templates. By default this field will assume that your primary keys are numeric, simply because this is the most common case. However, if you have a non-integer primary key, you can simply pass ``pk_indexable=False`` to the constructor, and Auditlog will fall back to using a non-indexed text based field for this model. Using this field will not automatically register the model for automatic logging. This is done so you can be more flexible with how you use this field. :param pk_indexable: Whether the primary key for this model is not an :py:class:`int` or :py:class:`long`. :type pk_indexable: bool :param delete_related: By default, including a generic relation into a model will cause all related objects to be cascade-deleted when the parent object is deleted. Passing False to this overrides this behavior, retaining the full auditlog history for the object. Defaults to True, because that's Django's default behavior. :type delete_related: bool """ def __init__(self, pk_indexable=True, delete_related=True, **kwargs): kwargs['to'] = LogEntry if pk_indexable: kwargs['object_id_field'] = 'object_id' else: kwargs['object_id_field'] = 'object_pk' kwargs['content_type_field'] = 'content_type' self.delete_related = delete_related super(AuditlogHistoryField, self).__init__(**kwargs)
da4089/simplefix
simplefix/parser.py
FixParser.add_raw
python
def add_raw(self, length_tag, value_tag): self.raw_len_tags.append(length_tag) self.raw_data_tags.append(value_tag) return
Define the tags used for a private raw data field. :param length_tag: tag number of length field. :param value_tag: tag number of value field. Data fields are not terminated by the SOH character as is usual for FIX, but instead have a second, preceding field that specifies the length of the value in bytes. The parser is initialised with all the data fields defined in FIX.5.0, but if your application uses private data fields, you can add them here, and the parser will process them correctly.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/parser.py#L65-L80
null
class FixParser(object): """FIX protocol message parser. This class translates FIX application messages in raw (wire) format into instance of the FixMessage class. It does not perform any validation of the fields, their presence or absence in a particular message, the data types of fields, or the values of enumerations. It is suitable for streaming processing, accumulating byte data from a network connection, and returning complete messages as they are delivered, potentially in multiple fragments.""" def __init__(self): """Constructor.""" # Internal buffer used to accumulate message data. self.buf = b"" # Parsed "tag=value" pairs, removed from the buffer, but not # yet returned as a message. self.pairs = [] # Copy raw field length tags. self.raw_len_tags = RAW_LEN_TAGS[:] # Copy raw field data tags. self.raw_data_tags = RAW_DATA_TAGS[:] # Parsed length of data field. self.raw_len = 0 return def remove_raw(self, length_tag, value_tag): """Remove the tags for a data type field. :param length_tag: tag number of the length field. :param value_tag: tag number of the value field. You can remove either private or standard data field definitions in case a particular application uses them for a field of a different type. """ self.raw_len_tags.remove(length_tag) self.raw_data_tags.remove(value_tag) return def reset(self): """Reset the internal parser state. This will discard any appended buffer content, and any fields parsed so far.""" self.buf = b"" self.pairs = [] self.raw_len = 0 return def append_buffer(self, buf): """Append a byte string to the parser buffer. :param buf: byte string to append. The parser maintains an internal buffer of bytes to be parsed. As raw data is read, it can be appended to this buffer. Each call to get_message() will try to remove the bytes of a complete messages from the head of the buffer.""" self.buf += fix_val(buf) return def get_buffer(self): """Return a reference to the internal buffer.""" return self.buf def get_message(self): """Process the accumulated buffer and return the first message. If the buffer starts with FIX fields other than BeginString (8), these are discarded until the start of a message is found. If no BeginString (8) field is found, this function returns None. Similarly, if (after a BeginString) no Checksum (10) field is found, the function returns None. Otherwise, it returns a simplefix.FixMessage instance initialised with the fields from the first complete message found in the buffer.""" # Break buffer into tag=value pairs. start = 0 point = 0 in_tag = True tag = 0 while point < len(self.buf): if in_tag and self.buf[point] == EQUALS_BYTE: tag_string = self.buf[start:point] point += 1 tag = int(tag_string) if tag in self.raw_data_tags and self.raw_len > 0: if self.raw_len > len(self.buf) - point: break value = self.buf[point:point + self.raw_len] self.pairs.append((tag, value)) self.buf = self.buf[point + self.raw_len + 1:] point = 0 self.raw_len = 0 start = point else: in_tag = False start = point elif self.buf[point] == SOH_BYTE: value = self.buf[start:point] self.pairs.append((tag, value)) self.buf = self.buf[point + 1:] point = 0 start = point in_tag = True if tag in self.raw_len_tags: self.raw_len = int(value) point += 1 if len(self.pairs) == 0: return None # Check first pair is FIX BeginString. while self.pairs and self.pairs[0][0] != 8: # Discard pairs until we find the beginning of a message. self.pairs.pop(0) if len(self.pairs) == 0: return None # Look for checksum. index = 0 while index < len(self.pairs) and self.pairs[index][0] != 10: index += 1 if index == len(self.pairs): return None # Found checksum, so we have a complete message. m = FixMessage() pairs = self.pairs[:index + 1] for tag, value in pairs: m.append_pair(tag, value) self.pairs = self.pairs[index + 1:] return m
da4089/simplefix
simplefix/parser.py
FixParser.remove_raw
python
def remove_raw(self, length_tag, value_tag): self.raw_len_tags.remove(length_tag) self.raw_data_tags.remove(value_tag) return
Remove the tags for a data type field. :param length_tag: tag number of the length field. :param value_tag: tag number of the value field. You can remove either private or standard data field definitions in case a particular application uses them for a field of a different type.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/parser.py#L82-L94
null
class FixParser(object): """FIX protocol message parser. This class translates FIX application messages in raw (wire) format into instance of the FixMessage class. It does not perform any validation of the fields, their presence or absence in a particular message, the data types of fields, or the values of enumerations. It is suitable for streaming processing, accumulating byte data from a network connection, and returning complete messages as they are delivered, potentially in multiple fragments.""" def __init__(self): """Constructor.""" # Internal buffer used to accumulate message data. self.buf = b"" # Parsed "tag=value" pairs, removed from the buffer, but not # yet returned as a message. self.pairs = [] # Copy raw field length tags. self.raw_len_tags = RAW_LEN_TAGS[:] # Copy raw field data tags. self.raw_data_tags = RAW_DATA_TAGS[:] # Parsed length of data field. self.raw_len = 0 return def add_raw(self, length_tag, value_tag): """Define the tags used for a private raw data field. :param length_tag: tag number of length field. :param value_tag: tag number of value field. Data fields are not terminated by the SOH character as is usual for FIX, but instead have a second, preceding field that specifies the length of the value in bytes. The parser is initialised with all the data fields defined in FIX.5.0, but if your application uses private data fields, you can add them here, and the parser will process them correctly. """ self.raw_len_tags.append(length_tag) self.raw_data_tags.append(value_tag) return def reset(self): """Reset the internal parser state. This will discard any appended buffer content, and any fields parsed so far.""" self.buf = b"" self.pairs = [] self.raw_len = 0 return def append_buffer(self, buf): """Append a byte string to the parser buffer. :param buf: byte string to append. The parser maintains an internal buffer of bytes to be parsed. As raw data is read, it can be appended to this buffer. Each call to get_message() will try to remove the bytes of a complete messages from the head of the buffer.""" self.buf += fix_val(buf) return def get_buffer(self): """Return a reference to the internal buffer.""" return self.buf def get_message(self): """Process the accumulated buffer and return the first message. If the buffer starts with FIX fields other than BeginString (8), these are discarded until the start of a message is found. If no BeginString (8) field is found, this function returns None. Similarly, if (after a BeginString) no Checksum (10) field is found, the function returns None. Otherwise, it returns a simplefix.FixMessage instance initialised with the fields from the first complete message found in the buffer.""" # Break buffer into tag=value pairs. start = 0 point = 0 in_tag = True tag = 0 while point < len(self.buf): if in_tag and self.buf[point] == EQUALS_BYTE: tag_string = self.buf[start:point] point += 1 tag = int(tag_string) if tag in self.raw_data_tags and self.raw_len > 0: if self.raw_len > len(self.buf) - point: break value = self.buf[point:point + self.raw_len] self.pairs.append((tag, value)) self.buf = self.buf[point + self.raw_len + 1:] point = 0 self.raw_len = 0 start = point else: in_tag = False start = point elif self.buf[point] == SOH_BYTE: value = self.buf[start:point] self.pairs.append((tag, value)) self.buf = self.buf[point + 1:] point = 0 start = point in_tag = True if tag in self.raw_len_tags: self.raw_len = int(value) point += 1 if len(self.pairs) == 0: return None # Check first pair is FIX BeginString. while self.pairs and self.pairs[0][0] != 8: # Discard pairs until we find the beginning of a message. self.pairs.pop(0) if len(self.pairs) == 0: return None # Look for checksum. index = 0 while index < len(self.pairs) and self.pairs[index][0] != 10: index += 1 if index == len(self.pairs): return None # Found checksum, so we have a complete message. m = FixMessage() pairs = self.pairs[:index + 1] for tag, value in pairs: m.append_pair(tag, value) self.pairs = self.pairs[index + 1:] return m
da4089/simplefix
simplefix/parser.py
FixParser.get_message
python
def get_message(self): # Break buffer into tag=value pairs. start = 0 point = 0 in_tag = True tag = 0 while point < len(self.buf): if in_tag and self.buf[point] == EQUALS_BYTE: tag_string = self.buf[start:point] point += 1 tag = int(tag_string) if tag in self.raw_data_tags and self.raw_len > 0: if self.raw_len > len(self.buf) - point: break value = self.buf[point:point + self.raw_len] self.pairs.append((tag, value)) self.buf = self.buf[point + self.raw_len + 1:] point = 0 self.raw_len = 0 start = point else: in_tag = False start = point elif self.buf[point] == SOH_BYTE: value = self.buf[start:point] self.pairs.append((tag, value)) self.buf = self.buf[point + 1:] point = 0 start = point in_tag = True if tag in self.raw_len_tags: self.raw_len = int(value) point += 1 if len(self.pairs) == 0: return None # Check first pair is FIX BeginString. while self.pairs and self.pairs[0][0] != 8: # Discard pairs until we find the beginning of a message. self.pairs.pop(0) if len(self.pairs) == 0: return None # Look for checksum. index = 0 while index < len(self.pairs) and self.pairs[index][0] != 10: index += 1 if index == len(self.pairs): return None # Found checksum, so we have a complete message. m = FixMessage() pairs = self.pairs[:index + 1] for tag, value in pairs: m.append_pair(tag, value) self.pairs = self.pairs[index + 1:] return m
Process the accumulated buffer and return the first message. If the buffer starts with FIX fields other than BeginString (8), these are discarded until the start of a message is found. If no BeginString (8) field is found, this function returns None. Similarly, if (after a BeginString) no Checksum (10) field is found, the function returns None. Otherwise, it returns a simplefix.FixMessage instance initialised with the fields from the first complete message found in the buffer.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/parser.py#L123-L204
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n" ]
class FixParser(object): """FIX protocol message parser. This class translates FIX application messages in raw (wire) format into instance of the FixMessage class. It does not perform any validation of the fields, their presence or absence in a particular message, the data types of fields, or the values of enumerations. It is suitable for streaming processing, accumulating byte data from a network connection, and returning complete messages as they are delivered, potentially in multiple fragments.""" def __init__(self): """Constructor.""" # Internal buffer used to accumulate message data. self.buf = b"" # Parsed "tag=value" pairs, removed from the buffer, but not # yet returned as a message. self.pairs = [] # Copy raw field length tags. self.raw_len_tags = RAW_LEN_TAGS[:] # Copy raw field data tags. self.raw_data_tags = RAW_DATA_TAGS[:] # Parsed length of data field. self.raw_len = 0 return def add_raw(self, length_tag, value_tag): """Define the tags used for a private raw data field. :param length_tag: tag number of length field. :param value_tag: tag number of value field. Data fields are not terminated by the SOH character as is usual for FIX, but instead have a second, preceding field that specifies the length of the value in bytes. The parser is initialised with all the data fields defined in FIX.5.0, but if your application uses private data fields, you can add them here, and the parser will process them correctly. """ self.raw_len_tags.append(length_tag) self.raw_data_tags.append(value_tag) return def remove_raw(self, length_tag, value_tag): """Remove the tags for a data type field. :param length_tag: tag number of the length field. :param value_tag: tag number of the value field. You can remove either private or standard data field definitions in case a particular application uses them for a field of a different type. """ self.raw_len_tags.remove(length_tag) self.raw_data_tags.remove(value_tag) return def reset(self): """Reset the internal parser state. This will discard any appended buffer content, and any fields parsed so far.""" self.buf = b"" self.pairs = [] self.raw_len = 0 return def append_buffer(self, buf): """Append a byte string to the parser buffer. :param buf: byte string to append. The parser maintains an internal buffer of bytes to be parsed. As raw data is read, it can be appended to this buffer. Each call to get_message() will try to remove the bytes of a complete messages from the head of the buffer.""" self.buf += fix_val(buf) return def get_buffer(self): """Return a reference to the internal buffer.""" return self.buf
da4089/simplefix
simplefix/message.py
fix_val
python
def fix_val(value): if type(value) == bytes: return value if sys.version_info[0] == 2: return bytes(value) elif type(value) == str: return bytes(value, 'UTF-8') else: return bytes(str(value), 'ASCII')
Make a FIX value from a string, bytes, or number.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L45-L55
null
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016-2018, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## # Implements generic FIX protocol. # # Each message is a collection of tag+value pairs. Tags are integers, # but values are converted to strings when they're set (if not # before). The pairs are maintained in order of creation. Duplicates # and repeating groups are allowed. # # If tags 8, 9 or 10 are not supplied, they will be automatically # added in the correct location, and with correct values. You can # supply these tags in the wrong order for testing error handling. import datetime import sys import time import warnings from .constants import SOH_STR def fix_tag(value): """Make a FIX tag value from string, bytes, or integer.""" if sys.version_info[0] == 2: return bytes(value) else: if type(value) == bytes: return value elif type(value) == str: return value.encode('ASCII') return str(value).encode('ASCII') class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s ########################################################################
da4089/simplefix
simplefix/message.py
fix_tag
python
def fix_tag(value): if sys.version_info[0] == 2: return bytes(value) else: if type(value) == bytes: return value elif type(value) == str: return value.encode('ASCII') return str(value).encode('ASCII')
Make a FIX tag value from string, bytes, or integer.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L58-L67
null
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016-2018, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## # Implements generic FIX protocol. # # Each message is a collection of tag+value pairs. Tags are integers, # but values are converted to strings when they're set (if not # before). The pairs are maintained in order of creation. Duplicates # and repeating groups are allowed. # # If tags 8, 9 or 10 are not supplied, they will be automatically # added in the correct location, and with correct values. You can # supply these tags in the wrong order for testing error handling. import datetime import sys import time import warnings from .constants import SOH_STR def fix_val(value): """Make a FIX value from a string, bytes, or number.""" if type(value) == bytes: return value if sys.version_info[0] == 2: return bytes(value) elif type(value) == str: return bytes(value, 'UTF-8') else: return bytes(str(value), 'ASCII') class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s ########################################################################
da4089/simplefix
simplefix/message.py
FixMessage.append_pair
python
def append_pair(self, tag, value, header=False): if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return
Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L95-L125
[ "def fix_val(value):\n \"\"\"Make a FIX value from a string, bytes, or number.\"\"\"\n if type(value) == bytes:\n return value\n\n if sys.version_info[0] == 2:\n return bytes(value)\n elif type(value) == str:\n return bytes(value, 'UTF-8')\n else:\n return bytes(str(value), 'ASCII')\n", "def fix_tag(value):\n \"\"\"Make a FIX tag value from string, bytes, or integer.\"\"\"\n if sys.version_info[0] == 2:\n return bytes(value)\n else:\n if type(value) == bytes:\n return value\n elif type(value) == str:\n return value.encode('ASCII')\n return str(value).encode('ASCII')\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_time
python
def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header)
Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L127-L170
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage._append_utc_datetime
python
def _append_utc_datetime(self, tag, format, ts, precision, header): if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header)
(Internal) Append formatted datetime.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L172-L190
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_utc_timestamp
python
def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header)
Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L192-L215
[ "def _append_utc_datetime(self, tag, format, ts, precision, header):\n \"\"\"(Internal) Append formatted datetime.\"\"\"\n\n if ts is None:\n t = datetime.datetime.utcnow()\n elif type(ts) is float:\n t = datetime.datetime.utcfromtimestamp(ts)\n else:\n t = ts\n\n s = t.strftime(format)\n if precision == 3:\n s += \".%03d\" % (t.microsecond / 1000)\n elif precision == 6:\n s += \".%06d\" % t.microsecond\n elif precision != 0:\n raise ValueError(\"Precision should be one of 0, 3 or 6 digits\")\n\n return self.append_pair(tag, s, header=header)\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_utc_time_only
python
def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header)
Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L217-L240
[ "def _append_utc_datetime(self, tag, format, ts, precision, header):\n \"\"\"(Internal) Append formatted datetime.\"\"\"\n\n if ts is None:\n t = datetime.datetime.utcnow()\n elif type(ts) is float:\n t = datetime.datetime.utcfromtimestamp(ts)\n else:\n t = ts\n\n s = t.strftime(format)\n if precision == 3:\n s += \".%03d\" % (t.microsecond / 1000)\n elif precision == 6:\n s += \".%06d\" % t.microsecond\n elif precision != 0:\n raise ValueError(\"Precision should be one of 0, 3 or 6 digits\")\n\n return self.append_pair(tag, s, header=header)\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_tz_timestamp
python
def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header)
Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L290-L334
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n", "def _tz_offset_string(offset):\n \"\"\"(Internal) Convert TZ offset in minutes east to string.\"\"\"\n\n s = \"\"\n io = int(offset)\n if io == 0:\n s += \"Z\"\n else:\n if -1440 < io < 1440:\n ho = abs(io) / 60\n mo = abs(io) % 60\n\n s += \"%c%02u\" % (\"+\" if io > 0 else \"-\", ho)\n if mo != 0:\n s += \":%02u\" % mo\n\n else:\n raise ValueError(\"Timezone `offset` (%u) out of range \"\n \"-1439 to +1439 minutes\" % io)\n return s\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_tz_time_only
python
def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header)
Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L336-L382
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n", "def _tz_offset_string(offset):\n \"\"\"(Internal) Convert TZ offset in minutes east to string.\"\"\"\n\n s = \"\"\n io = int(offset)\n if io == 0:\n s += \"Z\"\n else:\n if -1440 < io < 1440:\n ho = abs(io) / 60\n mo = abs(io) % 60\n\n s += \"%c%02u\" % (\"+\" if io > 0 else \"-\", ho)\n if mo != 0:\n s += \":%02u\" % mo\n\n else:\n raise ValueError(\"Timezone `offset` (%u) out of range \"\n \"-1439 to +1439 minutes\" % io)\n return s\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_tz_time_only_parts
python
def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header)
Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L384-L436
null
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_string
python
def append_string(self, field, header=False): # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return
Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L438-L460
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_strings
python
def append_strings(self, string_list, header=False): for s in string_list: self.append_string(s, header=header) return
Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L462-L473
[ "def append_string(self, field, header=False):\n \"\"\"Append a tag=value pair in string format.\n\n :param field: String \"tag=value\" to be appended to this message.\n :param header: Append to header if True; default to body.\n\n The string is split at the first '=' character, and the resulting\n tag and value strings are appended to the message.\"\"\"\n\n # Split into tag and value.\n bits = field.split('=', 1)\n if len(bits) != 2:\n raise ValueError(\"Field missing '=' separator.\")\n\n # Check tag is an integer.\n try:\n tag_int = int(bits[0])\n except ValueError:\n raise ValueError(\"Tag value must be an integer\")\n\n # Save.\n self.append_pair(tag_int, bits[1], header=header)\n return\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.append_data
python
def append_data(self, len_tag, val_tag, data, header=False): self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return
Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L475-L489
[ "def append_pair(self, tag, value, header=False):\n \"\"\"Append a tag=value pair to this message.\n\n :param tag: Integer or string FIX tag number.\n :param value: FIX tag value.\n :param header: Append to header if True; default to body.\n\n Both parameters are explicitly converted to strings before\n storage, so it's ok to pass integers if that's easier for\n your program logic.\n\n Note: a Python 'None' value will be silently ignored, and\n no field is appended.\"\"\"\n\n if tag is None or value is None:\n return\n\n if int(tag) == 8:\n self.begin_string = fix_val(value)\n\n if int(tag) == 35:\n self.message_type = fix_val(value)\n\n if header:\n self.pairs.insert(self.header_index,\n (fix_tag(tag),\n fix_val(value)))\n self.header_index += 1\n else:\n self.pairs.append((fix_tag(tag), fix_val(value)))\n return\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.get
python
def get(self, tag, nth=1): tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None
Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L491-L510
[ "def fix_tag(value):\n \"\"\"Make a FIX tag value from string, bytes, or integer.\"\"\"\n if sys.version_info[0] == 2:\n return bytes(value)\n else:\n if type(value) == bytes:\n return value\n elif type(value) == str:\n return value.encode('ASCII')\n return str(value).encode('ASCII')\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.remove
python
def remove(self, tag, nth=1): tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None
Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L512-L530
[ "def fix_tag(value):\n \"\"\"Make a FIX tag value from string, bytes, or integer.\"\"\"\n if sys.version_info[0] == 2:\n return bytes(value)\n else:\n if type(value) == bytes:\n return value\n elif type(value) == str:\n return value.encode('ASCII')\n return str(value).encode('ASCII')\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage.encode
python
def encode(self, raw=False): buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf
Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L533-L585
[ "def fix_val(value):\n \"\"\"Make a FIX value from a string, bytes, or number.\"\"\"\n if type(value) == bytes:\n return value\n\n if sys.version_info[0] == 2:\n return bytes(value)\n elif type(value) == str:\n return bytes(value, 'UTF-8')\n else:\n return bytes(str(value), 'ASCII')\n" ]
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod def _tz_offset_string(offset): """(Internal) Convert TZ offset in minutes east to string.""" s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
da4089/simplefix
simplefix/message.py
FixMessage._tz_offset_string
python
def _tz_offset_string(offset): s = "" io = int(offset) if io == 0: s += "Z" else: if -1440 < io < 1440: ho = abs(io) / 60 mo = abs(io) % 60 s += "%c%02u" % ("+" if io > 0 else "-", ho) if mo != 0: s += ":%02u" % mo else: raise ValueError("Timezone `offset` (%u) out of range " "-1439 to +1439 minutes" % io) return s
(Internal) Convert TZ offset in minutes east to string.
train
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L663-L682
null
class FixMessage(object): """FIX protocol message. FIX messages consist of an ordered list of tag=value pairs. Tags are numbers, represented on the wire as strings. Values may have various types, again all presented as strings on the wire. This class stores a FIX message: it does not perform any validation of the content of tags or values, nor the presence of tags required for compliance with a specific FIX protocol version.""" def __init__(self): """Initialise a FIX message.""" self.begin_string = None self.message_type = None self.pairs = [] self.header_index = 0 return def count(self): """Return the number of pairs in this message.""" return len(self.pairs) def append_pair(self, tag, value, header=False): """Append a tag=value pair to this message. :param tag: Integer or string FIX tag number. :param value: FIX tag value. :param header: Append to header if True; default to body. Both parameters are explicitly converted to strings before storage, so it's ok to pass integers if that's easier for your program logic. Note: a Python 'None' value will be silently ignored, and no field is appended.""" if tag is None or value is None: return if int(tag) == 8: self.begin_string = fix_val(value) if int(tag) == 35: self.message_type = fix_val(value) if header: self.pairs.insert(self.header_index, (fix_tag(tag), fix_val(value))) self.header_index += 1 else: self.pairs.append((fix_tag(tag), fix_val(value))) return def append_time(self, tag, timestamp=None, precision=3, utc=True, header=False): """Append a time field to this message. :param tag: Integer or string FIX tag number. :param timestamp: Time (see below) value to append, or None for now. :param precision: Number of decimal digits. Zero for seconds only, three for milliseconds, 6 for microseconds. Defaults to milliseconds. :param utc: Use UTC if True, local time if False. :param header: Append to header if True; default to body. THIS METHOD IS DEPRECATED! USE append_utc_timestamp() OR append_tz_timestamp() INSTEAD. Append a timestamp in FIX format from a Python time.time or datetime.datetime value. Note that prior to FIX 5.0, precision must be zero or three to be compliant with the standard.""" warnings.warn("simplefix.FixMessage.append_time() is deprecated. " "Use append_utc_timestamp() or append_tz_timestamp() " "instead.", DeprecationWarning) if not timestamp: t = datetime.datetime.utcnow() elif type(timestamp) is float: if utc: t = datetime.datetime.utcfromtimestamp(timestamp) else: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp s = t.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def _append_utc_datetime(self, tag, format, ts, precision, header): """(Internal) Append formatted datetime.""" if ts is None: t = datetime.datetime.utcnow() elif type(ts) is float: t = datetime.datetime.utcfromtimestamp(ts) else: t = ts s = t.strftime(format) if precision == 3: s += ".%03d" % (t.microsecond / 1000) elif precision == 6: s += ".%06d" % t.microsecond elif precision != 0: raise ValueError("Precision should be one of 0, 3 or 6 digits") return self.append_pair(tag, s, header=header) def append_utc_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimestamp value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%Y%m%d-%H:%M:%S", timestamp, precision, header) def append_utc_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a UTCTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a datetime, such as created by datetime.datetime.utcnow(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.utcnow() is used to get the current UTC time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" return self._append_utc_datetime(tag, "%H:%M:%S", timestamp, precision, header) def append_utc_time_only_parts(self, tag, h, m, s, ms=None, us=None, header=False): """Append a field with a UTCTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param header: Append to FIX header if True; default to body. Formats the UTCTimeOnly value from its components. If `ms` or `us` are None, the precision is truncated at that point. Note that seconds are not optional, unlike in TZTimeOnly.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v = "%02u:%02u:%02u" % (ih, im, isec) if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius return self.append_pair(tag, v, header=header) def append_tz_timestamp(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimestamp value, derived from local time. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current local time. Precision values other than zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" # Get float offset from Unix epoch. if timestamp is None: now = time.time() elif type(timestamp) is float: now = timestamp else: now = time.mktime(timestamp.timetuple()) + \ (timestamp.microsecond * 1e-6) # Get offset of local timezone east of UTC. utc = datetime.datetime.utcfromtimestamp(now) local = datetime.datetime.fromtimestamp(now) td = local - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = local.strftime("%Y%m%d-%H:%M:%S") if precision == 3: s += ".%03u" % (local.microsecond / 1000) elif precision == 6: s += ".%06u" % local.microsecond elif precision != 0: raise ValueError("Precision (%u) should be one of " "0, 3 or 6 digits" % precision) s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (ms) or 6 (us). :param header: Append to FIX header if True; default to body. The `timestamp` value should be a local datetime, such as created by datetime.datetime.now(); a float, being the number of seconds since midnight 1 Jan 1970 UTC, such as returned by time.time(); or, None, in which case datetime.datetime.now() is used to get the current UTC time. Precision values other than None (minutes), zero (seconds), 3 (milliseconds), or 6 (microseconds) will raise an exception. Note that prior to FIX 5.0, only values of 0 or 3 comply with the standard.""" if timestamp is None: t = datetime.datetime.now() elif type(timestamp) is float: t = datetime.datetime.fromtimestamp(timestamp) else: t = timestamp now = time.mktime(t.timetuple()) + (t.microsecond * 1e-6) utc = datetime.datetime.utcfromtimestamp(now) td = t - utc offset = int(((td.days * 86400) + td.seconds) / 60) s = t.strftime("%H:%M") if precision == 0: s += t.strftime(":%S") elif precision == 3: s += t.strftime(":%S") s += ".%03u" % (t.microsecond / 1000) elif precision == 6: s += t.strftime(":%S") s += ".%06u" % t.microsecond elif precision is not None: raise ValueError("Precision should be one of " "None, 0, 3 or 6 digits") s += self._tz_offset_string(offset) return self.append_pair(tag, s, header=header) def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): """Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in range 0 to 999. :param us: Optional microseconds, in range 0 to 999. :param offset: Minutes east of UTC, in range -1439 to +1439. :param header: Append to FIX header if True; default to body. Formats the TZTimeOnly value from its components. If `s`, `ms` or `us` are None, the precision is truncated at that point.""" ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(m) if im < 0 or im > 59: raise ValueError("Minute value `m` (%u) out of range " "0 to 59" % im) v = "%02u:%02u" % (ih, im) if s is not None: isec = int(s) if isec < 0 or isec > 60: raise ValueError("Seconds value `s` (%u) out of range " "0 to 60" % isec) v += ":%02u" % isec if ms is not None: ims = int(ms) if ims < 0 or ims > 999: raise ValueError("Milliseconds value `ms` (%u) " "out of range 0 to 999" % ims) v += ".%03u" % ims if us is not None: ius = int(us) if ius < 0 or ius > 999: raise ValueError("Microseconds value `us` (%u) " "out of range 0 to 999" % ius) v += "%03u" % ius v += self._tz_offset_string(offset) return self.append_pair(tag, v, header=header) def append_string(self, field, header=False): """Append a tag=value pair in string format. :param field: String "tag=value" to be appended to this message. :param header: Append to header if True; default to body. The string is split at the first '=' character, and the resulting tag and value strings are appended to the message.""" # Split into tag and value. bits = field.split('=', 1) if len(bits) != 2: raise ValueError("Field missing '=' separator.") # Check tag is an integer. try: tag_int = int(bits[0]) except ValueError: raise ValueError("Tag value must be an integer") # Save. self.append_pair(tag_int, bits[1], header=header) return def append_strings(self, string_list, header=False): """Append tag=pairs for each supplied string. :param string_list: List of "tag=value" strings. :param header: Append to header if True; default to body. Each string is split, and the resulting tag and value strings are appended to the message.""" for s in string_list: self.append_string(s, header=header) return def append_data(self, len_tag, val_tag, data, header=False): """Append raw data, possibly including a embedded SOH. :param len_tag: Tag number for length field. :param val_tag: Tag number for value field. :param data: Raw data byte string. :param header: Append to header if True; default to body. Appends two pairs: a length pair, followed by a data pair, containing the raw data supplied. Example fields that should use this method include: 95/96, 212/213, 354/355, etc.""" self.append_pair(len_tag, len(data), header=header) self.append_pair(val_tag, data, header=header) return def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can get repeated fields.""" tag = fix_tag(tag) nth = int(nth) for t, v in self.pairs: if t == tag: nth -= 1 if nth == 0: return v return None def remove(self, tag, nth=1): """Remove the n-th occurrence of tag in this message. :param tag: FIX field tag number to be removed. :param nth: Index of tag if repeating, first is 1. :returns: Value of the field if removed, None otherwise.""" tag = fix_tag(tag) nth = int(nth) for i in range(len(self.pairs)): t, v = self.pairs[i] if t == tag: nth -= 1 if nth == 0: self.pairs.pop(i) return v return None def encode(self, raw=False): """Convert message to on-the-wire FIX format. :param raw: If True, encode pairs exactly as provided. Unless 'raw' is set, this function will calculate and correctly set the BodyLength (9) and Checksum (10) fields, and ensure that the BeginString (8), Body Length (9), Message Type (35) and Checksum (10) fields are in the right positions. This function does no further validation of the message content.""" buf = b"" if raw: # Walk pairs, creating string. for tag, value in self.pairs: buf += tag + b'=' + value + SOH_STR return buf # Cooked. for tag, value in self.pairs: if int(tag) in (8, 9, 35, 10): continue buf += tag + b'=' + value + SOH_STR # Prepend the message type. if self.message_type is None: raise ValueError("No message type set") buf = b"35=" + self.message_type + SOH_STR + buf # Calculate body length. # # From first byte after body length field, to the delimiter # before the checksum (which shouldn't be there yet). body_length = len(buf) # Prepend begin-string and body-length. if not self.begin_string: raise ValueError("No begin string set") buf = b"8=" + self.begin_string + SOH_STR + \ b"9=" + fix_val("%u" % body_length) + SOH_STR + \ buf # Calculate and append the checksum. checksum = 0 for c in buf: checksum += ord(c) if sys.version_info[0] == 2 else c buf += b"10=" + fix_val("%03u" % (checksum % 256,)) + SOH_STR return buf def __str__(self): """Return string form of message contents.""" s = "" for tag, value in self.pairs: if s: s += "|" s += tag.decode("ascii") + "=" + value.decode("ascii") return s def __eq__(self, other): """Compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" if not hasattr(other, "pairs"): return False # Check pairs list lengths. if len(self.pairs) != len(other.pairs): return False # Clone our pairs list. tmp = [] for pair in self.pairs: tmp.append((pair[0], pair[1])) for pair in other.pairs: try: tmp.remove(pair) except ValueError: return False return True def __ne__(self, other): """Inverse compare with another FixMessage. :param other: Message to compare. Compares the tag=value pairs, message_type and FIX version of this message against the `other`.""" return not self == other # Disable hashing, since FixMessage is mutable. __hash__ = None def __getitem__(self, item_index): """Enable messages to be iterated over, and treated as a sequence. :param item_index: Numeric index in range 0 to length - 1 Supports both 'for tag, value in message' usage, and 'message[n]' access.""" if item_index >= len(self.pairs): raise IndexError tag, value = self.pairs[item_index] return int(tag), value def __contains__(self, item): """Directly support 'in' and 'not in' operators. :param item: Tag value to check.""" needle = fix_tag(item) for tag, value in self.pairs: if tag == needle: return True return False @staticmethod
pndurette/gTTS
gtts/lang.py
tts_langs
python
def tts_langs(): try: langs = dict() langs.update(_fetch_langs()) langs.update(_extra_langs()) log.debug("langs: %s", langs) return langs except Exception as e: raise RuntimeError("Unable to get language list: %s" % str(e))
Languages Google Text-to-Speech supports. Returns: dict: A dictionnary of the type `{ '<lang>': '<name>'}` Where `<lang>` is an IETF language tag such as `en` or `pt-br`, and `<name>` is the full English name of the language, such as `English` or `Portuguese (Brazil)`. The dictionnary returned combines languages from two origins: - Languages fetched automatically from Google Translate - Languages that are undocumented variations that were observed to work and present different dialects or accents.
train
https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/lang.py#L17-L41
[ "def _fetch_langs():\n \"\"\"Fetch (scrape) languages from Google Translate.\n\n Google Translate loads a JavaScript Array of 'languages codes' that can\n be spoken. We intersect this list with all the languages Google Translate\n provides to get the ones that support text-to-speech.\n\n Returns:\n dict: A dictionnary of languages from Google Translate\n\n \"\"\"\n # Load HTML\n page = requests.get(URL_BASE)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n # JavaScript URL\n # The <script src=''> path can change, but not the file.\n # Ex: /zyx/abc/20180211/desktop_module_main.js\n js_path = soup.find(src=re.compile(JS_FILE))['src']\n js_url = \"{}/{}\".format(URL_BASE, js_path)\n\n # Load JavaScript\n js_contents = requests.get(js_url).text\n\n # Approximately extract TTS-enabled language codes\n # RegEx pattern search because minified variables can change.\n # Extra garbage will be dealt with later as we keep languages only.\n # In: \"[...]Fv={af:1,ar:1,[...],zh:1,\"zh-cn\":1,\"zh-tw\":1}[...]\"\n # Out: ['is', '12', [...], 'af', 'ar', [...], 'zh', 'zh-cn', 'zh-tw']\n pattern = r'[{,\\\"](\\w{2}|\\w{2}-\\w{2,3})(?=:1|\\\":1)'\n tts_langs = re.findall(pattern, js_contents)\n\n # Build lang. dict. from main page (JavaScript object populating lang. menu)\n # Filtering with the TTS-enabled languages\n # In: \"{code:'auto',name:'Detect language'},{code:'af',name:'Afrikaans'},[...]\"\n # re.findall: [('auto', 'Detect language'), ('af', 'Afrikaans'), [...]]\n # Out: {'af': 'Afrikaans', [...]}\n trans_pattern = r\"{code:'(?P<lang>.+?[^'])',name:'(?P<name>.+?[^'])'}\"\n trans_langs = re.findall(trans_pattern, page.text)\n return {lang: name for lang, name in trans_langs if lang in tts_langs}\n", "def _extra_langs():\n \"\"\"Define extra languages.\n\n Returns:\n dict: A dictionnary of extra languages manually defined.\n\n Variations of the ones fetched by `_fetch_langs`,\n observed to provide different dialects or accents or\n just simply accepted by the Google Translate Text-to-Speech API.\n\n \"\"\"\n return {\n # Chinese\n 'zh-cn': 'Chinese (Mandarin/China)',\n 'zh-tw': 'Chinese (Mandarin/Taiwan)',\n # English\n 'en-us': 'English (US)',\n 'en-ca': 'English (Canada)',\n 'en-uk': 'English (UK)',\n 'en-gb': 'English (UK)',\n 'en-au': 'English (Australia)',\n 'en-gh': 'English (Ghana)',\n 'en-in': 'English (India)',\n 'en-ie': 'English (Ireland)',\n 'en-nz': 'English (New Zealand)',\n 'en-ng': 'English (Nigeria)',\n 'en-ph': 'English (Philippines)',\n 'en-za': 'English (South Africa)',\n 'en-tz': 'English (Tanzania)',\n # French\n 'fr-ca': 'French (Canada)',\n 'fr-fr': 'French (France)',\n # Portuguese\n 'pt-br': 'Portuguese (Brazil)',\n 'pt-pt': 'Portuguese (Portugal)',\n # Spanish\n 'es-es': 'Spanish (Spain)',\n 'es-us': 'Spanish (United States)'\n }\n" ]
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import requests import logging import re __all__ = ['tts_langs'] URL_BASE = 'http://translate.google.com' JS_FILE = 'translate_m.js' # Logger log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) def _fetch_langs(): """Fetch (scrape) languages from Google Translate. Google Translate loads a JavaScript Array of 'languages codes' that can be spoken. We intersect this list with all the languages Google Translate provides to get the ones that support text-to-speech. Returns: dict: A dictionnary of languages from Google Translate """ # Load HTML page = requests.get(URL_BASE) soup = BeautifulSoup(page.content, 'html.parser') # JavaScript URL # The <script src=''> path can change, but not the file. # Ex: /zyx/abc/20180211/desktop_module_main.js js_path = soup.find(src=re.compile(JS_FILE))['src'] js_url = "{}/{}".format(URL_BASE, js_path) # Load JavaScript js_contents = requests.get(js_url).text # Approximately extract TTS-enabled language codes # RegEx pattern search because minified variables can change. # Extra garbage will be dealt with later as we keep languages only. # In: "[...]Fv={af:1,ar:1,[...],zh:1,"zh-cn":1,"zh-tw":1}[...]" # Out: ['is', '12', [...], 'af', 'ar', [...], 'zh', 'zh-cn', 'zh-tw'] pattern = r'[{,\"](\w{2}|\w{2}-\w{2,3})(?=:1|\":1)' tts_langs = re.findall(pattern, js_contents) # Build lang. dict. from main page (JavaScript object populating lang. menu) # Filtering with the TTS-enabled languages # In: "{code:'auto',name:'Detect language'},{code:'af',name:'Afrikaans'},[...]" # re.findall: [('auto', 'Detect language'), ('af', 'Afrikaans'), [...]] # Out: {'af': 'Afrikaans', [...]} trans_pattern = r"{code:'(?P<lang>.+?[^'])',name:'(?P<name>.+?[^'])'}" trans_langs = re.findall(trans_pattern, page.text) return {lang: name for lang, name in trans_langs if lang in tts_langs} def _extra_langs(): """Define extra languages. Returns: dict: A dictionnary of extra languages manually defined. Variations of the ones fetched by `_fetch_langs`, observed to provide different dialects or accents or just simply accepted by the Google Translate Text-to-Speech API. """ return { # Chinese 'zh-cn': 'Chinese (Mandarin/China)', 'zh-tw': 'Chinese (Mandarin/Taiwan)', # English 'en-us': 'English (US)', 'en-ca': 'English (Canada)', 'en-uk': 'English (UK)', 'en-gb': 'English (UK)', 'en-au': 'English (Australia)', 'en-gh': 'English (Ghana)', 'en-in': 'English (India)', 'en-ie': 'English (Ireland)', 'en-nz': 'English (New Zealand)', 'en-ng': 'English (Nigeria)', 'en-ph': 'English (Philippines)', 'en-za': 'English (South Africa)', 'en-tz': 'English (Tanzania)', # French 'fr-ca': 'French (Canada)', 'fr-fr': 'French (France)', # Portuguese 'pt-br': 'Portuguese (Brazil)', 'pt-pt': 'Portuguese (Portugal)', # Spanish 'es-es': 'Spanish (Spain)', 'es-us': 'Spanish (United States)' }
pndurette/gTTS
gtts/lang.py
_fetch_langs
python
def _fetch_langs(): # Load HTML page = requests.get(URL_BASE) soup = BeautifulSoup(page.content, 'html.parser') # JavaScript URL # The <script src=''> path can change, but not the file. # Ex: /zyx/abc/20180211/desktop_module_main.js js_path = soup.find(src=re.compile(JS_FILE))['src'] js_url = "{}/{}".format(URL_BASE, js_path) # Load JavaScript js_contents = requests.get(js_url).text # Approximately extract TTS-enabled language codes # RegEx pattern search because minified variables can change. # Extra garbage will be dealt with later as we keep languages only. # In: "[...]Fv={af:1,ar:1,[...],zh:1,"zh-cn":1,"zh-tw":1}[...]" # Out: ['is', '12', [...], 'af', 'ar', [...], 'zh', 'zh-cn', 'zh-tw'] pattern = r'[{,\"](\w{2}|\w{2}-\w{2,3})(?=:1|\":1)' tts_langs = re.findall(pattern, js_contents) # Build lang. dict. from main page (JavaScript object populating lang. menu) # Filtering with the TTS-enabled languages # In: "{code:'auto',name:'Detect language'},{code:'af',name:'Afrikaans'},[...]" # re.findall: [('auto', 'Detect language'), ('af', 'Afrikaans'), [...]] # Out: {'af': 'Afrikaans', [...]} trans_pattern = r"{code:'(?P<lang>.+?[^'])',name:'(?P<name>.+?[^'])'}" trans_langs = re.findall(trans_pattern, page.text) return {lang: name for lang, name in trans_langs if lang in tts_langs}
Fetch (scrape) languages from Google Translate. Google Translate loads a JavaScript Array of 'languages codes' that can be spoken. We intersect this list with all the languages Google Translate provides to get the ones that support text-to-speech. Returns: dict: A dictionnary of languages from Google Translate
train
https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/lang.py#L44-L83
null
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import requests import logging import re __all__ = ['tts_langs'] URL_BASE = 'http://translate.google.com' JS_FILE = 'translate_m.js' # Logger log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) def tts_langs(): """Languages Google Text-to-Speech supports. Returns: dict: A dictionnary of the type `{ '<lang>': '<name>'}` Where `<lang>` is an IETF language tag such as `en` or `pt-br`, and `<name>` is the full English name of the language, such as `English` or `Portuguese (Brazil)`. The dictionnary returned combines languages from two origins: - Languages fetched automatically from Google Translate - Languages that are undocumented variations that were observed to work and present different dialects or accents. """ try: langs = dict() langs.update(_fetch_langs()) langs.update(_extra_langs()) log.debug("langs: %s", langs) return langs except Exception as e: raise RuntimeError("Unable to get language list: %s" % str(e)) def _extra_langs(): """Define extra languages. Returns: dict: A dictionnary of extra languages manually defined. Variations of the ones fetched by `_fetch_langs`, observed to provide different dialects or accents or just simply accepted by the Google Translate Text-to-Speech API. """ return { # Chinese 'zh-cn': 'Chinese (Mandarin/China)', 'zh-tw': 'Chinese (Mandarin/Taiwan)', # English 'en-us': 'English (US)', 'en-ca': 'English (Canada)', 'en-uk': 'English (UK)', 'en-gb': 'English (UK)', 'en-au': 'English (Australia)', 'en-gh': 'English (Ghana)', 'en-in': 'English (India)', 'en-ie': 'English (Ireland)', 'en-nz': 'English (New Zealand)', 'en-ng': 'English (Nigeria)', 'en-ph': 'English (Philippines)', 'en-za': 'English (South Africa)', 'en-tz': 'English (Tanzania)', # French 'fr-ca': 'French (Canada)', 'fr-fr': 'French (France)', # Portuguese 'pt-br': 'Portuguese (Brazil)', 'pt-pt': 'Portuguese (Portugal)', # Spanish 'es-es': 'Spanish (Spain)', 'es-us': 'Spanish (United States)' }
pndurette/gTTS
gtts/tokenizer/pre_processors.py
tone_marks
python
def tone_marks(text): return PreProcessorRegex( search_args=symbols.TONE_MARKS, search_func=lambda x: u"(?<={})".format(x), repl=' ').run(text)
Add a space after tone-modifying punctuation. Because the `tone_marks` tokenizer case will split after a tone-modidfying punctuation mark, make sure there's whitespace after.
train
https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/tokenizer/pre_processors.py#L6-L16
[ "def run(self, text):\n \"\"\"Run each regex substitution on ``text``.\n\n Args:\n text (string): the input text.\n\n Returns:\n string: text after all substitutions have been sequentially\n applied.\n\n \"\"\"\n for regex in self.regexes:\n text = regex.sub(self.repl, text)\n return text\n" ]
# -*- coding: utf-8 -*- from gtts.tokenizer import PreProcessorRegex, PreProcessorSub, symbols import re def end_of_line(text): """Re-form words cut by end-of-line hyphens. Remove "<hyphen><newline>". """ return PreProcessorRegex( search_args=u'-', search_func=lambda x: u"{}\n".format(x), repl='').run(text) def abbreviations(text): """Remove periods after an abbreviation from a list of known abbrevations that can be spoken the same without that period. This prevents having to handle tokenization of that period. Note: Could potentially remove the ending period of a sentence. Note: Abbreviations that Google Translate can't pronounce without (or even with) a period should be added as a word substitution with a :class:`PreProcessorSub` pre-processor. Ex.: 'Esq.', 'Esquire'. """ return PreProcessorRegex( search_args=symbols.ABBREVIATIONS, search_func=lambda x: r"(?<={})(?=\.).".format(x), repl='', flags=re.IGNORECASE).run(text) def word_sub(text): """Word-for-word substitutions.""" return PreProcessorSub( sub_pairs=symbols.SUB_PAIRS).run(text)
pndurette/gTTS
gtts/tokenizer/pre_processors.py
end_of_line
python
def end_of_line(text): return PreProcessorRegex( search_args=u'-', search_func=lambda x: u"{}\n".format(x), repl='').run(text)
Re-form words cut by end-of-line hyphens. Remove "<hyphen><newline>".
train
https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/tokenizer/pre_processors.py#L19-L28
[ "def run(self, text):\n \"\"\"Run each regex substitution on ``text``.\n\n Args:\n text (string): the input text.\n\n Returns:\n string: text after all substitutions have been sequentially\n applied.\n\n \"\"\"\n for regex in self.regexes:\n text = regex.sub(self.repl, text)\n return text\n" ]
# -*- coding: utf-8 -*- from gtts.tokenizer import PreProcessorRegex, PreProcessorSub, symbols import re def tone_marks(text): """Add a space after tone-modifying punctuation. Because the `tone_marks` tokenizer case will split after a tone-modidfying punctuation mark, make sure there's whitespace after. """ return PreProcessorRegex( search_args=symbols.TONE_MARKS, search_func=lambda x: u"(?<={})".format(x), repl=' ').run(text) def abbreviations(text): """Remove periods after an abbreviation from a list of known abbrevations that can be spoken the same without that period. This prevents having to handle tokenization of that period. Note: Could potentially remove the ending period of a sentence. Note: Abbreviations that Google Translate can't pronounce without (or even with) a period should be added as a word substitution with a :class:`PreProcessorSub` pre-processor. Ex.: 'Esq.', 'Esquire'. """ return PreProcessorRegex( search_args=symbols.ABBREVIATIONS, search_func=lambda x: r"(?<={})(?=\.).".format(x), repl='', flags=re.IGNORECASE).run(text) def word_sub(text): """Word-for-word substitutions.""" return PreProcessorSub( sub_pairs=symbols.SUB_PAIRS).run(text)
pndurette/gTTS
gtts/tokenizer/pre_processors.py
abbreviations
python
def abbreviations(text): return PreProcessorRegex( search_args=symbols.ABBREVIATIONS, search_func=lambda x: r"(?<={})(?=\.).".format(x), repl='', flags=re.IGNORECASE).run(text)
Remove periods after an abbreviation from a list of known abbrevations that can be spoken the same without that period. This prevents having to handle tokenization of that period. Note: Could potentially remove the ending period of a sentence. Note: Abbreviations that Google Translate can't pronounce without (or even with) a period should be added as a word substitution with a :class:`PreProcessorSub` pre-processor. Ex.: 'Esq.', 'Esquire'.
train
https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/tokenizer/pre_processors.py#L31-L48
[ "def run(self, text):\n \"\"\"Run each regex substitution on ``text``.\n\n Args:\n text (string): the input text.\n\n Returns:\n string: text after all substitutions have been sequentially\n applied.\n\n \"\"\"\n for regex in self.regexes:\n text = regex.sub(self.repl, text)\n return text\n" ]
# -*- coding: utf-8 -*- from gtts.tokenizer import PreProcessorRegex, PreProcessorSub, symbols import re def tone_marks(text): """Add a space after tone-modifying punctuation. Because the `tone_marks` tokenizer case will split after a tone-modidfying punctuation mark, make sure there's whitespace after. """ return PreProcessorRegex( search_args=symbols.TONE_MARKS, search_func=lambda x: u"(?<={})".format(x), repl=' ').run(text) def end_of_line(text): """Re-form words cut by end-of-line hyphens. Remove "<hyphen><newline>". """ return PreProcessorRegex( search_args=u'-', search_func=lambda x: u"{}\n".format(x), repl='').run(text) def word_sub(text): """Word-for-word substitutions.""" return PreProcessorSub( sub_pairs=symbols.SUB_PAIRS).run(text)