def _load_graph_ref(): graph_reference_dir = "graph_reference" json_files = ["graph_objs_meta.json", "OBJ_MAP.json", "NAME_TO_KEY.json", "KEY_TO_NAME.json"] out = [] for json_file in json_files: relative_path = os.path.join(graph_reference_dir, json_file) s = resource_string("plotly", relative_path).decode("utf-8") tmp = json.loads(s, object_pairs_hook=OrderedDict) tmp = utils.decode_unicode(tmp) out += [tmp] return tuple(out)
def get_graph_reference(): """ Load graph reference JSON (aka plot-schema) :return: (dict) The graph reference. """ path = os.path.join('package_data', 'default-schema.json') s = resource_string('plotly', path).decode('utf-8') graph_reference = _json.loads(s) return utils.decode_unicode(graph_reference)
def _load_graph_ref(): graph_reference_dir = 'graph_reference' json_files = [ 'graph_objs_meta.json', 'OBJ_MAP.json', 'NAME_TO_KEY.json', 'KEY_TO_NAME.json' ] out = [] for json_file in json_files: relative_path = os.path.join(graph_reference_dir, json_file) s = resource_string('plotly', relative_path).decode('utf-8') tmp = json.loads(s, object_pairs_hook=OrderedDict) tmp = utils.decode_unicode(tmp) out += [tmp] return tuple(out)
def get_graph_reference(): """ Attempts to load local copy of graph reference or makes GET request if DNE. :return: (dict) The graph reference. :raises: (PlotlyError) When graph reference DNE and GET request fails. """ default_config = files.FILE_CONTENT[files.CONFIG_FILE] if files.check_file_permissions(): graph_reference = utils.load_json_dict(files.GRAPH_REFERENCE_FILE) config = utils.load_json_dict(files.CONFIG_FILE) # TODO: https://github.com/plotly/python-api/issues/293 plotly_api_domain = config.get('plotly_api_domain', default_config['plotly_api_domain']) else: graph_reference = {} plotly_api_domain = default_config['plotly_api_domain'] sha1 = hashlib.sha1(six.b(str(graph_reference))).hexdigest() graph_reference_url = '{}{}?sha1={}'.format(plotly_api_domain, GRAPH_REFERENCE_PATH, sha1) try: response = http_requests.get(graph_reference_url, timeout=GRAPH_REFERENCE_DOWNLOAD_TIMEOUT) response.raise_for_status() except http_requests.exceptions.RequestException: if not graph_reference: path = os.path.join('graph_reference', 'default-schema.json') s = resource_string('plotly', path).decode('utf-8') graph_reference = json.loads(s) else: if six.PY3: content = str(response.content, encoding='utf-8') else: content = response.content data = json.loads(content) if data['modified']: graph_reference = data['schema'] return utils.decode_unicode(graph_reference)
def _load_graph_ref(): """ A private method to load the graph reference json files. :return: (tuple) A tuple of dict objects. """ out = [] # this splits directory path from basenames filenames = [ os.path.split(GRAPH_REFERENCE_GRAPH_OBJS_META)[-1], os.path.split(GRAPH_REFERENCE_OBJ_MAP)[-1], os.path.split(GRAPH_REFERENCE_NAME_TO_KEY)[-1], os.path.split(GRAPH_REFERENCE_KEY_TO_NAME)[-1] ] for filename in filenames: path = os.path.join(sys.prefix, GRAPH_REFERENCE_DIR, filename) with open(path, 'r') as f: tmp = json.load(f, object_pairs_hook=OrderedDict) tmp = utils.decode_unicode(tmp) out += [tmp] return tuple(out)
def get_graph_reference(): """ Load graph reference JSON (aka plot-schema) :return: (dict) The graph reference. """ path = os.path.join('package_data', 'plot-schema.json') s = resource_string('plotly', path).decode('utf-8') graph_reference = utils.decode_unicode(_json.loads(s)) # TODO: Patch in frames info until it hits streambed. See #659 graph_reference['frames'] = { "items": { "frames_entry": { "baseframe": { "description": "The name of the frame into which this " "frame's properties are merged before " "applying. This is used to unify " "properties and avoid needing to specify " "the same values for the same properties " "in multiple frames.", "role": "info", "valType": "string" }, "data": { "description": "A list of traces this frame modifies. " "The format is identical to the normal " "trace definition.", "role": "object", "valType": "any" }, "group": { "description": "An identifier that specifies the group " "to which the frame belongs, used by " "animate to select a subset of frames.", "role": "info", "valType": "string" }, "layout": { "role": "object", "description": "Layout properties which this frame " "modifies. The format is identical to " "the normal layout definition.", "valType": "any" }, "name": { "description": "A label by which to identify the frame", "role": "info", "valType": "string" }, "role": "object", "traces": { "description": "A list of trace indices that identify " "the respective traces in the data " "attribute", "role": "info", "valType": "info_array" } } }, "role": "object" } return graph_reference
def get_figure(file_owner_or_url, file_id=None, raw=False): """Returns a JSON figure representation for the specified file Plotly uniquely identifies figures with a 'file_owner'/'file_id' pair. Since each file is given a corresponding unique url, you may also simply pass a valid plotly url as the first argument. Note, if you're using a file_owner string as the first argument, you MUST specify a `file_id` keyword argument. Else, if you're using a url string as the first argument, you MUST NOT specify a `file_id` keyword argument, or file_id must be set to Python's None value. Positional arguments: file_owner_or_url (string) -- a valid plotly username OR a valid plotly url Keyword arguments: file_id (default=None) -- an int or string that can be converted to int if you're using a url, don't fill this in! raw (default=False) -- if true, return unicode JSON string verbatim** **by default, plotly will return a Figure object (run help(plotly .graph_objs.Figure)). This representation decodes the keys and values from unicode (if possible), removes information irrelevant to the figure representation, and converts the JSON dictionary objects to plotly `graph objects`. """ plotly_rest_url = get_config()['plotly_domain'] if file_id is None: # assume we're using a url url = file_owner_or_url if url[:len(plotly_rest_url)] != plotly_rest_url: raise exceptions.PlotlyError( "Because you didn't supply a 'file_id' in the call, " "we're assuming you're trying to snag a figure from a url. " "You supplied the url, '{0}', we expected it to start with " "'{1}'." "\nRun help on this function for more information." "".format(url, plotly_rest_url)) head = plotly_rest_url + "/~" file_owner = url.replace(head, "").split('/')[0] file_id = url.replace(head, "").split('/')[1] else: file_owner = file_owner_or_url resource = "/apigetfile/{username}/{file_id}".format(username=file_owner, file_id=file_id) (username, api_key) = _validation_key_logic() headers = {'plotly-username': username, 'plotly-apikey': api_key, 'plotly-version': version.__version__, 'plotly-platform': 'python'} try: test_if_int = int(file_id) except ValueError: raise exceptions.PlotlyError( "The 'file_id' argument was not able to be converted into an " "integer number. Make sure that the positional 'file_id' argument " "is a number that can be converted into an integer or a string " "that can be converted into an integer." ) if int(file_id) < 0: raise exceptions.PlotlyError( "The 'file_id' argument must be a non-negative number." ) response = requests.get(plotly_rest_url + resource, headers=headers, verify=get_config()['plotly_ssl_verification']) if response.status_code == 200: if six.PY3: content = json.loads(response.content.decode('unicode_escape')) else: content = json.loads(response.content) response_payload = content['payload'] figure = response_payload['figure'] utils.decode_unicode(figure) if raw: return figure else: return tools.get_valid_graph_obj(figure, obj_type='Figure') else: try: content = json.loads(response.content) raise exceptions.PlotlyError(content) except: raise exceptions.PlotlyError( "There was an error retrieving this file")
def get_figure(file_owner_or_url, file_id=None, raw=False): """Returns a JSON figure representation for the specified file Plotly uniquely identifies figures with a 'file_owner'/'file_id' pair. Since each file is given a corresponding unique url, you may also simply pass a valid plotly url as the first argument. Note, if you're using a file_owner string as the first argument, you MUST specify a `file_id` keyword argument. Else, if you're using a url string as the first argument, you MUST NOT specify a `file_id` keyword argument, or file_id must be set to Python's None value. Positional arguments: file_owner_or_url (string) -- a valid plotly username OR a valid plotly url Keyword arguments: file_id (default=None) -- an int or string that can be converted to int if you're using a url, don't fill this in! raw (default=False) -- if true, return unicode JSON string verbatim** **by default, plotly will return a Figure object (run help(plotly .graph_objs.Figure)). This representation decodes the keys and values from unicode (if possible), removes information irrelevant to the figure representation, and converts the JSON dictionary objects to plotly `graph objects`. """ plotly_rest_url = get_config()['plotly_domain'] if file_id is None: # assume we're using a url url = file_owner_or_url if url[:len(plotly_rest_url)] != plotly_rest_url: raise exceptions.PlotlyError( "Because you didn't supply a 'file_id' in the call, " "we're assuming you're trying to snag a figure from a url. " "You supplied the url, '{0}', we expected it to start with " "'{1}'." "\nRun help on this function for more information." "".format(url, plotly_rest_url)) head = plotly_rest_url + "/~" file_owner = url.replace(head, "").split('/')[0] file_id = url.replace(head, "").split('/')[1] else: file_owner = file_owner_or_url resource = "/apigetfile/{username}/{file_id}".format(username=file_owner, file_id=file_id) (username, api_key) = _validation_key_logic() headers = {'plotly-username': username, 'plotly-apikey': api_key, 'plotly-version': version.__version__, 'plotly-platform': 'python'} try: test_if_int = int(file_id) except ValueError: raise exceptions.PlotlyError( "The 'file_id' argument was not able to be converted into an " "integer number. Make sure that the positional 'file_id' argument " "is a number that can be converted into an integer or a string " "that can be converted into an integer." ) if int(file_id) < 0: raise exceptions.PlotlyError( "The 'file_id' argument must be a non-negative number." ) response = requests.get(plotly_rest_url + resource, headers=headers) if response.status_code == 200: if six.PY3: content = json.loads(response.content.decode('unicode_escape')) else: content = json.loads(response.content) response_payload = content['payload'] figure = response_payload['figure'] utils.decode_unicode(figure) if raw: return figure else: return tools.get_valid_graph_obj(figure, obj_type='Figure') else: try: content = json.loads(response.content) raise exceptions.PlotlyError(content) except: raise exceptions.PlotlyError( "There was an error retrieving this file")
def get_graph_reference(): """ Load graph reference JSON (aka plot-schema) :return: (dict) The graph reference. """ path = os.path.join("package_data", "default-schema.json") s = resource_string("plotly", path).decode("utf-8") graph_reference = utils.decode_unicode(_json.loads(s)) # TODO: Patch in frames info until it hits streambed. See #659 graph_reference["frames"] = { "items": { "frames_entry": { "baseframe": { "description": "The name of the frame into which this " "frame's properties are merged before " "applying. This is used to unify " "properties and avoid needing to specify " "the same values for the same properties " "in multiple frames.", "role": "info", "valType": "string", }, "data": { "description": "A list of traces this frame modifies. " "The format is identical to the normal " "trace definition.", "role": "object", "valType": "any", }, "group": { "description": "An identifier that specifies the group " "to which the frame belongs, used by " "animate to select a subset of frames.", "role": "info", "valType": "string", }, "layout": { "role": "object", "description": "Layout properties which this frame " "modifies. The format is identical to " "the normal layout definition.", "valType": "any", }, "name": {"description": "A label by which to identify the frame", "role": "info", "valType": "string"}, "role": "object", "traces": { "description": "A list of trace indices that identify " "the respective traces in the data " "attribute", "role": "info", "valType": "info_array", }, } }, "role": "object", } return graph_reference