代码:
from sipevents import db from sipevents import app from sipevents import models from sipevents import User, Event from datetime import datetime from datetime import timedelta # test Event create/query/delete startDatetime = datetime.now() app.logger.debug(‘startDatetime=%s’, startDatetime) oneDayDelta = timedelta(days=1) app.logger.debug(‘oneDayDelta=%s’, oneDayDelta) endDatetime = startDatetime + oneDayDelta app.logger.debug(‘endDatetime=%s’, endDatetime) eventDict = { ‘id’ : 1, ‘user_openid’ : crifanUserJson[‘openid’], ‘title’ : “讨论日历的公众号名字”, ‘start_date’ : startDatetime, ‘end_date’ : endDatetime, ‘user_limit’ : 5, ‘is_public’ : False, ‘description’ : “头脑风暴讨论公众号的名字”, } app.logger.debug(‘eventDict=%s’, eventDict) existedEvent= Event.query.filter_by(id=eventDict[‘id’]).first() app.logger.debug(‘existedEvent=%s’, existedEvent) if existedEvent : # has exsited this event app.logger.debug(u’已存在此活动 existedEvent=%r’, existedEvent) else : eventObj = Event(id = eventDict[‘id’], user_openid = eventDict[‘user_openid’], title = eventDict[‘title’], start_date = eventDict[‘start_date’], end_date = eventDict[‘end_date’], user_limit = eventDict[‘user_limit’], is_public = eventDict[‘is_public’], description = eventDict[‘description’]) app.logger.debug(‘eventObj=%s’, eventObj) db.session.add(eventObj) db.session.commit() app.logger.debug(‘added eventObj=%s’, eventObj) currentEvents= Event.query.all() app.logger.debug(‘currentEvents=%s’, currentEvents) currentEventsCount = len(currentEvents) app.logger.debug(‘currentEventsCount=%s’, currentEventsCount) if currentEventsCount > 0 : firstEvent = currentEventsCount[0] app.logger.debug(‘firstEvent=%s’, firstEvent) db.session.delete(firstEvent) db.session.commit() app.logger.debug(‘deleted firstEvent=%s’, firstEvent) |
出错:
<div–<—————————————————————————— DEBUG in db_create [db_create.py:114]: eventObj=<Event id=1 user_openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY title=讨论日历的公众号名字> <div–<—————————————————————————— Traceback (most recent call last): File “db_create.py”, line 117, in <module> db.session.commit() File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py”, line 157, in do return getattr(self.registry(), name)(*args, **kwargs) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/session.py”, line 801, in commit self.transaction.commit() File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/session.py”, line 392, in commit self._prepare_impl() File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/session.py”, line 372, in _prepare_impl self.session.flush() File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/session.py”, line 2019, in flush self._flush(objects) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/session.py”, line 2137, in _flush transaction.rollback(_capture_exception=True) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py”, line 60, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/session.py”, line 2101, in _flush flush_context.execute() File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py”, line 373, in execute rec.execute(self) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py”, line 532, in execute uow File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py”, line 174, in save_obj mapper, table, insert) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py”, line 767, in _emit_insert_statements execute(statement, multiparams) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/engine/base.py”, line 914, in execute return meth(self, multiparams, params) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/sql/elements.py”, line 323, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/engine/base.py”, line 1010, in _execute_clauseelement compiled_sql, distilled_params File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/engine/base.py”, line 1146, in _execute_context context) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/engine/base.py”, line 1341, in _handle_dbapi_exception exc_info File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/util/compat.py”, line 202, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/engine/base.py”, line 1139, in _execute_context context) File “/root/Envs/SIPEvents/lib/python2.7/site-packages/sqlalchemy/engine/default.py”, line 450, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (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. [SQL: u’INSERT INTO events (id, user_openid, title, start_date, end_date, location, user_limit, is_public, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)’] [parameters: (1, ‘oswjmv4X0cCXcfkIwjoDfCkeTVVY’, ‘\xe8\xae\xa8\xe8\xae\xba\xe6\x97\xa5\xe5\x8e\x86\xe7\x9a\x84\xe5\x85\xac\xe4\xbc\x97\xe5\x8f\xb7\xe5\x90\x8d\xe5\xad\x97’, ‘2016-08-23 17:28:48.249504’, ‘2016-08-24 17:28:48.249504’, None, 5, 0, ‘\xe5\xa4\xb4\xe8\x84\x91\xe9\xa3\x8e\xe6\x9a\xb4\xe8\xae\xa8\xe8\xae\xba\xe5\x85\xac\xe4\xbc\x97\xe5\x8f\xb7\xe7\x9a\x84\xe5\x90\x8d\xe5\xad\x97’)] (SIPEvents) ➜ SIPEvents |
搜:
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings
sqlite – sqlalchemy – (ProgrammingError) can interpret 8-bit bytestrings – Stack Overflow
->让写成:
db.Column(db.UnicodeText(64))
-》
connection = sqlite3.connect(…)
connection.text_factory = str
python – Programming error: You must not use 8-bit bytestrings – Stack Overflow
-》db.text_factory = str
(ProgrammingError) can interpret 8-bit bytestrings – Google Groups
-》u’mystring’
sqlalchemy and Unicode strings: errormessage | Coding Forums
->Use UnicodeText instead of Text.
-》自己此处,会遇到,非ascii的字符串
所以需要自己去确保:
在非ascii,此处的中文的部分,需要先去解码为unicode
所以此处Python 2中,去把中文的字符串的前面加上u
eventDict = { ‘id’ : 1, ‘user_openid’ : crifanUserJson[‘openid’], ‘title’ : u”讨论日历的公众号名字”, ‘start_date’ : startDatetime, ‘end_date’ : endDatetime, ‘user_limit’ : 5, ‘is_public’ : False, ‘description’ : u”头脑风暴讨论公众号的名字”, } |
看看效果
然后就可以了
就没了对应的提示了。
[总结]
对于自己的代码中:
如果设置到非ASCII字符串
典型的有:西欧的一些音标,中文字符等等
则
1.要么:
在你的SQLAlchemy的model定义中,用了:
Text或String
description = db.Column(db.Text) title = db.Column(db.String(128)) |
那么就确保,处理的字符串中,已经是unicode了,比如:
‘title’ : u”讨论日历的公众号名字”, ‘description’ : u”头脑风暴讨论公众号的名字”, |
2.要么:
(没去验证,估计是)
在你的SQLAlchemy的model定义中,已经制定了
db.UnicodeText或db.Unicode
description = db.Column(db.UnicodeText) title = db.Column(db.Unicode(128)) |
则:
代码中,可以不是unicode,然后自己会自动转换为unicode?
3.注意:
Column and Data Types — SQLAlchemy 1.1 Documentation
中的String或Text,初始化参数有:
convert_unicode
估计是:
如果设置为了True,则会自动把传入的非unicode字符串,转换为unicode字符串的。
-》暂时不去深究了。
转载请注明:在路上 » [已解决]Flask的SQLAlchemy运行出错:sqlalchemy.exc.ProgrammingError sqlite3.ProgrammingError You must not use 8-bit bytestrings