21 | | def get_new_session_key(self): |
22 | | "Returns session key that isn't being used." |
23 | | # The random module is seeded when this Apache child is created. |
24 | | # Use SECRET_KEY as added salt. |
25 | | try: |
26 | | pid = os.getpid() |
27 | | except AttributeError: |
28 | | # No getpid() in Jython, for example |
29 | | pid = 1 |
30 | | while 1: |
31 | | session_key = md5.new("%s%s%s%s" % (random.randint(0, sys.maxint - 1), pid, time.time(), settings.SECRET_KEY)).hexdigest() |
32 | | try: |
33 | | self.get(session_key=session_key) |
34 | | except self.model.DoesNotExist: |
35 | | break |
36 | | return session_key |
37 | | |
38 | | def get_new_session_object(self): |
39 | | """ |
40 | | Returns a new session object. |
41 | | """ |
42 | | # FIXME: There is a *small* chance of collision here, meaning we will |
43 | | # return an existing object. That can be fixed when we add a way to |
44 | | # validate (and guarantee) that non-auto primary keys are unique. For |
45 | | # now, we save immediately in order to reduce the "window of |
46 | | # misfortune" as much as possible. |
47 | | created = False |
48 | | while not created: |
49 | | obj, created = self.get_or_create(session_key=self.get_new_session_key(), |
50 | | expire_date = datetime.datetime.now()) |
51 | | # Collision in key generation, so re-seed the generator |
52 | | random.seed() |
53 | | return obj |
54 | | |