首页 > 解决方案 > Got RuntimeError: unsupported value when trying to insert binary data into a blob field in a sqlite3 table using python

问题描述

So I'm currently working in a personal project using flask that graphs a user's table and then rendesr it in a different page. However, when I try to do this I get the folowing error: RuntimeError: unsupported value. I have tried all sorts of stuff and none of it has worked. Any help would be appreciated.

Application.py:

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from helpers import apology, login_required, toBinary

#configure application
app = Flask(__name__)

#Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

#Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///graph.db")
@login_required
def graph():
#check wether to return user to a form or graph their table
    if request.method == "POST":

        #define variables
        table_name = request.form.get("table_name")
        x_axis = request.form.get("x_axis")
        y_axis = request.form.get("y_axis")
        x_values = list(request.form.get("x_values"))
        y_values = list(request.form.get("y_values"))
        graph_type = request.form.get("graph_type")

        #check wether there is an x value for every y value
        if len(x_values) != len(y_values):
            return apology("Every x value must have a y value and viceversa", code=400)

        #check graph type to use
        if graph_type == "line":

            plt.plot(x_values, y_values)


        elif graph_type == "bar":

            height = []
            first_value = min(y_values) - 1

            for x in y_values:
                height.append(x%first_value)

            plt.bar(x_values, height)

        else:
            plt.scatter(x_values, y_values)

        plt.xlabel(x_axis)
        plt.ylabel(y_axis)
        plt.savefig("user_graph")

        #set user_graph.png PATH
        script_location = Path(__file__).absolute().parent
        file_location = script_location / 'user_graph.png'

        #pass graph to binary
        user_graph = toBinary(file_location)
        print(user_graph)

        #insert user table into history for later use
        db.execute("INSERT INTO history (username, graph, table_name) VALUES(:username, :graph, :table_name)", username=session["username"], graph=user_graph, table_name=table_name)

        return render_template("graphed.html")

    else:
        return render_template("graph.html")

toBinary code:

    with open(filename, "rb") as file:
        data = file.read()
    return data```

标签: pythonsqlitebinary

解决方案


要插入 BLOB 值,VALUE 必须采用字节流/数组作为十六进制值的格式x'??????',例如。因此,您需要将字节流/数组转换为这样的字符串,然后可以使用该字符串。??????x'FFFE1266543267890A'


推荐阅读