首页 > 解决方案 > asyncpg 异常 DataError 查询参数的输入无效

问题描述

我的模型

    boundary_table = Table(
        'boundary',
        metadata,
...
        Column('geom', Geometry(geometry_type='GEOMETRY'), nullable=False)
    )

我的观点

    class DetailBoundaryView(handlers_base.BaseView):
        URL_PATH = r'/boundary/{boundary_id:\d+}'
    
        @property
        def boundary_id(self):
            return int(self.request.match_info.get('boundary_id'))
    
        @staticmethod
        async def get_boundary_by_id(conn, boundary_id):
            query = select([
                 ...
                db_schema.boundary_table.columns.geom.ST_Transform(4326).ST_AsGeoJSON(),
            ]).select_from(
                db_schema.boundary_table
            ).where(
                db_schema.boundary_table.columns.id == boundary_id,
            )
            return await conn.fetchrow(query)
    
        @docs(tags=['boundary'],
              summary='Get boundary.')
        @response_schema(api_schema.BoundaryResponseSchema(), code=HTTPStatus.OK.value)
        async def get(self):
            data = await self.get_boundary_by_id(self.pg, self.boundary_id)
            if data is None:
                raise HTTPNotFound()
            return Response(body={'data': data}, status=HTTPStatus.OK)

当被问及我得到错误

    Traceback (most recent call last):
      File "asyncpg/protocol/prepared_stmt.pyx", line 146, in asyncpg.protocol.protocol.PreparedStatementState._encode_bind_msg
      File "asyncpg/protocol/codecs/base.pyx", line 192, in asyncpg.protocol.protocol.Codec.encode
      File "asyncpg/protocol/codecs/base.pyx", line 103, in asyncpg.protocol.protocol.Codec.encode_scalar
      File "asyncpg/pgproto/./codecs/text.pyx", line 29, in asyncpg.pgproto.pgproto.text_encode
      File "asyncpg/pgproto/./codecs/text.pyx", line 12, in asyncpg.pgproto.pgproto.as_pg_string_and_size
    TypeError: expected str, got int
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
         ...
        resp = await method()
      File "/Users/folt/Documents/Work/geodb/server/api/handlers/boundary.py", line 103, in get
        data = await self.get_boundary_by_id(self.pg, self.boundary_id)
      File "/Users/folt/Documents/Work/geodb/server/api/handlers/boundary.py", line 97, in get_boundary_by_id
        return await conn.fetchrow(query)
       ...
      File "asyncpg/protocol/protocol.pyx", line 178, in bind_execute
      File "asyncpg/protocol/prepared_stmt.pyx", line 160, in asyncpg.protocol.protocol.PreparedStatementState._encode_bind_msg
    asyncpg.exceptions.DataError: invalid input for query argument $1: 4326 (expected str, got int)

我想使用 sqlalchemy 编写查询。但是,我在使用 Geometry 字段时遇到了问题。我尝试使用模块重复此func查询sqlalchemy。即使有了它,我也会收到此错误。

标签: pythonsqlsqlalchemyasyncpggeoalchemy2

解决方案


推荐阅读