标签云

微信群

扫码加入我们

WeChat QR Code

Django has a decorator function called @transaction.commit_manually. I am attempting to pass a parameter to this decorator, (using=db). db varies depending on which database is being used, based on business rules.What is the best way to pass the current database to this decorator?I tried to use an inner function, thus:def func(db):stuff = _business logic_@transaction.commit_manually(using=db)def do_transaction(stuff):try:stuff.save(using=db)except:transaction.rollback()else:transaction.commit()do_transaction()However, this fails. The error I discovered with pdb is that the inner block is "Not under transaction management."How do I overcome this problem?Traceback from pdb:-> success = transactional_registration()/usr/local/lib/python2.7/dist-packages/django/db/transaction.py(338)_commit_manually()-> return func(*args, **kw)> /home/syrion/dev/registration.py(59)transactional_registration()-> transaction.rollback()/usr/local/lib/python2.7/dist-packages/django/db/transaction.py(210)rollback()-> set_clean(using=using)/usr/local/lib/python2.7/dist-packages/django/db/transaction.py(125)set_clean()-> raise TransactionManagementError("This code isn't under transaction management"Edit: I fixed my own problem. The internal function solution works correctly, but I needed to be calling rollback() and commit() with a using parameter, i.e. transaction.commit(using=db), as well. I find that unintuitive, but...


can you add a raise after transaction.rollback() and post the stacktrace + full error ?

2019年04月22日28分41秒

Why are you making this so complex?Why isn't func a callable object?

2019年04月22日28分41秒

func is a callable method on an object.If I decorate func itself, the database is out of scope.

2019年04月22日28分41秒

You don't need a decorator at all if you use a simple callable object.Why aren't you creating a simple callable and avoiding the confusing decorator entirely?

2019年04月22日28分41秒

Note that you can now use context managers with Django transaction decorators; that might allow you to dump the inner function.

2019年04月22日28分41秒