最新消息:20190529 VPS服务器已从腾讯云香港换为Vultr新加坡,主题仍用朋友推荐的大前端D8

【已解决】Flask中SQLAlchemy的pagination传入page为2时出错:LookupError “” is not among the defined enum values

Flask crifan 868浏览 0评论

对于代码:

        # for debug
        taskPagination = None
        if curRole == UserRole.Initiator:
            taskPagination = Task.query.filter_by(initiatorId=userId).paginate(
                page=curPageNum,
                per_page=numPerPage,
                error_out=False)
        elif curRole == UserRole.Errandor:
            taskPagination = Task.query.filter_by(errandorId=userId).paginate(
                page=curPageNum,
                per_page=numPerPage,
                error_out=False)

当传入:

curPageNum=1

numPerPage=10

时,是可以正常执行的

返回的数据也是对的:

{
  "code": 200,
  "data": {
    "curPageNum": 1,
    "hasNext": true,
    "hasPrev": false,
    "numPerPage": 10,
    "tasks": [
      。。。
    ],
    "totalPageNum": 2,
    "totalTaskNum": 16
  },
  "message": "get task/orders ok"
}

总数是16,一共2页,都是正常的。

但是当传入:

curPageNum=2

numPerPage=10

时,竟然出错:

Traceback (most recent call last):
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py", line 884, in handle_one_response
    self.run_application()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/geventwebsocket/handler.py", line 88, in run_application
    return super(WebSocketHandler, self).run_application()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py", line 870, in run_application
    self.result = self.application(self.environ, self.start_response)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sockets.py", line 48, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 268, in error_router
    return self.handle_error(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 268, in error_router
    return self.handle_error(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 477, in wrapper
    resp = resource(*args, **kwargs)
  File "/root/RunningFast/staging/runningfast/resources/Accesstoken.py", line 167, in decorated_function
    return f(*args, **kwargs)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 587, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/root/RunningFast/staging/runningfast/resources/User.py", line 551, in get
    error_out=False)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 476, in paginate
    items = self.limit(per_page).offset((page – 1) * per_page).all()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2643, in all
    return list(self)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 90, in instances
    util.raise_from_cause(err)
  File "/root/Envs/RunningFast/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/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 75, in instances
    rows = [proc(row) for row in fetch]
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 435, in _instance
    loaded_instance, populate_existing, populators)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 496, in _populate_full
    dict_[key] = getter(row)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/sql/sqltypes.py", line 1384, in process
    value = self._object_value_for_elem(value)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/sql/sqltypes.py", line 1304, in _object_value_for_elem
    ‘"%s" is not among the defined enum values’ % elem)
