-
Notifications
You must be signed in to change notification settings - Fork 261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
asyncio tasks share the same mysql connection? #93
Comments
I make a workaround for this problem。I can reset _connect_context to avoid tasks inhrefit ContextVar from the point they were created at, and don't need to change my old code. import asyncio
import databases
from sqlalchemy import insert, select, update, Column, Integer, SmallInteger
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Database(databases.Database):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.token = None
def connection(self):
if self._global_connection is not None:
return self._global_connection
try:
return self._connection_context.get()
except LookupError:
connection = Connection(self._backend)
self.token = self._connection_context.set(connection)
return connection
def reset(self):
if self.token:
self._connection_context.reset(self.token)
database = Database("mysql://root:[email protected]:3306/demo?min_size=1&max_size=20")
class Task(Base):
__tablename__ = 'task'
id = Column(Integer, primary_key=True)
status = Column(SmallInteger, index=True, nullable=False)
async def add_tasks(num):
tasks = []
for i in range(num):
tasks.append({
'status': 0
})
await database.execute_many(insert(Task), values=tasks)
async def task_worker(task):
print("get task: %s" % task[0])
await database.execute(update(Task, Task.id == task[0]).values(status=1))
print("task: %s finished" % task[0])
async def process_tasks():
tasks = await database.fetch_all(select([Task], Task.status == 0))
print("get %s tasks" % len(tasks))
database.reset()
await asyncio.gather(*[task_worker(x) for x in tasks])
async def main():
await database.connect()
try:
await add_tasks(10)
await process_tasks()
finally:
await database.disconnect()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main()) |
Yup, duplicate of #81. |
Merged
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
windows10 64 python3.6.6
databases 0.2.2
aiomysql 0.0.20
exception
maybe related to #81
The text was updated successfully, but these errors were encountered: