zoukankan      html  css  js  c++  java
  • [Python]sqlite3二进制文件存储问题(BLOB)(You must not use 8-bit bytestrings unless you use a text_factory...)

    事情是这种:


    博主尝试用Python的sqlite3数据库存放加密后的usernamepassword信息,表是这种

    CREATE TABLE IF NOT EXISTS user
    			(
    			userID INTEGER PRIMARY KEY AUTOINCREMENT,
    			userStudentID BLOB NOT NULL UNIQUE ON CONFLICT IGNORE,
    			userPassword BLOB NOT NULL
    			);

    当中userStudentID and UserPassword 储存成了BLOB类型,作为二进制存储。

    但当博主把加密后的字节串插入数据库时。却报出例如以下错误:

    sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.

    显然它把博主的字节串当成了未经编码的字符串。

    此时不能參考它的做法。把text_factory 置为 str,这种话博主的密文就会被编码存放(如utf-8),而假设有些字节无法按utf-8编码的话,就会引发异常或被忽略。


    网上搜了好多文章,均没有解决博主的问题。

    后来还是找到了Official Document



    https://docs.python.org/2/library/sqlite3.html#module-sqlite3

    原来Python中与sqlite3的BLOB相应的数据类型为buffer,博主惊出一身冷汗,忙看了下自己的插入部分的代码:

    def insertUsernameAndPasswordToDB(conn, cu, username, password):
    	username = encrypt(username)
    	password = encrypt(password)
    	cu.execute("INSERT INTO user(userStudentID, userPassword) VALUES (?,?)", (username, password) )
    	conn.commit()

    測试了下username和password的数据类型

    print isinstance(username, str)
    print isinstance(password, str)
    
    结果均为True。怪不得sqlite3尝试把他们按字符串的形式存储。这里又涉及一个知识,sqlite3用的是动态的数据类型系统。它会依照数据的值来尝试将数据转换成数据库内部的标准类型。这里它就尝试将我的字节串密文转换成字符串。

    參考资料:http://www.cnblogs.com/kfqcome/archive/2011/06/27/2137000.html


    将username和password转换成buffer类型,问题解决。

    def insertUsernameAndPasswordToDB(conn, cu, username, password):
    	username = encrypt(username)
    	password = encrypt(password)
    	cu.execute("INSERT INTO user(userStudentID, userPassword) VALUES (?

    ,?)", (buffer(username), buffer(password)) ) conn.commit()





    微博:@浙大宋博

  • 相关阅读:
    {转}每次从vss获取文件都是只读
    點擊按鈕后彈出新頁面導致原頁面CSS失效
    Mschat控件示例升级错误处理方法
    一个简单的使用EVP框架的加密过程 aes 128 ecb
    centos7的syslog知识点
    pam模块使用syslog日志调试
    Linux系统上的popen()库函数
    linux C语言 用openssl进行签名验签 --- 亲测2 sha256 sha512
    linux C语言 用openssl进行签名验签 --- 亲测 sha256 sha512
    k8s简介
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5079622.html
Copyright © 2011-2022 走看看