import asyncore asynchat socket from django core management base impor

 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
68
69
70
71
72
73
74
75
76
77
78
import asyncore, asynchat, socket
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from repo.models import Repo
class uchandler(asynchat.async_chat):
def __init__(self, sock):
asynchat.async_chat.__init__(self, sock)
self.ibuffer = []
self.set_terminator('\n')
def _false(self):
self.push('0')
self.close_when_done()
def _true(self):
self.push('1')
self.close_when_done()
def collect_incoming_data(self, data):
'Buffer the data'
self.ibuffer.append(data)
def found_terminator(self):
data = ''.join(self.ibuffer)
self.ibuffer = []
try:
username, repo = data.split(',')
repouser, reponame = repo.split('/')
except ValueError:
return self._false()
self.handle_request(username, repouser, reponame)
def handle_request(self, username, repouser, reponame):
print username, repouser, reponame
try:
repo = Repo.objects.get(user_username=repouser, name=reponame)
user = User.objects.get(username=username)
except (Repo.DoesNotExist, User.DoesNotExist):
print 'wtf'
return self._false()
if repo.check_write(user):
print 'true'
self._true()
else:
print 'false'
self._false()
class ucserver(asyncore.dispatcher):
def __init__(self, address):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(address)
self.address = self.socket.getsockname()
self.listen(5)
def handle_accept(self):
conn, addr = self.accept()
uchandler(sock=conn)
def handle_close(self):
self.close()
class Command(BaseCommand):
help = ('starts a simple server answering if user is allowed to '
'write in repo')
args = ''
def handle(self, *args, **kwargs):
server = ucserver(('localhost', 8888))
print server.address
try:
asyncore.loop(timeout=2)
except KeyboardInterrupt:
print 'Ctrl-C pressed, exiting...'
server.close()