LookupError: "" is not among the defined enum values
{‘GATEWAY_INTERFACE’: ‘CGI/1.1’,
‘HTTP_ACCEPT’: ‘*/*’,
‘HTTP_ACCEPT_ENCODING’: ‘gzip, deflate, sdch’,
‘HTTP_ACCEPT_LANGUAGE’: ‘zh-CN,zh;q=0.8,en;q=0.6’,
‘HTTP_AUTHORIZATION’: ‘z9To19KbL9NvY9qGhy70xp8c1P9Sui8k’,
‘HTTP_CACHE_CONTROL’: ‘no-cache’,
‘HTTP_CONNECTION’: ‘keep-alive’,
‘HTTP_HOST’: ‘115.29.173.126:21085’,
‘HTTP_POSTMAN_TOKEN’: ’29e788fd-bf47-2b7b-ff42-59a278207dda’,
‘HTTP_USER_AGENT’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36’,
‘PATH_INFO’: ‘/runningfast/api/v1.0/users/user-bb22f24e-3c27-4e7b-867a-b855e139b295/tasks’,
‘QUERY_STRING’: ‘curRole=Initiator&curPageNum=2&numPerPage=10’,
‘REMOTE_ADDR’: ‘58.209.164.180’,
‘REMOTE_PORT’: ‘16673’,
‘REQUEST_METHOD’: ‘GET’,
‘SCRIPT_NAME’: ”,
‘SERVER_NAME’: ‘AY140128113754462e2eZ’,
‘SERVER_PORT’: ‘21085’,
‘SERVER_PROTOCOL’: ‘HTTP/1.1’,
‘SERVER_SOFTWARE’: ‘gevent/1.1.2 gunicorn/19.6.0’,
‘werkzeug.request’: <Request ‘http://115.29.173.126:21085/runningfast/api/v1.0/users/user-bb22f24e-3c27-4e7b-867a-b855e139b295/tasks?curRole=Initiator&curPageNum=2&numPerPage=10’ [GET]>,
‘wsgi.errors’: <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f1014bbff50>,
‘wsgi.file_wrapper’: <class ‘gunicorn.http.wsgi.FileWrapper’>,
‘wsgi.input’: <gevent.pywsgi.Input object at 0x7f1011c5e870>,
‘wsgi.multiprocess’: False,
‘wsgi.multithread’: True,
‘wsgi.run_once’: False,
‘wsgi.url_scheme’: ‘http’,
‘wsgi.version’: (1, 0)} failed with LookupError

没有返回对应的第二页的数据

-》

而昨天在测试的时候,还是正常的:

【已解决】Flask-Restful中如何设计分页的API

今天和昨天的区别和改动好像只有:

就是新建了2个task

昨天是14个task

现在是16个

但是为何代码就运行出错了,很诡异。

sqlalchemy LookupError  is not among the defined enum values

zzzeek / sqlalchemy / issues / #3841 – Enum validation causes problems with values not in Enum — Bitbucket

zzzeek / sqlalchemy / issues / #3833 – Enum validation causes problems with column_property — Bitbucket

sqlalchemy.sql.sqltypes — Flask AppBuilder

sqlalchemy/test_types.py at master · zzzeek/sqlalchemy

SQLAlchemy / Mailing Lists

去看了看此处的安装的SQLAlchemy的版本:

(RunningFast) ➜  staging pip list
。。。
enum34 (1.1.6)
Flask (0.11.1)
。。。
Flask-SQLAlchemy (2.1)
。。。
MySQL-python (1.2.5)
。。。
SQLAlchemy (1.1.1)
。。。
Werkzeug (0.11.11)
。。。

再去看看最新的版本是啥:

希望或许可以找到新版本,解决了此bug?

看到了最新的

SQLAlchemy – The Database Toolkit for Python

是:

1.1.3

参考:

[已解决]通过pip升级SQLAlchemy为最新的1.1版本

去升级结果下载不下来。。。

(RunningFast) ➜  staging pip install -U SQLAlchemy
Collecting SQLAlchemy
  Downloading SQLAlchemy-1.1.3.tar.gz (5.1MB)
Exception:
Traceback (most recent call last):
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/commands/install.py", line 310, in run
    wb.build(autobuilding=True)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/wheel.py", line 750, in build
    self.requirement_set.prepare_files(self.finder)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/req/req_set.py", line 370, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/req/req_set.py", line 587, in _prepare_file
    session=self.session, hashes=hashes)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/download.py", line 810, in unpack_url
    hashes=hashes
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/download.py", line 649, in unpack_http_url
    hashes)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/download.py", line 871, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/download.py", line 595, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/utils/hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/download.py", line 563, in written_chunks
    for chunk in chunks:
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/utils/ui.py", line 139, in iter
    for x in it:
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/download.py", line 552, in resp_read
    decode_content=False):
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 353, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 320, in read
    flush_decoder = True
  File "/usr/local/lib/python2.7/contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 242, in _error_catcher
    raise ReadTimeoutError(self._pool, None, ‘Read timed out.’)
ReadTimeoutError: HTTPSConnectionPool(host=’pypi.python.org’, port=443): Read timed out.
You are using pip version 8.1.2, however version 9.0.0 is available.
You should consider upgrading via the ‘pip install –upgrade pip’ command.

【已解决】如何使用pip去本地安装Python的包文件

但是升级到SQLAlchemy到1.1.3之后,错误依旧。

然后去看log的时候,无意间发现:

某一次在传入正常的:

curPageNum=1

curPageNum=10

竟然都出现过异常:

ProgrammingError: (_mysql_exceptions.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-10, 10′ at line 4") [SQL: u’SELECT tasks.id AS tasks_id, tasks.`statusType` AS `tasks_statusType`, tasks.`itemType` AS `tasks_itemType`, tasks.`promotionCode` AS `tasks_promotionCode`, tasks.`hasEnded` AS `tasks_hasEnded`, tasks.`endedTime` AS `tasks_endedTime`, tasks.`createdAt` AS `tasks_createdAt`, tasks.`updatedAt` AS `tasks_updatedAt`, tasks.`initiatorId` AS `tasks_initiatorId`, tasks.`errandorId` AS `tasks_errandorId`, tasks.`cancelByUserType` AS `tasks_cancelByUserType`, tasks.`initiatorTipType` AS `tasks_initiatorTipType`, tasks.`initiatorStartLocationId` AS `tasks_initiatorStartLocationId`, tasks.`initiatorEndLocationId` AS `tasks_initiatorEndLocationId`, tasks.`initiatorDescription` AS `tasks_initiatorDescription`, tasks.`initiatorCancelReasonType` AS `tasks_initiatorCancelReasonType`, tasks.`errandorStartLocationId` AS `tasks_errandorStartLocationId`, tasks.`errandorEndLocationId` AS `tasks_errandorEndLocationId`, tasks.`errandorDescription` AS `tasks_errandorDescription`, tasks.`errandorCancelReasonType` AS `tasks_errandorCancelReasonType`, tasks.`errandorStartTime` AS `tasks_errandorStartTime`, tasks.`errandorRatingType` AS `tasks_errandorRatingType` \nFROM tasks \nWHERE tasks.`initiatorId` = %s \n LIMIT %s, %s’] [parameters: (‘user-bb22f24e-3c27-4e7b-867a-b855e139b295’, -10, 10)]

很明显,内部出错了:

竟然生成的是

-10到10

而不是

1到10

详见:

DEBUG in User [/root/RunningFast/staging/runningfast/resources/User.py:474]:
userId=user-bb22f24e-3c27-4e7b-867a-b855e139b295

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in User [/root/RunningFast/staging/runningfast/resources/User.py:477]:
curRoleStr=Initiator

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in User [/root/RunningFast/staging/runningfast/resources/User.py:479]:
curPageNum=1

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in User [/root/RunningFast/staging/runningfast/resources/User.py:481]:
curPageNum=10

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in User [/root/RunningFast/staging/runningfast/resources/User.py:484]:
curUser=<User:id=user-bb22f24e-3c27-4e7b-867a-b855e139b295,phone=13733331111,email=alalei@qq.com,firstName=u’\u62c9\u857e’,lastName=u’\u963f’,avatarUrl=,facebookUserId=327731344684915,createdAt=2016-10-18 14:29:52,updatedAt=2016-11-07 16:35:28,locationId=location-c71da291-bd83-4292-9f54-e7baa46ac32f,isOnline=True,curRole=UserRole.IdleNoRole,shareCodeCount=1,errandorRating=0.0,errandorIsAuthenticated=True,errandorIsAvailable=True>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in User [/root/RunningFast/staging/runningfast/resources/User.py:492]:
curRole=UserRole.Initiator

<div–<——————————————————————————

Traceback (most recent call last):
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py", line 884, in handle_one_response
    self.run_application()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/geventwebsocket/handler.py", line 88, in run_application
    return super(WebSocketHandler, self).run_application()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py", line 870, in run_application
    self.result = self.application(self.environ, self.start_response)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sockets.py", line 48, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 268, in error_router
    return self.handle_error(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 268, in error_router
    return self.handle_error(e)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 477, in wrapper
    resp = resource(*args, **kwargs)
  File "/root/RunningFast/staging/runningfast/resources/Accesstoken.py", line 167, in decorated_function
    return f(*args, **kwargs)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask/views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py", line 587, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/root/RunningFast/staging/runningfast/resources/User.py", line 540, in get
    taskPagination.prev(error_out=False),
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 342, in prev
    return self.query.paginate(self.page – 1, self.per_page, error_out)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 476, in paginate
    items = self.limit(per_page).offset((page – 1) * per_page).all()
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2643, in all
    return list(self)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2795, in __iter__
    return self._execute_and_instances(context)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2818, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1393, in _handle_dbapi_exception
    exc_info
  File "/root/Envs/RunningFast/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/RunningFast/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 462, in do_execute
    cursor.execute(statement, parameters)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/root/Envs/RunningFast/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
ProgrammingError: (_mysql_exceptions.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-10, 10′ at line 4") [SQL: u’SELECT tasks.id AS tasks_id, tasks.`statusType` AS `tasks_statusType`, tasks.`itemType` AS `tasks_itemType`, tasks.`promotionCode` AS `tasks_promotionCode`, tasks.`hasEnded` AS `tasks_hasEnded`, tasks.`endedTime` AS `tasks_endedTime`, tasks.`createdAt` AS `tasks_createdAt`, tasks.`updatedAt` AS `tasks_updatedAt`, tasks.`initiatorId` AS `tasks_initiatorId`, tasks.`errandorId` AS `tasks_errandorId`, tasks.`cancelByUserType` AS `tasks_cancelByUserType`, tasks.`initiatorTipType` AS `tasks_initiatorTipType`, tasks.`initiatorStartLocationId` AS `tasks_initiatorStartLocationId`, tasks.`initiatorEndLocationId` AS `tasks_initiatorEndLocationId`, tasks.`initiatorDescription` AS `tasks_initiatorDescription`, tasks.`initiatorCancelReasonType` AS `tasks_initiatorCancelReasonType`, tasks.`errandorStartLocationId` AS `tasks_errandorStartLocationId`, tasks.`errandorEndLocationId` AS `tasks_errandorEndLocationId`, tasks.`errandorDescription` AS `tasks_errandorDescription`, tasks.`errandorCancelReasonType` AS `tasks_errandorCancelReasonType`, tasks.`errandorStartTime` AS `tasks_errandorStartTime`, tasks.`errandorRatingType` AS `tasks_errandorRatingType` \nFROM tasks \nWHERE tasks.`initiatorId` = %s \n LIMIT %s, %s’] [parameters: (‘user-bb22f24e-3c27-4e7b-867a-b855e139b295’, -10, 10)]
{‘GATEWAY_INTERFACE’: ‘CGI/1.1’,
‘HTTP_ACCEPT’: ‘*/*’,
‘HTTP_ACCEPT_ENCODING’: ‘gzip, deflate, sdch’,
‘HTTP_ACCEPT_LANGUAGE’: ‘zh-CN,zh;q=0.8,en;q=0.6’,
‘HTTP_AUTHORIZATION’: ‘HmucMnNvaDtTOk21LuvP1FLGBiznisLI’,
‘HTTP_CACHE_CONTROL’: ‘no-cache’,
‘HTTP_CONNECTION’: ‘keep-alive’,
‘HTTP_HOST’: ‘115.29.173.126:21085’,
‘HTTP_POSTMAN_TOKEN’: ‘e0cdf176-230e-7ad2-1eb5-953546a3f539’,
‘HTTP_USER_AGENT’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36’,
‘PATH_INFO’: ‘/runningfast/api/v1.0/users/user-bb22f24e-3c27-4e7b-867a-b855e139b295/tasks’,
‘QUERY_STRING’: ‘curRole=Initiator’,
‘REMOTE_ADDR’: ‘58.209.20.165’,
‘REMOTE_PORT’: ‘10070’,
‘REQUEST_METHOD’: ‘GET’,
‘SCRIPT_NAME’: ”,
‘SERVER_NAME’: ‘AY140128113754462e2eZ’,
‘SERVER_PORT’: ‘21085’,
‘SERVER_PROTOCOL’: ‘HTTP/1.1’,
‘SERVER_SOFTWARE’: ‘gevent/1.1.2 gunicorn/19.6.0’,
‘werkzeug.request’: <Request ‘http://115.29.173.126:21085/runningfast/api/v1.0/users/user-bb22f24e-3c27-4e7b-867a-b855e139b295/tasks?curRole=Initiator’ [GET]>,
‘wsgi.errors’: <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f82b0eb4f50>,
‘wsgi.file_wrapper’: <class ‘gunicorn.http.wsgi.FileWrapper’>,
‘wsgi.input’: <gevent.pywsgi.Input object at 0x7f82b0ecc188>,
‘wsgi.multiprocess’: False,
‘wsgi.multithread’: True,
‘wsgi.run_once’: False,
‘wsgi.url_scheme’: ‘http’,
‘wsgi.version’: (1, 0)} failed with ProgrammingError

