4

I am trying to use ZODB 3.10.2 on my web server which is running Debian and Python 2.7.1. It seems like every time I try to access the same database from 2 different processes, I get a mysterious exception. I tried accessing a database from an interactive Python session and everything seemed to work fine:

>>> import ZODB
>>> from ZODB.FileStorage import FileStorage
>>> storage = FileStorage("test.db")
>>> 

But then I tried the same series of commands from another session running at the same time and it didn't seem to work:

>>> import ZODB
>>> from ZODB.FileStorage import FileStorage
>>> storage = FileStorage("test.db")
    No handlers could be found for logger "zc.lockfile"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/ZODB3-3.10.2-py2.7-linux-x86_64.egg/ZODB/FileStorage/FileStorage.py", line 125, in __init__
    self._lock_file = LockFile(file_name + '.lock')
  File "/usr/local/lib/python2.7/site-packages/zc.lockfile-1.0.0-py2.7.egg/zc/lockfile/__init__.py", line 76, in __init__
    _lock_file(fp)
  File "/usr/local/lib/python2.7/site-packages/zc.lockfile-1.0.0-py2.7.egg/zc/lockfile/__init__.py", line 59, in _lock_file
    raise LockError("Couldn't lock %r" % file.name)
zc.lockfile.LockError: Couldn't lock 'test.db.lock'
>>>

Why is this happening? What can be done about it?

4

3 回答 3

11

ZODB 不支持多进程访问。这就是您收到锁定错误的原因;ZODB 文件存储已被一个进程锁定,以防止其他进程更改它。

有几种方法可以解决这个问题。最简单的选择是使用ZEO。ZEO 扩展了 ZODB 机制以提供对网络对象的访问,您可以轻松配置 ZODB 以访问 ZEO 服务器而不是本地 FileStorage 文件:

<zodb>
    <zeoclient>
    server localhost:9100
    </zeoclient>
</zodb>

另一种选择是使用RelStorage,它将 ZODB 数据存储在关系数据库中。RelStorage 支持 PostgreSQL、Oracle 和 MySQL 后端。RelStorage 负责处理来自不同 ZODB 客户端的并发访问。这是一个示例配置:

<zodb>
  <relstorage>
    <postgresql>
      # The dsn is optional, as are each of the parameters in the dsn.
      dsn dbname='zodb' user='username' host='localhost' password='pass'
    </postgresql>
  </relstorage>
</zodb>

RelStorage 需要更多的前期设置工作,但在许多情况下可以胜过 ZEO。

于 2011-02-26T18:44:07.410 回答
3

You can not access the same database files from two processes at the same time (which is obvious). That's why you get this error. If you need to perform actions on the same data.fs file from two or more processes: use ZEO.

于 2011-02-26T18:34:50.253 回答
0
## Let the program run once (if it's already running, don't run it again)
## Run the program, open the form
import sys
import zc.lockfile
try:
    lock = zc.lockfile.LockFile('lock', content_template='{pid};{hostname}')
    if __name__ == '__main__':
        mainForm()
except zc.lockfile.LockError:
    sys.exit()

## zc.lockfile thanks
## https://pypi.org/project/zc.lockfile/#detailed-documentation
于 2021-12-18T12:37:33.860 回答