下記内容でエラーが発生しています。解決方法教えて頂けると助かります。

このエラーは数時間APIアクセスを行わなかった場合に、再度アクセスを行おうとすると発生します。  
FastAPIアプリを再起動すると復旧します。

**Error**

```

    Traceback (most recent call last):
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
        result = await app(self.scope, self.receive, self.send)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
        return await self.app(scope, receive, send)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/fastapi/applications.py", line 261, in __call__
        await super().__call__(scope, receive, send)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
        raise exc
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
        await self.app(scope, receive, _send)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
        raise exc
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
        await self.app(scope, receive, sender)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
        raise e
      File "/usr/lib/python3.8/contextlib.py", line 679, in __aexit__
        raise exc_details[1]
      File "/usr/lib/python3.8/contextlib.py", line 662, in __aexit__
        cb_suppress = await cb(*exc_details)
      File "/usr/lib/python3.8/contextlib.py", line 189, in __aexit__
        await self.gen.athrow(typ, value, traceback)
      File "/home/ubuntu/app/backend/db.py", line 41, in get_db
        yield session
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/ext/asyncio/session.py", line 626, in __aexit__
        await self.close()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/ext/asyncio/session.py", line 608, in close
        return await greenlet_spawn(self.sync_session.close)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 134, in greenlet_spawn
        result = context.throw(*sys.exc_info())
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 1789, in close
        self._close_impl(invalidate=False)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 1831, in _close_impl
        transaction.close(invalidate)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 923, in close
        transaction.close()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2324, in close
        self._do_close()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2547, in _do_close
        self._close_impl()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2533, in _close_impl
        self._connection_rollback_impl()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2525, in _connection_rollback_impl
        self.connection._rollback_impl()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 974, in _rollback_impl
        self._handle_dbapi_exception(e, None, None, None, None)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2032, in _handle_dbapi_exception
        util.raise_(
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
        raise exception
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 972, in _rollback_impl
        self.engine.dialect.do_rollback(self.connection)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 682, in do_rollback
        dbapi_connection.rollback()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/dialects/mysql/aiomysql.py", line 205, in rollback
        self.await_(self._connection.rollback())
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 76, in await_only
        return current.driver.switch(awaitable)
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 129, in greenlet_spawn
        value = await result
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/aiomysql/connection.py", line 358, in rollback
        await self._read_ok_packet()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/aiomysql/connection.py", line 331, in _read_ok_packet
        pkt = await self._read_packet()
      File "/home/ubuntu/app/backend/venv/lib/python3.8/site-packages/aiomysql/connection.py", line 572, in _read_packet
        raise InternalError(
    sqlalchemy.exc.InternalError: (pymysql.err.InternalError) Packet sequence number wrong - got 35 expected 1
    (Background on this error at: https://sqlalche.me/e/14/2j85)
    
```

**Development Environment**

```

    Python 3.8.10
    mysql  Ver 8.0.31-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))
    
    Package             Version    
    ------------------- -----------
    aiomysql            0.0.22     
    anyio               3.5.0      
    asgiref             3.5.0      
    autopep8            1.7.0      
    bcrypt              4.0.0      
    beautifulsoup4      4.11.1     
    certifi             2021.10.8  
    cffi                1.15.0     
    charset-normalizer  2.0.12     
    click               8.0.4      
    contourpy           1.0.5      
    cryptography        36.0.2     
    cycler              0.11.0     
    dnspython           2.2.1      
    ecdsa               0.18.0     
    email-validator     1.1.3      
    et-xmlfile          1.1.0      
    fastapi             0.75.0     
    fonttools           4.38.0     
    greenlet            1.1.2      
    gunicorn            20.1.0     
    h11                 0.13.0     
    htmldocx            0.0.6      
    httptools           0.2.0      
    idna                3.3        
    itsdangerous        2.1.2      
    japanize-matplotlib 1.1.3      
    Jinja2              3.1.1      
    kiwisolver          1.4.4      
    lxml                4.9.1      
    MarkupSafe          2.1.1      
    matplotlib          3.6.1      
    numpy               1.23.4     
    openpyxl            3.0.10     
    orjson              3.6.7      
    packaging           21.3       
    passlib             1.7.4      
    Pillow              9.2.0      
    pip                 20.0.2     
    pkg-resources       0.0.0      
    pyasn1              0.4.8      
    pycodestyle         2.9.1      
    pycparser           2.21       
    pydantic            1.9.0      
    PyMySQL             0.9.3      
    pyparsing           3.0.9      
    python-dateutil     2.8.2      
    python-docx         0.8.11     
    python-dotenv       0.20.0     
    python-jose         3.3.0      
    python-multipart    0.0.5      
    PyYAML              5.4.1      
    requests            2.27.1     
    rsa                 4.9        
    setuptools          44.0.0     
    six                 1.16.0     
    sniffio             1.2.0      
    soupsieve           2.3.2.post1
    SQLAlchemy          1.4.32     
    starlette           0.17.1     
    toml                0.10.2     
    typing-extensions   4.1.1      
    ujson               4.3.0      
    urllib3             1.26.9     
    uvicorn             0.15.0     
    uvloop              0.16.0     
    watchgod            0.8.1      
    websockets          10.2       
    wheel               0.37.1     
    
```

**Source Code**

app.py

```

    from fastapi        import FastAPI
    from routers.v1     import XXXXXXX, XXXXXXX
    from core.handlers  import api_exception_handler, system_exception_handler
    from exceptions     import ApiException
    
    app = FastAPI()
    
    app.add_exception_handler(ApiException, api_exception_handler)
    app.add_exception_handler(Exception,    system_exception_handler)
    
    prefix="/api/v1"
    app.include_router(XXXX.router,     prefix=prefix, tags=['XXXX'])
    app.include_router(XXXX.router,     prefix=prefix, tags=['XXXX'])
    
```

db.py

```

    from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
    from sqlalchemy.orm         import sessionmaker, declarative_base
    import core.config          as config
    
    
    DB_USER     = config.get_env().db_user
    DB_PASSWORD = config.get_env().db_password
    DB_HOST     = config.get_env().db_host
    DB_NAME     = config.get_env().db_name
    
    DB_CONNETION_STRING = 'mysql+aiomysql://%s:%s@%s/%s?charset=utf8mb4' % (
        DB_USER,
        DB_PASSWORD,
        DB_HOST,
        DB_NAME,
    )
    
    async_engine = create_async_engine(
        DB_CONNETION_STRING, 
        echo=True
    )
    
    async_session = sessionmaker(
        autocommit=False, 
        autoflush=False, 
        bind=async_engine, 
        class_=AsyncSession
    )
    
    
    Base = declarative_base()
    
    
    async def get_db():
        async with async_session() as session:
            yield session
    
```
CC BY-SA 4.0
2022-11-08T01:11:21.300
92073
2022-11-08T03:25:45.037
2022-11-08T03:25:44.620
3060
55266
question
python mysql sqlalchemy pymysql fastapi
エラー (pymysql.err.InternalError) Packet sequence number wrong