Snippet List
Look here: https://bitbucket.org/depaolim/optlock
The snippet of Marco De Paoli is much better than this one! :-)
=========================================================
If two users save same record, the second one will overwrite first one.
Use this snippet to achieve an optimistic locking, so the second user will get an exception.
Save the snippet in optlock.py and put it anywhere in your pythonpath.
**Do not put _version_opt_lock in readonly_fields** or the snippet will fail! (if you need to hide it, use jquery).
The snippet need in request.POST the original value of _version_opt_lock and if you make it a readonly field Django doesn't POST its value. When this [bug](https://code.djangoproject.com/ticket/11277) will be fixed it should be possible to use a hiddeninput widget.
models.py example:
...
import optlock
...
class YourModel(optlock.Model):
...
admin.py example:
...
import optlock
...
class YourModelAdmin(optlock.ModelAdmin):
...
That's it :-)
- admin
- locking
- optimistic locking
This code provides a mixin and decorator which, when used together, can provide advisory locking on model methods. It provides locking by using MySQL's advisory lock system. See the example at the bottom of the code.
This is a convenient and easy way to guarantee your model methods have exclusive access to a model instance.
The LockableObjects class requires a MySQL backend, but it could be modified to use other back-end locking systems.
The lock name generation in `LockableObject.get_lock_name()` could be altered to create much more complex locking schemes. Locking per-object, per-method for example..
Lock attempts have a timeout value of 45 seconds by default. If a timeout occurs, EnvironmentError is raised.
**See the bottom of the script for an example**
> **Instructions:**
* **1:** Place the code in locking.py somewhere in your path
* **2:** In your models.py (or any script with an object you want to lock):
`from locking import LockableObject, require_object_lock`
* **3:** In the model you want locking for, add the `LockableObject` mixin
* **4:** Decorate the method you want to be exclusively locked with `@require_object_lock`
- model
- mysql
- decorator
- mixin
- locking
*WARNING* This is *extremely* slow.
This snippet allows you to easily prevent *most* race conditions (if used properly).
Feel free to extend on top of this as you like, I'd appreciate any comments to [email protected]
- django
- mysql
- database
- table
- lock
- condition
- race
- locking
- unlock
- atomic
- operation
- operations
4 snippets posted so far.