sr (owner)

Fork Of

Revisions

gist: 117724 Download_button fork
public
Description:
http://simonwillison.net/2009/May/25/uuid/
Public Clone URL: git://gist.github.com/117724.git
Embed All Files: show embed
uuid.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import socket
 
 
def sockrecv(sock):
    d = ''
    while not d or d[-1] != '\n':
        d += sock.recv(8192)
    return d
 
 
class UUID(object):
    def __init__(self):
        self.sock = socket.socket()
        self.sock.connect(('127.0.0.1', 8007))
        self.sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
 
    def uuid(self):
        self.sock.sendall('gee\n')
        uuid = sockrecv(self.sock).strip()
        return uuid
 
    def close(self):
        self.sock.sendall('quit\n')
        self.sock.close()
 
 
uuid = UUID()
 
if __name__ == '__main__':
    while True:
        print uuid.uuid()
uuidd.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from __future__ import with_statement
import fcntl
import sys
import os
import socket
import asyncore
 
STEP = 10000
 
if not os.path.exists('uuid.txt'):
    with open('uuid.txt', 'wb+') as f:
        f.write('0')
 
def uuids():
    while True:
        with open('uuid.txt', 'rb+') as uuid_file:
            fcntl.lockf(uuid_file.fileno(), fcntl.LOCK_EX)
            min = int(uuid_file.read() or 0)
            max = min + STEP
            uuid_file.seek(0)
            uuid_file.write(str(max))
            uuid_file.flush()
            fcntl.lockf(uuid_file.fileno(), fcntl.LOCK_UN)
        for uuid in xrange(min, max):
            yield str(uuid)
uuids = uuids()
 
 
class UUIDConnection(asyncore.dispatcher):
    def __init__(self, sock):
        self.data = None
        asyncore.dispatcher.__init__(self, sock)
 
    def writable(self):
        return bool(self.data)
    
    def handle_write(self):
        self.send(self.data + "\n")
        self.data = None
 
    def handle_read(self):
        line = self.recv(1024)
        line = line.strip()
 
        if line == 'gee':
            self.data = uuids.next()
        elif line == 'quit':
            self.close()
        else:
            self.data = "ERROR"
 
 
class UUIDServer(asyncore.dispatcher):
    def __init__(self, port=8007):
        asyncore.dispatcher.__init__(self)
        self.port = port
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(("", port))
        self.listen(1)
 
    def handle_accept(self):
        channel, addr = self.accept()
        UUIDConnection(channel)
 
if __name__ == '__main__':
    server = UUIDServer()
    asyncore.loop()