看到上述生成的命令是:

[SQL: u’SELECT tasks.id AS tasks_id, tasks.`statusType` AS `tasks_statusType`, tasks.`itemType` AS `tasks_itemType`, tasks.`promotionCode` AS `tasks_promotionCode`, tasks.`hasEnded` AS `tasks_hasEnded`, tasks.`endedTime` AS `tasks_endedTime`, tasks.`createdAt` AS `tasks_createdAt`, tasks.`updatedAt` AS `tasks_updatedAt`, tasks.`initiatorId` AS `tasks_initiatorId`, tasks.`errandorId` AS `tasks_errandorId`, tasks.`cancelByUserType` AS `tasks_cancelByUserType`, tasks.`initiatorTipType` AS `tasks_initiatorTipType`, tasks.`initiatorStartLocationId` AS `tasks_initiatorStartLocationId`, tasks.`initiatorEndLocationId` AS `tasks_initiatorEndLocationId`, tasks.`initiatorDescription` AS `tasks_initiatorDescription`, tasks.`initiatorCancelReasonType` AS `tasks_initiatorCancelReasonType`, tasks.`errandorStartLocationId` AS `tasks_errandorStartLocationId`, tasks.`errandorEndLocationId` AS `tasks_errandorEndLocationId`, tasks.`errandorDescription` AS `tasks_errandorDescription`, tasks.`errandorCancelReasonType` AS `tasks_errandorCancelReasonType`, tasks.`errandorStartTime` AS `tasks_errandorStartTime`, tasks.`errandorRatingType` AS `tasks_errandorRatingType` \nFROM tasks \nWHERE tasks.`initiatorId` = %s \n LIMIT %s, %s’

估计是:

Task.query.filter_by(initiatorId=userId)

中的

filter_by

导致的?

去换成:

filter(Task.initiatorId==userId)

或许就可以了?

突然注意到:

或许是因为:

initiatorCancelReasonType

也去做了判断,要有值才可以。

但是此处的,某个新增加的task的initiatorCancelReasonType为空:

从而导致了此处代码的内部执行时出错?

找不到“”==空字符串==对应的initiatorCancelReasonType的值

所对应的enum枚举类型

-》所以此处,感觉是:

要么是

尝试换成

filter(Task.initiatorId==userId)

或许就只检查Task的initiatorId,而不去检查其他字段(包括initiatorCancelReasonType)了。

或许是:

把这个initiatorCancelReasonType为空的task删除掉,估计就可以了?

先去试试上面那种办法:

            #taskPagination = Task.query.filter_by(initiatorId=userId).paginate(
            taskPagination = Task.query.filter(Task.initiatorId==userId).paginate(

看看结果如何。

以及对应生成的query是啥

结果错误依旧。也就看不到后续的log中的query是啥了。

再去试试第二个:

删除对应的出错的,initiatorCancelReasonType为空的那个task

然后再去运行代码看看

果然就可以了,返回正常的结果:

{
  "code": 200,
  "data": {
    "curPageNum": 2,
    "hasNext": false,
    "hasPrev": true,
    "numPerPage": 10,
    "tasks": [……….
    ],
    "totalPageNum": 2,
    "totalTaskNum": 15
  },
  "message": "get task/orders ok"
}

然后再去看看log中query是啥:

代码:

      gLog.debug("type(taskPagination)=%s"
                   ",taskPagination=%s"
                   ",has_next=%s"
                   ",has_prev=%s"
                   # ",items=%s"
                   # ",next()=%s"
                   # ",next_num=%s"
                   ",page=%s"
                   ",pages=%s"
                   ",per_page=%s"
                   # ",prev_num=%s"
                   ",query=%s"
                   ",total=%s",
                   type(taskPagination),
                   taskPagination,
                   taskPagination.has_next,
                   taskPagination.has_prev,
                   # taskPagination.items,
                   # taskPagination.next(error_out=False),
                   # taskPagination.next_num,
                   taskPagination.page,
                   taskPagination.pages,
                   taskPagination.per_page,
                   # taskPagination.prev_num,
                   taskPagination.query,
                   taskPagination.total
                   )

对应的log是:

type(taskPagination)=<class ‘flask_sqlalchemy.Pagination’>,taskPagination=<flask_sqlalchemy.Pagination object at 0x7f26540efcd0>,has_next=False,has_prev=True,page=2,pages=2,per_page=10,query=SELECT tasks.id AS tasks_id, tasks.`statusType` AS `tasks_statusType`, tasks.`itemType` AS `tasks_itemType`, tasks.`promotionCode` AS `tasks_promotionCode`, tasks.`hasEnded` AS `tasks_hasEnded`, tasks.`endedTime` AS `tasks_endedTime`, tasks.`createdAt` AS `tasks_createdAt`, tasks.`updatedAt` AS `tasks_updatedAt`, tasks.`initiatorId` AS `tasks_initiatorId`, tasks.`errandorId` AS `tasks_errandorId`, tasks.`cancelByUserType` AS `tasks_cancelByUserType`, tasks.`initiatorTipType` AS `tasks_initiatorTipType`, tasks.`initiatorStartLocationId` AS `tasks_initiatorStartLocationId`, tasks.`initiatorEndLocationId` AS `tasks_initiatorEndLocationId`, tasks.`initiatorDescription` AS `tasks_initiatorDescription`, tasks.`initiatorCancelReasonType` AS `tasks_initiatorCancelReasonType`, tasks.`errandorStartLocationId` AS `tasks_errandorStartLocationId`, tasks.`errandorEndLocationId` AS `tasks_errandorEndLocationId`, tasks.`errandorDescription` AS `tasks_errandorDescription`, tasks.`errandorCancelReasonType` AS `tasks_errandorCancelReasonType`, tasks.`errandorStartTime` AS `tasks_errandorStartTime`, tasks.`errandorRatingType` AS `tasks_errandorRatingType`
FROM tasks
WHERE tasks.`initiatorId` = %s,total=15

把其中的SQL语句格式化看看:

SELECT tasks.id
AS tasks_id, tasks.`statusType`
AS `tasks_statusType`, tasks.`itemType`
AS `tasks_itemType`, tasks.`promotionCode`
AS `tasks_promotionCode`, tasks.`hasEnded`
AS `tasks_hasEnded`, tasks.`endedTime`
AS `tasks_endedTime`, tasks.`createdAt`
AS `tasks_createdAt`, tasks.`updatedAt`
AS `tasks_updatedAt`, tasks.`initiatorId`
AS `tasks_initiatorId`, tasks.`errandorId`
AS `tasks_errandorId`, tasks.`cancelByUserType`
AS `tasks_cancelByUserType`, tasks.`initiatorTipType`
AS `tasks_initiatorTipType`, tasks.`initiatorStartLocationId`
AS `tasks_initiatorStartLocationId`, tasks.`initiatorEndLocationId`
AS `tasks_initiatorEndLocationId`, tasks.`initiatorDescription`
AS `tasks_initiatorDescription`, tasks.`initiatorCancelReasonType`
AS `tasks_initiatorCancelReasonType`, tasks.`errandorStartLocationId`
AS `tasks_errandorStartLocationId`, tasks.`errandorEndLocationId`
AS `tasks_errandorEndLocationId`, tasks.`errandorDescription`
AS `tasks_errandorDescription`, tasks.`errandorCancelReasonType`
AS `tasks_errandorCancelReasonType`, tasks.`errandorStartTime`
AS `tasks_errandorStartTime`, tasks.`errandorRatingType`
AS `tasks_errandorRatingType`
FROM tasks
WHERE tasks.`initiatorId` = %s,total=15

-》

看来:

filter和filter_by一样

-》内部还是会生成对象的每个字段的检索的

【总结】

此处,使用SQLAlchemy中的pagination:

            taskPagination = Task.query.filter_by(initiatorId=userId).paginate(
                page=curPageNum,
                per_page=numPerPage,
                error_out=False)

在page为2时出错:

LookupError "" is not among the defined enum values

的原因是:

此处的Task中,page为2时,会去访问到一个,特殊的Task,initiatorCancelReasonType字段为空字符串

而initiatorCancelReasonType的类型本身是枚举:

class InitiatorCancelTaskReasonType(enum.Enum):

所以,在调用filter_by(后来证实,filter也会生成类似于的query查询语句,把对象每个的字段都去查询的)时,无法把空字符串””转换为对应的initiatorCancelReasonType,从而报错。

解决办法是:

把异常的Task删除掉。

另外:

对于之后正常运行的代码所产生的Task,initiatorCancelReasonType默认值是有值,不会为空字符串的。所以以后也不会出现类似问题的。

转载请注明:在路上 » 【已解决】Flask中SQLAlchemy的pagination传入page为2时出错:LookupError “” is not among the defined enum values

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
68 queries in 0.092 seconds, using 18.95MB memory