matplotlib OSError:[Errno 36]文件名太长- Base 64

rnmwe5a2  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(392)

目前,我正在制作一个不和谐的机器人,有一个图形/条形图图像implimented在它(。我正在使用matplotlib,条形图已经工作了。然而,matplotlib输出的基数64远远超过2000个字符。
所以我试着:
return send_file(data[short_url], mimetype='image/png')
导致OSError:[错误号36]文件名太长
然后我尝试在discord命令本身中实现它。显然,由于它是2000+字符太长,它没有工作。
这就是我现在所拥有的,我甚至在这一点上做了我自己的URL缩短器:

def generate_short_url():
    with open("urls.json", "r") as f:
      data = json.load(f)
    while True:
      characters = string.ascii_letters + string.digits
      short_url = ''.join(random.choice(characters) for _ in range(6))
      if not short_url in data:
        break
    return short_url

@app.route("/api/barchart/<info>")
def bcrt(info):
    info = ast.literal_eval(info)
    lps = 0
    for i in info:
        lps += 1
        if lps == 1:
            name = info[i]
        else:
            stats = info[i]
    stats_labels = list(stats.keys())
    stats_values = list(stats.values())

    fig, ax = plt.subplots(1, 1)

    total_value = sum(stats_values)
    chart_size = 100
    normalized_values = [value / total_value for value in stats_values]
    bar_sizes = [value * chart_size/100 for value in stats_values]

    ax.barh(stats_labels, bar_sizes, color='#CB3E3E', edgecolor='none', height=0.5)
    ax.set_xlim(0, 100)
    ax.set_ylabel('Stats', color='white')
    ax.set_xlabel('Points', color='white')
    ax.set_title(f"{name} Magic", color='white')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.xaxis.set_ticks_position('none')
    ax.yaxis.set_ticks_position('none')
    ax.xaxis.set_tick_params(width=0)
    ax.yaxis.set_tick_params(width=0)
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))

    ax.grid(axis='x', linestyle='-', linewidth=0.2, alpha=0.5)
    fig.set_size_inches(6, 4)

    ax.set_facecolor('none')
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')

    for spine in ax.spines.values():
        spine.set_edgecolor('white')

    for text_object in ax.texts:
        text_object.set_color('white')

    chart_bytes = io.BytesIO()
    plt.savefig(chart_bytes, format='png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.close(fig)

    chart_bytes.seek(0)
    chart_base64 = base64.b64encode(chart_bytes.getvalue()).decode('utf-8')

    short_url = generate_short_url()

    with open("urls.json", "r") as f:
      data = json.load(f)
    data[short_url] = chart_base64
    with open("urls.json", "w") as f:
      json.dump(data, f, indent=2)
    full_short_url = '{"url": "https://asvxin.xyz/api/url/' +str(short_url) + '"}'

    return full_short_url

@app.route("/api/url/<short_url>.png")
def redirect_to_chart(short_url):
    with open("urls.json", "r") as f:
      data = json.load(f)
    if short_url in data:
        return send_file(data[short_url], mimetype='image/png')

    return "Error"
sulc1iza

sulc1iza1#

多亏了Udhay,我得到了答案。

def save_chart_image(chart_bytes, short_url):
    folder = "images"
    if not os.path.exists(folder):
        os.makedirs(folder)
    file_path = os.path.join(folder, f"{short_url}.png")
    with open(file_path, "wb") as f:
        f.write(chart_bytes.getvalue())
    return file_path

相关问题