Added templates and config for Python client generation.

This commit is contained in:
Russell Horton
2011-11-11 01:06:12 -08:00
parent 9b1d1a9dad
commit 087b22bcf3
9 changed files with 702 additions and 0 deletions

View File

@@ -0,0 +1,128 @@
#!/usr/bin/env python
"""Wordnik.com's Swagger generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the Swagger
templates."""
import sys
import os
import re
import urllib
import urllib2
import httplib
import json
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')
import model
class APIClient:
"""Generic API client for Swagger client library builds"""
def __init__(self, apiKey=None, apiServer=None):
if apiKey == None:
raise Exception('You must pass an apiKey when instantiating the '
'APIClient')
self.apiKey = apiKey
self.apiServer = apiServer
def callAPI(self, resourcePath, method, queryParams, postData,
headerParams=None):
url = self.apiServer + resourcePath
headers = {}
if headerParams:
for param, value in headerParams.iteritems():
headers[param] = value
headers['Content-type'] = 'application/json'
headers['api_key'] = self.apiKey
data = None
if method == 'GET':
if queryParams:
# Need to remove None values, these should not be sent
sentQueryParams = {}
for param, value in queryParams.iteritems():
if value != None:
sentQueryParams[param] = value
url = url + '?' + urllib.urlencode(sentQueryParams)
request = urllib2.Request(url=url, headers=headers)
elif method in ['POST', 'PUT', 'DELETE']:
data = postData
if data:
if type(postData) not in [str, int, float, bool]:
data = json.dumps(postData.__dict__)
request = urllib2.Request(url=url, headers=headers, data=data)
if method in ['PUT', 'DELETE']:
# Monkey patch alert! Urllib2 doesn't really do PUT / DELETE
request.get_method = lambda: method
else:
raise Exception('Method ' + method + ' is not recognized.')
# Make the request
response = urllib2.urlopen(request).read()
try:
data = json.loads(response)
except ValueError: # PUT requests don't return anything
data = None
return data
def serialize(self, obj):
"""
Args:
obj -- data object to be serialized
Returns:
string -- json serialization of object
"""
return json.dumps(obj)
def deserialize(self, obj, objClass):
"""Derialize a JSON string into an object.
Args:
obj -- string or object to be deserialized
objClass -- class literal for deserialzied object, or string
of class name
Returns:
object -- deserialized object"""
# Have to accept objClass as string or actual type. Type could be a
# native Python type, or one of the model classes.
if type(objClass) == str:
try:
objClass = eval(objClass)
except NameError: # not a native type, must be model class
objClass = eval('model.' + objClass + '.' + objClass)
if objClass in [str, int, float, bool]:
return objClass(obj)
instance = objClass()
for attr, attrType in instance.swaggerTypes.iteritems():
if attr in obj:
value = obj[attr]
if attrType in ['str', 'int', 'float', 'bool']:
attrType = eval(attrType)
try:
value = attrType(value)
except UnicodeEncodeError:
value = unicode(value)
setattr(instance, attr, value)
elif 'list<' in attrType:
match = re.match('list<(.*)>', attrType)
subClass = match.group(1)
subValues = []
for subValue in value:
subValues.append(self.deserialize(subValue, subClass))
setattr(instance, attr, subValues)
else:
setattr(instance, attr, self.deserialize(value,
objClass))
return instance

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env python
"""Load all of the modules in the models directory."""
import os
for module in os.listdir(os.path.dirname(__file__)):
if module != '__init__.py' and module[-3:] == '.py':
__import__(module[:-3], locals(), globals())

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env python
"""
Copyright 2011 Wordnik, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class $className$:
"""
$enum.description$
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__():
$values: { value | self.$value.name$ = $value.value$};separator=";\n"$

View File

@@ -0,0 +1,37 @@
#!/usr/bin/env python
"""
Copyright 2011 Wordnik, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class $className$:
"""
$model.description$
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
self.swaggerTypes = {
$fields: { field |'$field.fieldDefinition.name$': '$field.fieldDefinition.returnType$'};separator=",\n"$
}
$fields:{ field |
# $field.description$
self.$field.fieldDefinition.name$ = None # $field.fieldDefinition.returnType$
}$

View File

@@ -0,0 +1,115 @@
#!/usr/bin/env python
"""
$resource$.py
Copyright 2011 Wordnik, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')
import model
class $resource$(object):
def __init__(self, apiClient):
self.apiClient = apiClient
$methods:{ method |
def $method.name$(self, $method.arguments: { argument | $if(argument.required)$$argument.name$, $endif$}$$method.arguments: { argument | $if(! argument.required)$$argument.name$=None, $endif$}$):
"""$method.title$
$if(method.description)$
$method.description$
$endif$
Args:
$method.arguments:{ argument |$argument.name$ -- $argument.description$
$if(argument.allowedValues)$
Allowed values are - $argument.allowedValues$
$endif$}$
$if(!method.responseVoid)$
Return:
$method.returnValue$ -- an instance of $method.returnClassName$
$endif$"""
# Parse inputs
resourcePath = '$method.resourcePath$'
resourcePath = resourcePath.replace('{format}', 'json')
method = '$method.methodType$'
queryParams = {}
headerParams = {}
$if(method.authToken)$
if not authToken:
raise Exception('missing authToken')
headerParams['auth_token'] = authToken
$endif$
$if(!method.inputModel)$
$method.queryParameters:{ argument |
queryParams['$argument.name$'] = $argument.name$
}$
$method.pathParameters:{ argument |
if $argument.name$ != None:
resourcePath = resourcePath.replace('{$argument.name$}', $argument.name$)
}$
$endif$
$if(method.inputModel)$
$method.queryParameters:{ argument |
if $argument.inputModelClassArgument$ != None and $argument.inputModelClassArgument$.$argument.name$ != None:
queryParams['$argument.name$'] = $argument.inputModelClassArgument$.$argument.name$
}$
$method.pathParameters:{ argument |
if $argument.inputModelClassArgument$ != None and $argument.inputModelClassArgument$.$argument.name$ != None:
resourcePath = resourcePath.replace('{$argument.name$}', $argument.inputModelClassArgument$.$argument.name$)
}$
$endif$
# Make the API Call
$if(method.postObject)$
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
$endif$
$if(!method.postObject)$
response = self.apiClient.callAPI(resourcePath, method, queryParams,
None, headerParams)
$endif$
$if(!method.responseVoid)$
if not response:
return None
$if(!method.returnValueList)$
# Create output objects if the response has more than one object
responseObject = self.apiClient.deserialize(response,
model.$method.returnClassName$.$method.returnClassName$)
return responseObject
$endif$
$if(method.returnValueList)$
responseObjects = []
for responseObject in response:
responseObjects.append(self.apiClient.deserialize(responseObject,
model.$method.returnClassName$.$method.returnClassName$))
return responseObjects
$endif$
$endif$
}$

View File

@@ -0,0 +1,36 @@
<?php
/**
* Copyright 2011 Wordnik, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* Maintains the compatible server version against which the drive is written
* NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
*/
class VersionChecker {
public static compatibleVersion = "$apiVersion$";
/**
* Gets the version against which the library code was written
*/
public function getCompatibleVersion() {
return self::\$compatibleVersion;
}
}
?>