Initializer getting called twice

27 kali dilihat
Langsung ke pesan pertama yang belum dibaca

Roy Smith

belum dibaca,
17 Jun 2011, 07.36.4917/06/11
kepadaMongoKit
I'm running mongokit 0.6, pymongo 1.11, python 2.6.5, mongo 1.6.6-pre

It looks like if you define default_values, the initializers get
called twice. If the initializer is non-idempotent, that's a
problem! We use incrementing integers for object ids, and I want to
use initializers to create them. When I do so (see code below), the
initializer gets called twice, causing the id counter to get
incremented twice.

The code below produces:

./init2.py
about to create Test() object
get_next_id() ==> 1377751
get_next_id() ==> 1377752
got Test() object, id=1377752


---------------------------------------------------------------------
import pymongo
from mongokit import *

def get_next_id():
db = pymongo.Connection()['stations']
result = db.meta.find_and_modify({'data': 'max_station_id'},
{'$inc': {'max_id': 1}})
id = result['max_id']
print "get_next_id() ==> %d" % id
return id

class Test(Document):
structure = {'id': int}
default_values = {'id': get_next_id}

print "about to create Test() object"
t = Test()
print "got Test() object, id=%d" % t['id']
---------------------------------------------------------------------

Nicolas Clairon

belum dibaca,
17 Jun 2011, 10.57.0717/06/11
kepadamong...@googlegroups.com
Yep, you're right, the __init__ is called twice in order to be
attached to a the connection.

By the way, I don't think it is a good idea to instanciate a
connection in `get_next_id` because you may expect some issue in
production (if you must pass some arguments to the connection
constructor).
You should put this function into the __init__ and call `self.db`
instead to use the current connection configuration.

I'll see what I can do with the double-called __init__ :
https://github.com/namlook/mongokit/issues/56

N.

Roy Smith

belum dibaca,
17 Jun 2011, 11.04.2817/06/11
kepadamong...@googlegroups.com

On Jun 17, 2011, at 10:57 AM, Nicolas Clairon wrote:

> By the way, I don't think it is a good idea to instanciate a
> connection in `get_next_id` because you may expect some issue in
> production (if you must pass some arguments to the connection
> constructor).

Certainly, in a production environment, we cache the connections. This was just a small bit of code to demonstrate the problem. Thanks for opening the ticket.

---
Roy Smith
r...@panix.com

Balas ke semua
Balas ke penulis
Teruskan
0 pesan baru