Search is not available for this dataset
text
stringlengths
75
104k
def add_value(self, value, timestamp=None): """ Method for `Update Data Stream Value <https://m2x.att.com/developer/documentation/v2/device#Update-Data-Stream-Value>`_ endpoint. :param value: The updated stream value :param timestamp: The (optional) timestamp for the upadted value :return: The API response, see M2X API docs for details :rtype: dict :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request """ data = {'value': value} if timestamp: data['timestamp'] = timestamp return self.api.put(self.subpath('/value'), data=data)
def post_values(self, values): """ Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint. :param values: Values to post, see M2X API docs for details :type values: dict :return: The API response, see M2X API docs for details :rtype: dict :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request """ return self.api.post(self.subpath('/values'), data={ 'values': values })
def delete_values(self, start, stop): """ Method for `Delete Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Delete-Data-Stream-Values>`_ endpoint. :param start: ISO8601 timestamp for starting timerange for values to be deleted :param stop: ISO8601 timestamp for ending timerange for values to be deleted :return: The API response, see M2X API docs for details :rtype: dict :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request """ return self.api.delete(self.subpath('/values'), data=self.to_server({ 'from': start, 'end': stop }))
def loads(s, strip_comments=False, **kw): """ Load a list of trees from a Newick formatted string. :param s: Newick formatted string. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. :return: List of Node objects. """ kw['strip_comments'] = strip_comments return [parse_node(ss.strip(), **kw) for ss in s.split(';') if ss.strip()]
def dumps(trees): """ Serialize a list of trees in Newick format. :param trees: List of Node objects or a single Node object. :return: Newick formatted string. """ if isinstance(trees, Node): trees = [trees] return ';\n'.join([tree.newick for tree in trees]) + ';'
def load(fp, strip_comments=False, **kw): """ Load a list of trees from an open Newick formatted file. :param fp: open file handle. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. :return: List of Node objects. """ kw['strip_comments'] = strip_comments return loads(fp.read(), **kw)
def read(fname, encoding='utf8', strip_comments=False, **kw): """ Load a list of trees from a Newick formatted file. :param fname: file path. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. :return: List of Node objects. """ kw['strip_comments'] = strip_comments with io.open(fname, encoding=encoding) as fp: return load(fp, **kw)
def _parse_siblings(s, **kw): """ http://stackoverflow.com/a/26809037 """ bracket_level = 0 current = [] # trick to remove special-case of trailing chars for c in (s + ","): if c == "," and bracket_level == 0: yield parse_node("".join(current), **kw) current = [] else: if c == "(": bracket_level += 1 elif c == ")": bracket_level -= 1 current.append(c)
def parse_node(s, strip_comments=False, **kw): """ Parse a Newick formatted string into a `Node` object. :param s: Newick formatted string to parse. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. :return: `Node` instance. """ if strip_comments: s = COMMENT.sub('', s) s = s.strip() parts = s.split(')') if len(parts) == 1: descendants, label = [], s else: if not parts[0].startswith('('): raise ValueError('unmatched braces %s' % parts[0][:100]) descendants = list(_parse_siblings(')'.join(parts[:-1])[1:], **kw)) label = parts[-1] name, length = _parse_name_and_length(label) return Node.create(name=name, length=length, descendants=descendants, **kw)
def create(cls, name=None, length=None, descendants=None, **kw): """ Create a new `Node` object. :param name: Node label. :param length: Branch length from the new node to its parent. :param descendants: list of descendants or `None`. :param kw: Additonal keyword arguments are passed through to `Node.__init__`. :return: `Node` instance. """ node = cls(name=name, length=length, **kw) for descendant in descendants or []: node.add_descendant(descendant) return node
def newick(self): """The representation of the Node in Newick format.""" label = self.name or '' if self._length: label += ':' + self._length descendants = ','.join([n.newick for n in self.descendants]) if descendants: descendants = '(' + descendants + ')' return descendants + label
def ascii_art(self, strict=False, show_internal=True): """ Return a unicode string representing a tree in ASCII art fashion. :param strict: Use ASCII characters strictly (for the tree symbols). :param show_internal: Show labels of internal nodes. :return: unicode string >>> node = loads('((A,B)C,((D,E)F,G,H)I)J;')[0] >>> print(node.ascii_art(show_internal=False, strict=True)) /-A /---| | \-B ----| /-D | /---| | | \-E \---| |-G \-H """ cmap = { '\u2500': '-', '\u2502': '|', '\u250c': '/', '\u2514': '\\', '\u251c': '|', '\u2524': '|', '\u253c': '+', } def normalize(line): m = re.compile('(?<=\u2502)(?P<s>\s+)(?=[\u250c\u2514\u2502])') line = m.sub(lambda m: m.group('s')[1:], line) line = re.sub('\u2500\u2502', '\u2500\u2524', line) # -| line = re.sub('\u2502\u2500', '\u251c', line) # |- line = re.sub('\u2524\u2500', '\u253c', line) # -|- if strict: for u, a in cmap.items(): line = line.replace(u, a) return line return '\n'.join( normalize(l) for l in self._ascii_art(show_internal=show_internal)[0] if set(l) != {' ', '\u2502'})
def walk(self, mode=None): """ Traverses the (sub)tree rooted at self, yielding each visited Node. .. seealso:: https://en.wikipedia.org/wiki/Tree_traversal :param mode: Specifies the algorithm to use when traversing the subtree rooted \ at self. `None` for breadth-first, `'postorder'` for post-order depth-first \ search. :return: Generator of the visited Nodes. """ if mode == 'postorder': for n in self._postorder(): yield n else: # default to a breadth-first search yield self for node in self.descendants: for n in node.walk(): yield n
def visit(self, visitor, predicate=None, **kw): """ Apply a function to matching nodes in the (sub)tree rooted at self. :param visitor: A callable accepting a Node object as single argument.. :param predicate: A callable accepting a Node object as single argument and \ returning a boolean signaling whether Node matches; if `None` all nodes match. :param kw: Addtional keyword arguments are passed through to self.walk. """ predicate = predicate or bool for n in self.walk(**kw): if predicate(n): visitor(n)
def get_node(self, label): """ Gets the specified node by name. :return: Node or None if name does not exist in tree """ for n in self.walk(): if n.name == label: return n
def prune(self, leaves, inverse=False): """ Remove all those nodes in the specified list, or if inverse=True, remove all those nodes not in the specified list. The specified nodes must be leaves and distinct from the root node. :param nodes: A list of Node objects :param inverse: Specifies whether to remove nodes in the list or not\ in the list. """ self.visit( lambda n: n.ancestor.descendants.remove(n), # We won't prune the root node, even if it is a leave and requested to # be pruned! lambda n: ((not inverse and n in leaves) or (inverse and n.is_leaf and n not in leaves)) and n.ancestor, mode="postorder")
def prune_by_names(self, leaf_names, inverse=False): """ Perform an (inverse) prune, with leaves specified by name. :param node_names: A list of leaaf Node names (strings) :param inverse: Specifies whether to remove nodes in the list or not\ in the list. """ self.prune([l for l in self.walk() if l.name in leaf_names], inverse)
def remove_redundant_nodes(self, preserve_lengths=True): """ Remove all nodes which have only a single child, and attach their grandchildren to their parent. The resulting tree has the minimum number of internal nodes required for the number of leaves. :param preserve_lengths: If true, branch lengths of removed nodes are \ added to those of their children. """ for n in self.walk(mode='postorder'): while n.ancestor and len(n.ancestor.descendants) == 1: grandfather = n.ancestor.ancestor father = n.ancestor if preserve_lengths: n.length += father.length if grandfather: for i, child in enumerate(grandfather.descendants): if child is father: del grandfather.descendants[i] grandfather.add_descendant(n) father.ancestor = None else: self.descendants = n.descendants if preserve_lengths: self.length = n.length
def resolve_polytomies(self): """ Insert additional nodes with length=0 into the subtree in such a way that all non-leaf nodes have only 2 descendants, i.e. the tree becomes a fully resolved binary tree. """ def _resolve_polytomies(n): new = Node(length=self._length_formatter(self._length_parser('0'))) while len(n.descendants) > 1: new.add_descendant(n.descendants.pop()) n.descendants.append(new) self.visit(_resolve_polytomies, lambda n: len(n.descendants) > 2)
def remove_internal_names(self): """ Set the name of all non-leaf nodes in the subtree to None. """ self.visit(lambda n: setattr(n, 'name', None), lambda n: not n.is_leaf)
def remove_leaf_names(self): """ Set the name of all leaf nodes in the subtree to None. """ self.visit(lambda n: setattr(n, 'name', None), lambda n: n.is_leaf)
def auth_required(realm, auth_func): '''Decorator that protect methods with HTTP authentication.''' def auth_decorator(func): def inner(self, *args, **kw): if self.get_authenticated_user(auth_func, realm): return func(self, *args, **kw) return inner return auth_decorator
def dispose(json_str): """Clear all comments in json_str. Clear JS-style comments like // and /**/ in json_str. Accept a str or unicode as input. Args: json_str: A json string of str or unicode to clean up comment Returns: str: The str without comments (or unicode if you pass in unicode) """ result_str = list(json_str) escaped = False normal = True sl_comment = False ml_comment = False quoted = False a_step_from_comment = False a_step_from_comment_away = False former_index = None for index, char in enumerate(json_str): if escaped: # We have just met a '\' escaped = False continue if a_step_from_comment: # We have just met a '/' if char != '/' and char != '*': a_step_from_comment = False normal = True continue if a_step_from_comment_away: # We have just met a '*' if char != '/': a_step_from_comment_away = False if char == '"': if normal and not escaped: # We are now in a string quoted = True normal = False elif quoted and not escaped: # We are now out of a string quoted = False normal = True elif char == '\\': # '\' should not take effect in comment if normal or quoted: escaped = True elif char == '/': if a_step_from_comment: # Now we are in single line comment a_step_from_comment = False sl_comment = True normal = False former_index = index - 1 elif a_step_from_comment_away: # Now we are out of comment a_step_from_comment_away = False normal = True ml_comment = False for i in range(former_index, index + 1): result_str[i] = "" elif normal: # Now we are just one step away from comment a_step_from_comment = True normal = False elif char == '*': if a_step_from_comment: # We are now in multi-line comment a_step_from_comment = False ml_comment = True normal = False former_index = index - 1 elif ml_comment: a_step_from_comment_away = True elif char == '\n': if sl_comment: sl_comment = False normal = True for i in range(former_index, index + 1): result_str[i] = "" elif char == ']' or char == '}': if normal: _remove_last_comma(result_str, index) # Show respect to original input if we are in python2 return ("" if isinstance(json_str, str) else u"").join(result_str)
def require_setting(self, name, feature="this feature"): """Raises an exception if the given app setting is not defined.""" if name not in self.settings: raise Exception("You must define the '%s' setting in your " "application to use %s" % (name, feature))
def get_argument(self, name, default=_ARG_DEFAULT, strip=True): """Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we throw an HTTP 400 exception if it is missing. If the argument appears in the url more than once, we return the last value. The returned value is always unicode. """ args = self.get_arguments(name, strip=strip) if not args: if default is self._ARG_DEFAULT: raise HTTPError(400, "Missing argument %s" % name) return default return args[-1]
def get_arguments(self, name, strip=True): """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. The returned values are always unicode. """ values = [] for v in self.request.params.getall(name): v = self.decode_argument(v, name=name) if isinstance(v, unicode): # Get rid of any weird control chars (unless decoding gave # us bytes, in which case leave it alone) v = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", v) if strip: v = v.strip() values.append(v) return values
def async_callback(self, callback, *args, **kwargs): """Obsolete - catches exceptions from the wrapped function. This function is unnecessary since Tornado 1.1. """ if callback is None: return None if args or kwargs: callback = functools.partial(callback, *args, **kwargs) #FIXME what about the exception wrapper? return callback
def get_cookie(self, name, default=None): """Gets the value of the cookie with the given name, else default.""" assert self.cookie_monster, 'Cookie Monster not set' return self.cookie_monster.get_cookie(name, default)
def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ assert self.cookie_monster, 'Cookie Monster not set' #, domain=domain, path=path) self.cookie_monster.set_cookie(name, value)
def clear_cookie(self, name, path="/", domain=None): """Deletes the cookie with the given name.""" assert self.cookie_monster, 'Cookie Monster not set' #, path=path, domain=domain) self.cookie_monster.delete_cookie(name)
def authenticate_redirect( self, callback_uri=None, ax_attrs=["name", "email", "language", "username"]): """Returns the authentication URL for this service. After authentication, the service will redirect back to the given callback URI. We request the given attributes for the authenticated user by default (name, email, language, and username). If you don't need all those attributes for your app, you can request fewer with the ax_attrs keyword argument. """ callback_uri = callback_uri or self.request.uri args = self._openid_args(callback_uri, ax_attrs=ax_attrs) self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
def get_authenticated_user(self, callback): """Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods. """ # Verify the OpenID response via direct request to the OP # Recommendation @hmarrao, ref #3 args = dict((k, unicode(v[-1]).encode('utf-8')) for k, v in self.request.arguments.iteritems()) args["openid.mode"] = u"check_authentication" url = self._OPENID_ENDPOINT http = httpclient.AsyncHTTPClient() log.debug("OpenID requesting {0} at uri {1}".format(args, url)) http.fetch(url, self.async_callback( self._on_authentication_verified, callback), method="POST", body=urllib.urlencode(args))
def authorize_redirect(self, callback_uri=None, extra_params=None): """Redirects the user to obtain OAuth authorization for this service. Twitter and FriendFeed both require that you register a Callback URL with your application. You should call this method to log the user in, and then call get_authenticated_user() in the handler you registered as your Callback URL to complete the authorization process. This method sets a cookie called _oauth_request_token which is subsequently used (and cleared) in get_authenticated_user for security purposes. """ if callback_uri and getattr(self, "_OAUTH_NO_CALLBACKS", False): raise Exception("This service does not support oauth_callback") http = httpclient.AsyncHTTPClient() if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a": http.fetch(self._oauth_request_token_url(callback_uri=callback_uri, extra_params=extra_params), self.async_callback( self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri)) else: http.fetch(self._oauth_request_token_url(), self.async_callback( self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri))
def get_authenticated_user(self, callback): """Gets the OAuth authorized user and access token on callback. This method should be called from the handler for your registered OAuth Callback URL to complete the registration process. We call callback with the authenticated user, which in addition to standard attributes like 'name' includes the 'access_key' attribute, which contains the OAuth access you can use to make authorized requests to this service on behalf of the user. """ request_key = self.get_argument("oauth_token") oauth_verifier = self.get_argument("oauth_verifier", None) request_cookie = self.get_cookie("_oauth_request_token") if not request_cookie: log.warning("Missing OAuth request token cookie") callback(None) return self.clear_cookie("_oauth_request_token") cookie_key, cookie_secret = [base64.b64decode(i) for i in request_cookie.split("|")] if cookie_key != request_key: log.warning("Request token does not match cookie") callback(None) return token = dict(key=cookie_key, secret=cookie_secret) if oauth_verifier: token["verifier"] = oauth_verifier http = httpclient.AsyncHTTPClient() http.fetch(self._oauth_access_token_url(token), self.async_callback( self._on_access_token, callback))
def _oauth_request_parameters(self, url, access_token, parameters={}, method="GET"): """Returns the OAuth parameters as a dict for the given request. parameters should include all POST arguments and query string arguments that will be sent with the request. """ consumer_token = self._oauth_consumer_token() base_args = dict( oauth_consumer_key=consumer_token["key"], oauth_token=access_token["key"], oauth_signature_method="HMAC-SHA1", oauth_timestamp=str(int(time.time())), oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes), oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"), ) args = {} args.update(base_args) args.update(parameters) if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a": signature = _oauth10a_signature(consumer_token, method, url, args, access_token) else: signature = _oauth_signature(consumer_token, method, url, args, access_token) base_args["oauth_signature"] = signature return base_args
def authorize_redirect(self, redirect_uri=None, client_id=None, client_secret=None, extra_params=None ): """Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a Callback URL with your application. You should call this method to log the user in, and then call get_authenticated_user() in the handler you registered as your Callback URL to complete the authorization process. """ args = { "redirect_uri": redirect_uri, "client_id": client_id } if extra_params: args.update(extra_params) self.redirect( url_concat(self._OAUTH_AUTHORIZE_URL, args))
def friendfeed_request(self, path, callback, access_token=None, post_args=None, **args): """Fetches the given relative API path, e.g., "/bret/friends" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments. All the FriendFeed methods are documented at http://friendfeed.com/api/documentation. Many methods require an OAuth access token which you can obtain through authorize_redirect() and get_authenticated_user(). The user returned through that process includes an 'access_token' attribute that can be used to make authenticated requests via this method. Example usage:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FriendFeedMixin): @tornado.web.authenticated @tornado.web.asynchronous def get(self): self.friendfeed_request( "/entry", post_args={"body": "Testing Tornado Web Server"}, access_token=self.current_user["access_token"], callback=self.async_callback(self._on_post)) def _on_post(self, new_entry): if not new_entry: # Call failed; perhaps missing permission? self.authorize_redirect() return self.finish("Posted a message!") """ # Add the OAuth resource request signature if we have credentials url = "http://friendfeed-api.com/v2" + path if access_token: all_args = {} all_args.update(args) all_args.update(post_args or {}) consumer_token = self._oauth_consumer_token() method = "POST" if post_args is not None else "GET" oauth = self._oauth_request_parameters( url, access_token, all_args, method=method) args.update(oauth) if args: url += "?" + urllib.urlencode(args) callback = self.async_callback(self._on_friendfeed_request, callback) http = httpclient.AsyncHTTPClient() if post_args is not None: http.fetch(url, method="POST", body=urllib.urlencode(post_args), callback=callback) else: http.fetch(url, callback=callback)
def authorize_redirect(self, oauth_scope, callback_uri=None, ax_attrs=["name","email","language","username"]): """Authenticates and authorizes for the given Google resource. Some of the available resources are: * Gmail Contacts - http://www.google.com/m8/feeds/ * Calendar - http://www.google.com/calendar/feeds/ * Finance - http://finance.google.com/finance/feeds/ You can authorize multiple resources by separating the resource URLs with a space. """ callback_uri = callback_uri or self.request.uri args = self._openid_args(callback_uri, ax_attrs=ax_attrs, oauth_scope=oauth_scope) self.redirect(self._OPENID_ENDPOINT + "?" + urllib.urlencode(args))
def get_authenticated_user(self, callback): """Fetches the authenticated user data upon redirect.""" # Look to see if we are doing combined OpenID/OAuth oauth_ns = "" for name, values in self.request.arguments.iteritems(): if name.startswith("openid.ns.") and \ values[-1] == u"http://specs.openid.net/extensions/oauth/1.0": oauth_ns = name[10:] break token = self.get_argument("openid." + oauth_ns + ".request_token", "") if token: http = httpclient.AsyncHTTPClient() token = dict(key=token, secret="") http.fetch(self._oauth_access_token_url(token), self.async_callback(self._on_access_token, callback)) else: OpenIdMixin.get_authenticated_user(self, callback)
def facebook_request(self, method, callback, **args): """Makes a Facebook API REST request. We automatically include the Facebook API key and signature, but it is the callers responsibility to include 'session_key' and any other required arguments to the method. The available Facebook methods are documented here: http://wiki.developers.facebook.com/index.php/API Here is an example for the stream.get() method:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookMixin): @tornado.web.authenticated @tornado.web.asynchronous def get(self): self.facebook_request( method="stream.get", callback=self.async_callback(self._on_stream), session_key=self.current_user["session_key"]) def _on_stream(self, stream): if stream is None: # Not authorized to read the stream yet? self.redirect(self.authorize_redirect("read_stream")) return self.render("stream.html", stream=stream) """ self.require_setting("facebook_api_key", "Facebook Connect") self.require_setting("facebook_secret", "Facebook Connect") if not method.startswith("facebook."): method = "facebook." + method args["api_key"] = self.settings["facebook_api_key"] args["v"] = "1.0" args["method"] = method args["call_id"] = str(long(time.time() * 1e6)) args["format"] = "json" args["sig"] = self._signature(args) url = "http://api.facebook.com/restserver.php?" + \ urllib.urlencode(args) http = httpclient.AsyncHTTPClient() http.fetch(url, callback=self.async_callback( self._parse_response, callback))
def get_authenticated_user(self, redirect_uri, client_id, client_secret, code, callback, fields=None): """Handles the login for the Facebook user, returning a user object. Example usage:: class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin): @tornado.web.asynchronous def get(self): if self.get_argument("code", False): self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], client_secret=self.settings["facebook_secret"], code=self.get_argument("code"), callback=self.async_callback( self._on_login)) return self.authorize_redirect(redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"}) def _on_login(self, user): log.error(user) self.finish() """ http = httpclient.AsyncHTTPClient() args = { "redirect_uri": redirect_uri, "code": code, "client_id": client_id, "client_secret": client_secret, } #fields = set(['id', 'name', 'first_name', 'last_name', # 'locale', 'picture', 'link']) #if extra_fields: fields.update(extra_fields) if fields: fields = fields.split(',') http.fetch(self._oauth_request_token_url(**args), self.async_callback(self._on_access_token, redirect_uri, client_id, client_secret, callback, fields))
def facebook_request(self, path, callback, access_token=None, post_args=None, **args): """Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments. An introduction to the Facebook Graph API can be found at http://developers.facebook.com/docs/api Many methods require an OAuth access token which you can obtain through authorize_redirect() and get_authenticated_user(). The user returned through that process includes an 'access_token' attribute that can be used to make authenticated requests via this method. Example usage:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated @tornado.web.asynchronous def get(self): self.facebook_request( "/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"], callback=self.async_callback(self._on_post)) def _on_post(self, new_entry): if not new_entry: # Call failed; perhaps missing permission? self.authorize_redirect() return self.finish("Posted a message!") """ url = "https://graph.facebook.com" + path all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(args) all_args.update(post_args or {}) if all_args: url += "?" + urllib.urlencode(all_args) callback = self.async_callback(self._on_facebook_request, callback) http = httpclient.AsyncHTTPClient() if post_args is not None: http.fetch(url, method="POST", body=urllib.urlencode(post_args), callback=callback) else: http.fetch(url, callback=callback)
def url_concat(url, args): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args: return url if url[-1] not in ('?', '&'): url += '&' if ('?' in url) else '?' return url + urllib.urlencode(args)
def parse_multipart_form_data(boundary, data, arguments, files): """Parses a multipart/form-data body. The boundary and data parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. """ # The standard allows for the boundary to be quoted in the header, # although it's rare (it happens at least for google app engine # xmpp). I think we're also supposed to handle backslash-escapes # here but I'll save that until we see a client that uses them # in the wild. if boundary.startswith(b('"')) and boundary.endswith(b('"')): boundary = boundary[1:-1] if data.endswith(b("\r\n")): footer_length = len(boundary) + 6 else: footer_length = len(boundary) + 4 parts = data[:-footer_length].split(b("--") + boundary + b("\r\n")) for part in parts: if not part: continue eoh = part.find(b("\r\n\r\n")) if eoh == -1: logging.warning("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(part[:eoh].decode("utf-8")) disp_header = headers.get("Content-Disposition", "") disposition, disp_params = _parse_header(disp_header) if disposition != "form-data" or not part.endswith(b("\r\n")): logging.warning("Invalid multipart/form-data") continue value = part[eoh + 4:-2] if not disp_params.get("name"): logging.warning("multipart/form-data value missing name") continue name = disp_params["name"] if disp_params.get("filename"): ctype = headers.get("Content-Type", "application/unknown") files.setdefault(name, []).append(dict( filename=disp_params["filename"], body=value, content_type=ctype)) else: arguments.setdefault(name, []).append(value)
def _parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(';' + line) key = parts.next() pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace('\\\\', '\\').replace('\\"', '"') pdict[name] = value return key, pdict
def add(self, name, value): """Adds a new value for the given key.""" norm_name = HTTPHeaders._normalize_name(name) self._last_key = norm_name if norm_name in self: # bypass our override of __setitem__ since it modifies _as_list dict.__setitem__(self, norm_name, self[norm_name] + ',' + value) self._as_list[norm_name].append(value) else: self[norm_name] = value
def get_list(self, name): """Returns all values for the given header as a list.""" norm_name = HTTPHeaders._normalize_name(name) return self._as_list.get(norm_name, [])
def get_all(self): """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. """ for name, list in self._as_list.iteritems(): for value in list: yield (name, value)
def parse_line(self, line): """Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html' """ if line[0].isspace(): # continuation of a multi-line header new_part = ' ' + line.lstrip() self._as_list[self._last_key][-1] += new_part dict.__setitem__(self, self._last_key, self[self._last_key] + new_part) else: name, value = line.split(":", 1) self.add(name, value.strip())
def parse(cls, headers): """Returns a dictionary from HTTP header text. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n") >>> sorted(h.iteritems()) [('Content-Length', '42'), ('Content-Type', 'text/html')] """ h = cls() for line in headers.splitlines(): if line: h.parse_line(line) return h
def _normalize_name(name): """Converts a name to Http-Header-Case. >>> HTTPHeaders._normalize_name("coNtent-TYPE") 'Content-Type' """ try: return HTTPHeaders._normalized_headers[name] except KeyError: if HTTPHeaders._NORMALIZED_HEADER_RE.match(name): normalized = name else: normalized = "-".join([w.capitalize() for w in name.split("-")]) HTTPHeaders._normalized_headers[name] = normalized return normalized
def utf8(value): """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value assert isinstance(value, unicode) return value.encode("utf-8")
def to_unicode(value): """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value assert isinstance(value, bytes) return value.decode("utf-8")
def to_basestring(value): """Converts a string argument to a subclass of basestring. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two types are not interchangeable, so this method is needed to convert byte strings to unicode. """ if isinstance(value, _BASESTRING_TYPES): return value assert isinstance(value, bytes) return value.decode("utf-8")
def recursive_unicode(obj): """Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries. """ if isinstance(obj, dict): return dict((recursive_unicode(k), recursive_unicode(v)) for (k,v) in obj.iteritems()) elif isinstance(obj, list): return list(recursive_unicode(i) for i in obj) elif isinstance(obj, tuple): return tuple(recursive_unicode(i) for i in obj) elif isinstance(obj, bytes): return to_unicode(obj) else: return obj
def setup(self, app): """ Make sure that other installed plugins don't affect the same keyword argument and check if metadata is available.""" for other in app.plugins: if not isinstance(other, AuthPlugin): continue if other.keyword == self.keyword: raise bottle.PluginError("Found another auth plugin " "with conflicting settings (" "non-unique keyword).")
def iter_subclasses(cls, _seen=None): """ Generator over all subclasses of a given class, in depth-first order. >>> bool in list(iter_subclasses(int)) True >>> class A(object): pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in iter_subclasses(A): ... print(cls.__name__) B D E C >>> # get ALL (new-style) classes currently defined >>> res = [cls.__name__ for cls in iter_subclasses(object)] >>> 'type' in res True >>> 'tuple' in res True >>> len(res) > 100 True """ if not isinstance(cls, type): raise TypeError( 'iter_subclasses must be called with ' 'new-style classes, not %.100r' % cls ) if _seen is None: _seen = set() try: subs = cls.__subclasses__() except TypeError: # fails only when cls is type subs = cls.__subclasses__(cls) for sub in subs: if sub in _seen: continue _seen.add(sub) yield sub for sub in iter_subclasses(sub, _seen): yield sub
def selectPolicy(self, origin, request_method=None): "Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned." ret_origin = None policyname = None if self.matchstrategy in ("firstmatch", "verbmatch"): for pol in self.activepolicies: policy=self.policies[pol] ret_origin = None policyname = policy.name if policyname == "deny": break if self.matchstrategy == "verbmatch": if policy.methods != "*" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True): continue if origin and policy.match: if CORS.matchlist(origin, policy.match): ret_origin = origin elif policy.origin == "copy": ret_origin = origin elif policy.origin: ret_origin = policy.origin if ret_origin: break return policyname, ret_origin
def loads(data, wrapper=dict): """ Loads Appinfo content into a Python object. :param data: A byte-like object with the contents of an Appinfo file. :param wrapper: A wrapping object for key-value pairs. :return: An Ordered Dictionary with Appinfo data. """ if not isinstance(data, (bytes, bytearray)): raise TypeError('can only load a bytes-like object as an Appinfo but got ' + type(data).__name__) return AppinfoDecoder(data, wrapper=wrapper).decode()
def dumps(obj): """ Serializes a dictionary into Appinfo data. :param obj: A dictionary to serialize. :return: """ if not isinstance(obj, dict): raise TypeError('can only dump a dictionary as an Appinfo but got ' + type(obj).__name__) return b''.join(AppinfoEncoder(obj).iter_encode())
def loads(data, wrapper=dict): """ Loads Manifest content into a Python object. :param data: A byte-like object with the contents of an Appinfo file. :param wrapper: A wrapping object for key-value pairs. :return: A dictionary with Manifest data. """ if not isinstance(data, (bytes, bytearray)): raise TypeError('can only load a bytes-like object as a Manifest but got ' + type(data).__name__) offset = 0 parsed = wrapper() int32 = struct.Struct('<I') while True: msg_id, = int32.unpack_from(data, offset) offset += int32.size if msg_id == MSG_EOF: break msg_size, = int32.unpack_from(data, offset) offset += int32.size msg_data = data[offset:offset + msg_size] offset += msg_size message = MessageClass[msg_id]() message.ParseFromString(msg_data) parsed[MSG_NAMES[msg_id]] = wrapper(protobuf_to_dict(message)) return parsed
def dumps(obj): """ Serializes a dictionary into Manifest data. :param obj: A dictionary to serialize. :return: A file object. """ if not isinstance(obj, dict): raise TypeError('can only dump a dictionary as a Manifest but got ' + type(obj).__name__) data = [] int32 = struct.Struct('<I') for message_name in ('payload', 'metadata', 'signature'): message_data = obj[message_name] message_id = MSG_IDS[message_name] message_class = MessageClass[message_id] message = dict_to_protobuf(message_class, message_data) message_bytes = message.SerializeToString() message_size = len(message_bytes) data.append(int32.pack(message_id)) data.append(int32.pack(message_size)) data.append(message_bytes) # MSG_EOF marks the end of messages. data.append(int32.pack(MSG_EOF)) return b''.join(data)
def loads(data, wrapper=dict): """ Loads ACF content into a Python object. :param data: An UTF-8 encoded content of an ACF file. :param wrapper: A wrapping object for key-value pairs. :return: An Ordered Dictionary with ACF data. """ if not isinstance(data, str): raise TypeError('can only load a str as an ACF but got ' + type(data).__name__) parsed = wrapper() current_section = parsed sections = [] lines = (line.strip() for line in data.splitlines()) for line in lines: try: key, value = line.split(None, 1) key = key.replace('"', '').lstrip() value = value.replace('"', '').rstrip() except ValueError: if line == SECTION_START: # Initialize the last added section. current_section = _prepare_subsection(parsed, sections, wrapper) elif line == SECTION_END: # Remove the last section from the queue. sections.pop() else: # Add a new section to the queue. sections.append(line.replace('"', '')) continue current_section[key] = value return parsed
def dumps(obj): """ Serializes a dictionary into ACF data. :param obj: A dictionary to serialize. :return: ACF data. """ if not isinstance(obj, dict): raise TypeError('can only dump a dictionary as an ACF but got ' + type(obj).__name__) return '\n'.join(_dumps(obj, level=0)) + '\n'
def _dumps(obj, level): """ Does the actual serializing of data into an ACF format. :param obj: A dictionary to serialize. :param level: Nesting level. :return: A List of strings. """ lines = [] indent = '\t' * level for key, value in obj.items(): if isinstance(value, dict): # [INDENT]"KEY" # [INDENT]{ line = indent + '"{}"\n'.format(key) + indent + '{' lines.append(line) # Increase intendation of the nested dict lines.extend(_dumps(value, level+1)) # [INDENT]} lines.append(indent + '}') else: # [INDENT]"KEY"[TAB][TAB]"VALUE" lines.append(indent + '"{}"'.format(key) + '\t\t' + '"{}"'.format(value)) return lines
def _prepare_subsection(data, sections, wrapper): """ Creates a subsection ready to be filled. :param data: Semi-parsed dictionary. :param sections: A list of sections. :param wrapper: A wrapping object for key-value pairs. :return: A newly created subsection. """ current = data for i in sections[:-1]: current = current[i] current[sections[-1]] = wrapper() return current[sections[-1]]
def occupancy(grid, points, spacing=0.01): """Return a vector with the occupancy of each grid point for given array of points""" distances = ((grid[:,None,:] - points[None,:,:])**2).sum(axis=2) occupied = (distances < spacing).sum(axis=1) return occupied
def write_gro(outfile, title, atoms, box): """ Write a GRO file. Parameters ---------- outfile The stream to write in. title The title of the GRO file. Must be a single line. atoms An instance of Structure containing the atoms to write. box The periodic box as a 3x3 matrix. """ # Print the title print(title, file=outfile) # Print the number of atoms print("{:5d}".format(len(atoms)), file=outfile) # Print the atoms atom_template = "{:5d}{:<5s}{:>5s}{:5d}{:8.3f}{:8.3f}{:8.3f}" for idx, atname, resname, resid, x, y, z in atoms: print(atom_template .format(int(resid % 1e5), resname, atname, int(idx % 1e5), x, y, z), file=outfile) # Print the box grobox = (box[0][0], box[1][1], box[2][2], box[0][1], box[0][2], box[1][0], box[1][2], box[2][0], box[2][1]) box_template = '{:10.5f}' * 9 print(box_template.format(*grobox), file=outfile)
def write_pdb(outfile, title, atoms, box): """ Write a PDB file. Parameters ---------- outfile The stream to write in. title The title of the GRO file. Must be a single line. atoms An instance of Structure containing the atoms to write. box The periodic box as a 3x3 matrix. """ # Print the title print('TITLE ' + title, file=outfile) # Print the box print(pdbBoxString(box), file=outfile) # Print the atoms for idx, atname, resname, resid, x, y, z in atoms: print(pdbline % (idx % 1e5, atname[:4], resname[:3], "", resid % 1e4, '', 10*x, 10*y, 10*z, 0, 0, ''), file=outfile)
def determine_molecule_numbers(total, molecules, absolute, relative): """Determine molecule numbers for given total, absolute and relative numbers""" weight = sum(relative) if not any(absolute): # Only relative numbers numbers = [int(total*i/weight) for i in relative] elif any(relative): # Absolute numbers and fill the rest with relative numbers rest = total - sum(absolute) numbers = [int(rest*i/weight) if i else j for i,j in zip(relative, absolute)] else: # Only absolute numbers numbers = absolute return list(zip(molecules, numbers))
def resize_pbc_for_lipids(pbc, relL, relU, absL, absU, uparea, area, hole, proteins): """ Adapt the size of the box to accomodate the lipids. The PBC is changed **in place**. """ if any(relL) and any(relU): # Determine box from size # If one leaflet is defined with an absolute number of lipids # then the other leaflet (with relative numbers) will follow # from that. # box/d/x/y/z needed to define unit cell # box is set up already... # yet it may be set to 0, then there is nothing we can do. if 0 in (pbc.x, pbc.y, pbc.z): raise PBCException('Not enough information to set the box size.') elif any(absL) or any(absU): # All numbers are absolute.. determine size from number of lipids # Box x/y will be set, d/dz/z is needed to set third box vector. # The area is needed to determine the size of the x/y plane OR # the area will be SET if a box is given. if pbc.z == 0: raise PBCException('Not enough information to set the box size.') if 0 in (pbc.x, pbc.y): # We do not know what size the box should be. # Let X and Y be the same. #T This does not agree with the default pbc being hexagonal... pbc.x = pbc.y = 1 # A scaling factor is needed for the box # This is the area for the given number of lipids upsize = sum(absU) * uparea losize = sum(absL) * area # This is the size of the hole, going through both leaflets holesize = np.pi * hole ** 2 # This is the area of the PBC xy plane xysize = pbc.x * pbc.y # This is the total area of the proteins per leaflet (IMPLEMENT!) psize_up = sum([p.areaxy(0, 2.4) for p in proteins]) psize_lo = sum([p.areaxy(-2.4, 0) for p in proteins]) # So this is unavailable: unavail_up = holesize + psize_up unavail_lo = holesize + psize_lo # This is the current area marked for lipids # xysize_up = xysize - unavail_up # xysize_lo = xysize - unavail_lo # This is how much the unit cell xy needs to be scaled # to accomodate the fixed amount of lipids with given area. upscale = (upsize + unavail_up)/xysize loscale = (losize + unavail_lo)/xysize area_scale = max(upscale, loscale) aspect_ratio = pbc.x / pbc.y scale_x = np.sqrt(area_scale / aspect_ratio) scale_y = np.sqrt(area_scale / aspect_ratio) pbc.box[:2,:] *= math.sqrt(area_scale)
def write_top(outpath, molecules, title): """ Write a basic TOP file. The topology is written in *outpath*. If *outpath* is en empty string, or anything for which ``bool(outpath) == False``, the topology is written on the standard error, and the header is omitted, and only what has been buit by Insane id displayed (e.g. Proteins are excluded). Parameters ---------- outpath The path to the file to write. If empty, a simplify topology is written on stderr. molecules List of molecules with the number of them. title Title of the system. """ topmolecules = [] for i in molecules: if i[0].endswith('.o'): topmolecules.append(tuple([i[0][:-2]]+list(i[1:]))) else: topmolecules.append(i) if outpath: # Write a rudimentary topology file with open(outpath, "w") as top: print('#include "martini.itp"\n', file=top) print('[ system ]', file=top) print('; name', file=top) print(title, file=top) print('\n', file=top) print('[ molecules ]', file=top) print('; name number', file=top) print("\n".join("%-10s %7d"%i for i in topmolecules), file=top) else: # Here we only include molecules that have beed added by insane. # This is usually concatenated at the end of an existint top file. # As the existing file usually contain the proteins already, we do not # include them here. added_molecules = (molecule for molecule in topmolecules if molecule[0] != 'Protein') print("\n".join("%-10s %7d"%i for i in added_molecules), file=sys.stderr)
def iter_resource(filename): """ Return a stream for a given resource file in the module. The resource file has to be part of the module and its filenane given relative to the module. """ with pkg_resources.resource_stream(__name__, filename) as resource: for line in resource: yield line.decode('utf-8')
def parse(self, string): """ Parse lipid definition from string: alhead=C P, allink=A A, altail=TCC CCCC, alname=DPSM, charge=0.0 """ fields = [i.split("=") for i in string.split(', ')] for what, val in fields: what = what.strip() val = val.split() if what.endswith("head"): self.head = val elif what.endswith("link"): self.link = val elif what.endswith("tail"): self.tail = val elif what == "charge": self.charge = float(val[0]) elif what.endswith("name") and not self.name: self.name = val[0] if self.charge is None: # Infer charge from head groups self.charge = sum([headgroup_charges[bead] for bead in self.head])
def build(self, **kwargs): """Build/return a list of [(bead, x, y, z), ...]""" if not self.coords: if self.beads and self.template: stuff = zip(self.beads, self.template) self.coords = [[i, x, y, z] for i, (x, y, z) in stuff if i != "-"] else: # Set beads/structure from head/link/tail # Set bead names if self.beads: beads = list(self.beads) else: beads = [HEADBEADS[i] for i in self.head] beads.extend([LINKBEADS[n] + str(i + 1) for i, n in enumerate(self.link)]) for i, t in enumerate(self.tail): beads.extend([n + chr(65 + i) + str(j + 1) for j, n in enumerate(t)]) taillength = max([0]+[len(i) for i in self.tail]) length = len(self.head)+taillength # Add the pseudocoordinates for the head rl = range(len(self.head)) struc = [(0, 0, length-i) for i in rl] # Add the linkers rl = range(len(self.link)) struc.extend([(i%2, i//2, taillength) for i in rl ]) # Add the tails for j, tail in enumerate(self.tail): rl = range(len(tail)) struc.extend([(j%2, j//2, taillength-1-i) for i in rl]) mx, my, mz = [ (max(i)+min(i))/2 for i in zip(*struc) ] self.coords = [ [i, 0.25 * (x - mx), 0.25 * (y - my), z] for i, (x, y, z) in zip(beads, struc) ] # Scale the x/y based on the lipid's APL - diameter is less than sqrt(APL) diam = kwargs.get("diam", self.diam) radius = diam*0.45 minmax = [ (min(i), max(i)) for i in list(zip(*self.coords))[1:] ] mx, my, mz = [ sum(i)/2. for i in minmax ] scale = radius/math.sqrt((minmax[0][0]-mx)**2 + (minmax[1][0]-my)**2) for i in self.coords: i[1] = scale*(i[1]-mx) i[2] = scale*(i[2]-my) i[3] -= minmax[2][0] return self.coords
def molspec(x): """ Parse a string for a lipid or a solvent as given on the command line (MOLECULE[=NUMBER|:NUMBER]); where `=NUMBER` sets an absolute number of the molecule, and `:NUMBER` sets a relative number of it. If both absolute and relative number are set False, then relative count is 1. """ lip = x.split(":") abn = lip[0].split("=") names = abn[0] if len(abn) > 1: nrel = 0 nabs = int(abn[1]) else: nabs = 0 if len(lip) > 1: nrel = float(lip[1]) else: nrel = 1 return abn[0], nabs, nrel
def message_user(user, message, level=constants.INFO): """ Send a message to a particular user. :param user: User instance :param message: Message to show :param level: Message level """ # We store a list of messages in the cache so we can have multiple messages # queued up for a user. user_key = _user_key(user) messages = cache.get(user_key) or [] messages.append((message, level)) cache.set(user_key, messages)
def message_users(users, message, level=constants.INFO): """ Send a message to a group of users. :param users: Users queryset :param message: Message to show :param level: Message level """ for user in users: message_user(user, message, level)
def get_messages(user): """ Fetch messages for given user. Returns None if no such message exists. :param user: User instance """ key = _user_key(user) result = cache.get(key) if result: cache.delete(key) return result return None
def process_response(self, request, response): """ Check for messages for this user and, if it exists, call the messages API with it """ if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated(): msgs = get_messages(request.user) if msgs: for msg, level in msgs: messages.add_message(request, level, msg) return response
def check_config_file(msg): """ Checks the config.json file for default settings and auth values. Args: :msg: (Message class) an instance of a message class. """ with jsonconfig.Config("messages", indent=4) as cfg: verify_profile_name(msg, cfg) retrieve_data_from_config(msg, cfg) if msg._auth is None: retrieve_pwd_from_config(msg, cfg) if msg.save: update_config_data(msg, cfg) update_config_pwd(msg, cfg)
def verify_profile_name(msg, cfg): """ Verifies the profile name exists in the config.json file. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance. """ if msg.profile not in cfg.data: raise UnknownProfileError(msg.profile)
def retrieve_data_from_config(msg, cfg): """ Update msg attrs with values from the profile configuration if the msg.attr=None, else leave it alone. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance. """ msg_type = msg.__class__.__name__.lower() for attr in msg: if getattr(msg, attr) is None and attr in cfg.data[msg.profile][msg_type]: setattr(msg, attr, cfg.data[msg.profile][msg_type][attr])
def retrieve_pwd_from_config(msg, cfg): """ Retrieve auth from profile configuration and set in msg.auth attr. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance. """ msg_type = msg.__class__.__name__.lower() key_fmt = msg.profile + "_" + msg_type pwd = cfg.pwd[key_fmt].split(" :: ") if len(pwd) == 1: msg.auth = pwd[0] else: msg.auth = tuple(pwd)
def update_config_data(msg, cfg): """ Updates the profile's config entry with values set in each attr by the user. This will overwrite existing values. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance. """ for attr in msg: if attr in cfg.data[msg.profile] and attr is not "auth": cfg.data[msg.profile][attr] = getattr(msg, attr)
def update_config_pwd(msg, cfg): """ Updates the profile's auth entry with values set by the user. This will overwrite existing values. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance. """ msg_type = msg.__class__.__name__.lower() key_fmt = msg.profile + "_" + msg_type if isinstance(msg._auth, (MutableSequence, tuple)): cfg.pwd[key_fmt] = " :: ".join(msg._auth) else: cfg.pwd[key_fmt] = msg._auth
def create_config_profile(msg_type): """ Create a profile for the given message type. Args: :msg_type: (str) message type to create config entry. """ msg_type = msg_type.lower() if msg_type not in CONFIG.keys(): raise UnsupportedMessageTypeError(msg_type) display_required_items(msg_type) if get_user_ack(): profile_name = input("Profile Name: ") data = get_data_from_user(msg_type) auth = get_auth_from_user(msg_type) configure_profile(msg_type, profile_name, data, auth)
def display_required_items(msg_type): """ Display the required items needed to configure a profile for the given message type. Args: :msg_type: (str) message type to create config entry. """ print("Configure a profile for: " + msg_type) print("You will need the following information:") for k, v in CONFIG[msg_type]["settings"].items(): print(" * " + v) print("Authorization/credentials required:") for k, v in CONFIG[msg_type]["auth"].items(): print(" * " + v)
def get_data_from_user(msg_type): """Get the required 'settings' from the user and return as a dict.""" data = {} for k, v in CONFIG[msg_type]["settings"].items(): data[k] = input(v + ": ") return data
def get_auth_from_user(msg_type): """Get the required 'auth' from the user and return as a dict.""" auth = [] for k, v in CONFIG[msg_type]["auth"].items(): auth.append((k, getpass(v + ": "))) return OrderedDict(auth)
def configure_profile(msg_type, profile_name, data, auth): """ Create the profile entry. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :auth: (dict) auth parameters """ with jsonconfig.Config("messages", indent=4) as cfg: write_data(msg_type, profile_name, data, cfg) write_auth(msg_type, profile_name, auth, cfg) print("[+] Configuration entry for <" + profile_name + "> created.") print("[+] Configuration file location: " + cfg.filename)
def write_data(msg_type, profile_name, data, cfg): """ Write the settings into the data portion of the cfg. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :data: (dict) dict values for the 'settings' :cfg: (jsonconfig.Config) config instance. """ if profile_name not in cfg.data: cfg.data[profile_name] = {} cfg.data[profile_name][msg_type] = data
def write_auth(msg_type, profile_name, auth, cfg): """ Write the settings into the auth portion of the cfg. Args: :msg_type: (str) message type to create config entry. :profile_name: (str) name of the profile entry :auth: (dict) auth parameters :cfg: (jsonconfig.Config) config instance. """ key_fmt = profile_name + "_" + msg_type pwd = [] for k, v in CONFIG[msg_type]["auth"].items(): pwd.append(auth[k]) if len(pwd) > 1: cfg.pwd[key_fmt] = " :: ".join(pwd) else: cfg.pwd[key_fmt] = pwd[0]
def _construct_message(self): """Build the message params.""" self.message["text"] = "" if self.from_: self.message["text"] += "From: " + self.from_ + "\n" if self.subject: self.message["text"] += "Subject: " + self.subject + "\n" self.message["text"] += self.body self._add_attachments()
def _add_attachments(self): """Add attachments.""" if self.attachments: if not isinstance(self.attachments, list): self.attachments = [self.attachments] self.message["attachments"] = [ {"image_url": url, "author_name": ""} for url in self.attachments ] if self.params: for attachment in self.message["attachments"]: attachment.update(self.params)
def send(self, encoding="json"): """Send the message via HTTP POST, default is json-encoded.""" self._construct_message() if self.verbose: print( "Debugging info" "\n--------------" "\n{} Message created.".format(timestamp()) ) if encoding == "json": resp = requests.post(self.url, json=self.message) elif encoding == "url": resp = requests.post(self.url, data=self.message) try: resp.raise_for_status() if resp.history and resp.history[0].status_code >= 300: raise MessageSendError("HTTP Redirect: Possibly Invalid authentication") elif "invalid_auth" in resp.text: raise MessageSendError("Invalid Auth: Possibly Bad Auth Token") except (requests.exceptions.HTTPError, MessageSendError) as e: raise MessageSendError(e) if self.verbose: print( timestamp(), type(self).__name__, " info:", self.__str__(indentation="\n * "), "\n * HTTP status code:", resp.status_code, ) print("Message sent.")
def _construct_message(self): """Set the message token/channel, then call the bas class constructor.""" self.message = {"token": self._auth, "channel": self.channel} super()._construct_message()
def send(msg_type, send_async=False, *args, **kwargs): """ Constructs a message class and sends the message. Defaults to sending synchronously. Set send_async=True to send asynchronously. Args: :msg_type: (str) the type of message to send, i.e. 'Email' :send_async: (bool) default is False, set True to send asynchronously. :kwargs: (dict) keywords arguments that are required for the various message types. See docstrings for each type. i.e. help(messages.Email), help(messages.Twilio), etc. Example: >>> kwargs = { from_: 'me@here.com', to: 'you@there.com', auth: 'yourPassword', subject: 'Email Subject', body: 'Your message to send', attachments: ['filepath1', 'filepath2'], } >>> messages.send('email', **kwargs) Message sent... """ message = message_factory(msg_type, *args, **kwargs) try: if send_async: message.send_async() else: message.send() except MessageSendError as e: err_exit("Unable to send message: ", e)
def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs): """ Factory function to return the specified message instance. Args: :msg_type: (str) the type of message to send, i.e. 'Email' :msg_types: (str, list, or set) the supported message types :kwargs: (dict) keywords arguments that are required for the various message types. See docstrings for each type. i.e. help(messages.Email), help(messages.Twilio), etc. """ try: return msg_types[msg_type.lower()](*args, **kwargs) except (UnknownProfileError, InvalidMessageInputError) as e: err_exit("Unable to send message: ", e) except KeyError: raise UnsupportedMessageTypeError(msg_type, msg_types)
def credential_property(cred): """ A credential property factory for each message class that will set private attributes and return obfuscated credentials when requested. """ def getter(instance): return "***obfuscated***" def setter(instance, value): private = "_" + cred instance.__dict__[private] = value return property(fget=getter, fset=setter)