在Python中禁用Plotly以任何形式与网络通信

Pon*_*ars 7 python networking plotly

是否有可能获得Plotly(在Python中使用)"严格本地"?换句话说,是否可以以保证不会因任何原因联系网络的方式使用它?

这包括试图联系Plotly服务的程序(因为那是商业模式),以及确保在生成的html中的任何地方点击都不会有Plotly或其他任何地方的链接.

当然,我希望能够在连接到网络的生产机器上执行此操作,因此不能选择拔出网络连接.

Sam*_*Sam 1

我想我已经为此想出了一个解决方案。首先,您需要下载开源 Plotly.js文件。然后我有一个函数,写在下面,它将从 python 图中生成 javascript 并引用您的本地副本的plotly-latest.min.js。见下文:

import sys
import os
from plotly import session, tools, utils
import uuid
import json

def get_plotlyjs():
    path = os.path.join('offline', 'plotly.min.js')
    plotlyjs = resource_string('plotly', path).decode('utf-8')
    return plotlyjs


def js_convert(figure_or_data,outfilename, show_link=False, link_text='Export to plot.ly',
          validate=True):

    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

    width = figure.get('layout', {}).get('width', '100%')
    height = figure.get('layout', {}).get('height', 525)
    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    plotdivid = uuid.uuid4()
    jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder)
    jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder)

    config = {}
    config['showLink'] = show_link
    config['linkText'] = link_text
    config["displaylogo"]=False
    config["modeBarButtonsToRemove"]= ['sendDataToCloud']
    jconfig = json.dumps(config)

    plotly_platform_url = session.get_session_config().get('plotly_domain',
                                                           'https://plot.ly')
    if (plotly_platform_url != 'https://plot.ly' and
            link_text == 'Export to plot.ly'):

        link_domain = plotly_platform_url\
            .replace('https://', '')\
            .replace('http://', '')
        link_text = link_text.replace('plot.ly', link_domain)


    script = '\n'.join([
        'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{',
        '    $(".{id}.loading").remove();',
        '}})'
    ]).format(id=plotdivid,
              data=jdata,
              layout=jlayout,
              config=jconfig)

    html="""<div class="{id} loading" style="color: rgb(50,50,50);">
                 Drawing...</div>
                 <div id="{id}" style="height: {height}; width: {width};" 
                 class="plotly-graph-div">
                 </div>
                 <script type="text/javascript">
                 {script}
                 </script>
                 """.format(id=plotdivid, script=script,
                           height=height, width=width)

    #html =  html.replace('\n', '')
    with open(outfilename, 'wb') as out:
        #out.write(r'<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>')
        out.write(r'<script src="plotly-latest.min.js"></script>')
        for line in html.split('\n'):
            out.write(line)

        out.close()
    print ('JS Conversion Complete')
Run Code Online (Sandbox Code Playgroud)

删除所有链接的关键行是:

config['showLink'] = show_link #False
....
config["modeBarButtonsToRemove"]= ['sendDataToCloud']
Run Code Online (Sandbox Code Playgroud)

您可以这样调用该函数来获取引用您的本地开源库副本的静态 HTML 文件:

fig = {
"data": [{
    "x": [1, 2, 3],
    "y": [4, 2, 5]
}],
"layout": {
    "title": "hello world"
}
}
js_convert(fig, 'test.html')
Run Code Online (Sandbox Code Playgroud)