/usr/lib/python2.7/dist-packages/djextdirect/client.py is in python-django-extdirect 0.10-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | # -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; replace-tabs on;
"""
* Copyright (C) 2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
*
* djExtDirect is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
"""
import json
import httplib
from threading import Lock
from urlparse import urljoin, urlparse
def lexjs(javascript):
""" Parse the given javascript and return a dict of variables defined in there. """
ST_NAME, ST_ASSIGN = range(2)
state = ST_NAME
foundvars = {}
buf = ""
name = ""
for char in javascript:
if state == ST_NAME:
if char == ' ':
continue
elif char == '=':
state = ST_ASSIGN
name = buf
buf = ""
elif char == ';':
state = ST_NAME
buf = ""
else:
buf += char
elif state == ST_ASSIGN:
if char == ';':
state = ST_NAME
foundvars[name] = json.loads(buf)
name = ""
buf = ""
else:
buf += char
return foundvars
class RequestError(Exception):
""" Raised if the request returned a status code other than 200. """
pass
class ReturnedError(Exception):
""" Raised if the "type" field in the response is "exception". """
pass
class Client(object):
""" Ext.Direct client side implementation.
This class handles parsing an API specification, building proxy objects from it,
and making calls to the router specified in the API.
Instantiation:
>>> cli = Client( "http://localhost:8000/mumble/api/api.js", "Ext.app.REMOTING_API" )
The apiname parameter defaults to ``Ext.app.REMOTING_API`` and is used to select
the proper API variable from the API source.
The client will then create proxy objects for each action defined in the URL,
which are accessible as properties of the Client instance. Suppose your API defines
the ``Accounts`` and ``Mumble`` actions, then the client will provide those as such:
>>> cli.Accounts
<client.AccountsPrx object at 0x93d9e2c>
>>> cli.Mumble
<client.MumblePrx object at 0x93d9a2c>
These objects provide native Python methods for each method defined in the actions:
>>> cli.Accounts.login
<bound method AccountsPrx.login of <client.AccountsPrx object at 0x93d9e2c>>
So, in order to make a call over Ext.Direct, you would simply call the proxy method:
>>> cli.Accounts.login( "svedrin", "passwort" )
{'success': True}
"""
def __init__( self, apiurl, apiname="Ext.app.REMOTING_API", cookie=None ):
self.apiurl = apiurl
self.apiname = apiname
self.cookie = cookie
purl = urlparse( self.apiurl )
conn = {
"http": httplib.HTTPConnection,
"https": httplib.HTTPSConnection
}[purl.scheme.lower()]( purl.netloc )
conn.putrequest( "GET", purl.path )
conn.endheaders()
resp = conn.getresponse()
foundvars = lexjs( resp.read() )
conn.close()
self.api = foundvars[apiname]
self.routerurl = urljoin( self.apiurl, self.api["url"] )
self._tid = 1
self._tidlock = Lock()
for action in self.api['actions']:
setattr( self, action, self.get_object(action) )
@property
def tid( self ):
""" Thread-safely get a new TID. """
self._tidlock.acquire()
self._tid += 1
newtid = self._tid
self._tidlock.release()
return newtid
def call( self, action, method, *args ):
""" Make a call to Ext.Direct. """
reqtid = self.tid
data=json.dumps({
'tid': reqtid,
'action': action,
'method': method,
'data': args,
'type': 'rpc'
})
purl = urlparse( self.routerurl )
conn = {
"http": httplib.HTTPConnection,
"https": httplib.HTTPSConnection
}[purl.scheme.lower()]( purl.netloc )
conn.putrequest( "POST", purl.path )
conn.putheader( "Content-Type", "application/json" )
conn.putheader( "Content-Length", str(len(data)) )
if self.cookie:
conn.putheader( "Cookie", self.cookie )
conn.endheaders()
conn.send( data )
resp = conn.getresponse()
if resp.status != 200:
raise RequestError( resp.status, resp.reason )
respdata = json.loads( resp.read() )
if respdata['type'] == 'exception':
raise ReturnedError( respdata['message'], respdata['where'] )
if respdata['tid'] != reqtid:
raise RequestError( 'TID mismatch' )
cookie = resp.getheader( "set-cookie" )
if cookie:
self.cookie = cookie.split(';')[0]
conn.close()
return respdata['result']
def get_object( self, action ):
""" Return a proxy object that has methods defined in the API. """
def makemethod( methspec ):
def func( self, *args ):
if len(args) != methspec['len']:
raise TypeError( '%s() takes exactly %d arguments (%d given)' % (
methspec['name'], methspec['len'], len(args)
) )
return self._cli.call( action, methspec['name'], *args )
func.__name__ = methspec['name']
return func
def init( self, cli ):
self._cli = cli
attrs = {
'__init__': init
}
for methspec in self.api['actions'][action]:
attrs[methspec['name']] = makemethod( methspec )
return type( action+"Prx", (object,), attrs )( self )
|