sqlalchemy - (ProgrammingError)可以解释8位字节串

时间:2014-05-26 19:08:41

标签: sqlite python-2.7 sqlalchemy

我正在使用SqlAlchemy和python 2.7.6

我遇到了:

  

sqlalchemy.exc.ProgrammingError :( ProgrammingError)您不能使用8位字节   除非你使用一个可以解释8位字节串的text_factory(比如   text_factory = str)。强烈建议您只需切换即可   应用于Unicode字符串。 u'INSERT INTO algoritimo(“nomeAlgoritimo”,clas   se,“estruturaDados”,“complexidadePiorCaso”,“complexidadeMedioCaso”,“complexi”   dadeMelhorCaso“,”complexidadeEspacos“,”pseudoAlgoritimo“)VALUES(?,?,?,?,   ?,?,?,?)'('Ordena \ xe7 \ xe3o Sele \ xe7 \ xe3o','Algoritmo de oderna \ xe7 \ xe3o','   数组,Listas ligadas','O(n ^ 2)','O(n ^ 2)','O(n ^ 2)','O(n)total,O(1)auxiliar   ','')

我用:

  

Base = declarative_base()   engine = create_engine('sqlite:///classificacao_pesquisa.db')

class Algoritimo(Base):
    __tablename__ = 'algoritimo'
    id = Column(Integer, primary_key=True)
    nomeAlgoritimo = Column(String(50))
    classe = Column(String(250))
    estruturaDados = Column(String(50))
    complexidadePiorCaso = Column(String(50))
    complexidadeMedioCaso = Column(String(50))
    complexidadeMelhorCaso = Column(String(50))
    complexidadeEspacos = Column(String(50))
    pseudoAlgoritimo = Column(String(4000))

你有任何提示吗?

2 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,这是解决方案;

https://bitcoinwisdom.com/markets/bitstamp/btcusd

如上面的文档中所述db.Unicode类型是不够的,你仍然必须以你的字符串形式发送字符串';

  

关于Unicode类型的常见混淆源是它   打算只处理Python端的Python unicode对象,   作为绑定参数传递给它的含义值必须是形式   你的字符串'如果使用Python 2而不是3.编码/解码   它执行的功能只适合所使用的DBAPI,   并且主要是私人实施细节。

因此,您可以使用TypeDecorator创建自己的Type;

    HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 320
Content-Type: application/json; charset=utf-8
Expires: -1
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
apim-request-id: ef73d48d-ab35-4fa5-a346-c57339415824
Date: Thu, 21 Jul 2016 20:00:12 GMT

{"candidates":[{"words":"i want to break free","probability":-7.1759999999999993},{"words":"iwant to break free","probability":-9.1660000000000021},{"words":"i want to breakfree","probability":-9.547},{"words":"i wan t to break free","probability":-9.8390000000000022},{"words":"iwanttobreakfree","probability":-9.877}]}
--------
bool(true)

用法:

from sqlalchemy.types import TypeDecorator, Unicode

class CoerceUTF8(TypeDecorator):
    """Safely coerce Python bytestrings to Unicode
    before passing off to the database."""

    impl = Unicode

    def process_bind_param(self, value, dialect):
        if isinstance(value, str):
            value = value.decode('utf-8')
        return value

答案 1 :(得分:1)

在需要Unicode string type的位置使用db.Column(db.UnicodeText(64))