added python files

This commit is contained in:
Tony Tam 2012-08-24 19:39:34 -07:00
parent af41b43c56
commit 384a549807
17 changed files with 1383 additions and 0 deletions

6
bin/python-petstore.sh Executable file
View File

@ -0,0 +1,6 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export CLASSPATH="$DIR/../target/lib/*:$DIR/../target/*"
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
scala $WORDNIK_OPTS $JAVA_CONFIG_OPTIONS -cp $CLASSPATH "$@" PythonPetstoreCodegen http://petstore.swagger.wordnik.com/api/resources.json special-key

View File

@ -0,0 +1,216 @@
#!/usr/bin/env python
"""
WordAPI.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
from models import *
class PetApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def getPetById(self, petId, **kwargs):
"""Find pet by ID
Args:
petId, str: ID of pet that needs to be fetched (required)
Returns: Pet
"""
allParams = ['petId']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method getPetById" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet.{format}/{petId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('petId' in params):
resourcePath = resourcePath.replace('{' + 'petId' + '}',
self.apiClient.toPathValue(params['petId']))
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'Pet')
return responseObject
def addPet(self, body, **kwargs):
"""Add a new pet to the store
Args:
body, Pet: Pet object that needs to be added to the store (required)
Returns:
"""
allParams = ['body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method addPet" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet.{format}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def updatePet(self, body, **kwargs):
"""Update an existing pet
Args:
body, Pet: Pet object that needs to be updated in the store (required)
Returns:
"""
allParams = ['body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method updatePet" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet.{format}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'PUT'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def findPetsByStatus(self, status, **kwargs):
"""Finds Pets by status
Args:
status, str: Status values that need to be considered for filter (required)
Returns: list[Pet]
"""
allParams = ['status']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method findPetsByStatus" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet.{format}/findByStatus'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('status' in params):
queryParams['status'] = self.apiClient.toPathValue(params['status'])
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'list[Pet]')
return responseObject
def findPetsByTags(self, tags, **kwargs):
"""Finds Pets by tags
Args:
tags, str: Tags to filter by (required)
Returns: list[Pet]
"""
allParams = ['tags']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method findPetsByTags" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet.{format}/findByTags'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('tags' in params):
queryParams['tags'] = self.apiClient.toPathValue(params['tags'])
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'list[Pet]')
return responseObject

View File

@ -0,0 +1,141 @@
#!/usr/bin/env python
"""
WordAPI.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
from models import *
class StoreApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def getOrderById(self, orderId, **kwargs):
"""Find purchase order by ID
Args:
orderId, str: ID of pet that needs to be fetched (required)
Returns: Order
"""
allParams = ['orderId']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method getOrderById" % key)
params[key] = val
del params['kwargs']
resourcePath = '/store.{format}/order/{orderId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('orderId' in params):
resourcePath = resourcePath.replace('{' + 'orderId' + '}',
self.apiClient.toPathValue(params['orderId']))
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'Order')
return responseObject
def deleteOrder(self, orderId, **kwargs):
"""Delete purchase order by ID
Args:
orderId, str: ID of the order that needs to be deleted (required)
Returns:
"""
allParams = ['orderId']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method deleteOrder" % key)
params[key] = val
del params['kwargs']
resourcePath = '/store.{format}/order/{orderId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'DELETE'
queryParams = {}
headerParams = {}
if ('orderId' in params):
resourcePath = resourcePath.replace('{' + 'orderId' + '}',
self.apiClient.toPathValue(params['orderId']))
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def placeOrder(self, body, **kwargs):
"""Place an order for a pet
Args:
body, Order: order placed for purchasing the pet (required)
Returns:
"""
allParams = ['body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method placeOrder" % key)
params[key] = val
del params['kwargs']
resourcePath = '/store.{format}/order'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)

View File

@ -0,0 +1,314 @@
#!/usr/bin/env python
"""
WordAPI.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
from models import *
class UserApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def createUsersWithArrayInput(self, body, **kwargs):
"""Creates list of users with given input array
Args:
body, list[User]: List of user object (required)
Returns:
"""
allParams = ['body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithArrayInput" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/createWithArray'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def createUser(self, body, **kwargs):
"""Create user
Args:
body, User: Created user object (required)
Returns:
"""
allParams = ['body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method createUser" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def createUsersWithListInput(self, body, **kwargs):
"""Creates list of users with given list input
Args:
body, List[User]: List of user object (required)
Returns:
"""
allParams = ['body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithListInput" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/createWithList'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def updateUser(self, username, body, **kwargs):
"""Updated user
Args:
username, str: name that need to be deleted (required)
body, User: Updated user object (required)
Returns:
"""
allParams = ['username', 'body']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method updateUser" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/{username}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'PUT'
queryParams = {}
headerParams = {}
if ('username' in params):
resourcePath = resourcePath.replace('{' + 'username' + '}',
self.apiClient.toPathValue(params['username']))
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def deleteUser(self, username, **kwargs):
"""Delete user
Args:
username, str: The name that needs to be deleted (required)
Returns:
"""
allParams = ['username']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method deleteUser" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/{username}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'DELETE'
queryParams = {}
headerParams = {}
if ('username' in params):
resourcePath = resourcePath.replace('{' + 'username' + '}',
self.apiClient.toPathValue(params['username']))
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
def getUserByName(self, username, **kwargs):
"""Get user by user name
Args:
username, str: The name that needs to be fetched. Use user1 for testing. (required)
Returns: User
"""
allParams = ['username']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method getUserByName" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/{username}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('username' in params):
resourcePath = resourcePath.replace('{' + 'username' + '}',
self.apiClient.toPathValue(params['username']))
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'User')
return responseObject
def loginUser(self, username, password, **kwargs):
"""Logs user into the system
Args:
username, str: The user name for login (required)
password, str: The password for login in clear text (required)
Returns: str
"""
allParams = ['username', 'password']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method loginUser" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/login'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
if ('username' in params):
queryParams['username'] = self.apiClient.toPathValue(params['username'])
if ('password' in params):
queryParams['password'] = self.apiClient.toPathValue(params['password'])
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'str')
return responseObject
def logoutUser(self, **kwargs):
"""Logs out current logged in user session
Args:
Returns:
"""
allParams = []
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method logoutUser" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user.{format}/logout'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)

View File

@ -0,0 +1,10 @@
#!/usr/bin/env python
"""Add all of the modules in the current directory to __all__"""
import os
__all__ = []
for module in os.listdir(os.path.dirname(__file__)):
if module != '__init__.py' and module[-3:] == '.py':
__all__.append(module[:-3])

View File

@ -0,0 +1,32 @@
#!/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 Category:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'long',
'name': 'str'
}
self.id = None # long
self.name = None # str

View File

@ -0,0 +1,39 @@
#!/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 Order:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'long',
'petId': 'long',
'status': 'str',
'quantity': 'int',
'shipDate': 'str'
}
self.id = None # long
self.petId = None # long
#Order Status
self.status = None # str
self.quantity = None # int
self.shipDate = None # str

View File

@ -0,0 +1,41 @@
#!/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 Pet:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'long',
'tags': 'list[Tag]',
'category': 'Category',
'status': 'str',
'name': 'str',
'photoUrls': 'list[str]'
}
self.id = None # long
self.tags = None # list[Tag]
self.category = None # Category
#pet status in the store
self.status = None # str
self.name = None # str
self.photoUrls = None # list[str]

View File

@ -0,0 +1,32 @@
#!/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 Tag:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'long',
'name': 'str'
}
self.id = None # long
self.name = None # str

View File

@ -0,0 +1,45 @@
#!/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 User:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'long',
'lastName': 'str',
'username': 'str',
'phone': 'str',
'email': 'str',
'userStatus': 'int',
'firstName': 'str',
'password': 'str'
}
self.id = None # long
self.lastName = None # str
self.username = None # str
self.phone = None # str
self.email = None # str
#User Status
self.userStatus = None # int
self.firstName = None # str
self.password = None # str

View File

@ -0,0 +1,10 @@
#!/usr/bin/env python
"""Add all of the modules in the current directory to __all__"""
import os
__all__ = []
for module in os.listdir(os.path.dirname(__file__)):
if module != '__init__.py' and module[-3:] == '.py':
__all__.append(module[:-3])

View File

@ -0,0 +1,169 @@
#!/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
from models import *
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
self.cookie = None
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['api_key'] = self.apiKey
if self.cookie:
headers['Cookie'] = self.cookie
data = None
# What can safely be JSON serialized?
safeToDump = [str, int, float, bool]
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)
if method in ['POST', 'PUT', 'DELETE']:
data = postData
if data:
headers['Content-type'] = 'application/json'
if type(postData) == list:
# Could be a list of objects
if type(postData[0]) in safeToDump:
data = json.dumps(postData)
else:
data = json.dumps([datum.__dict__ for datum in postData])
elif type(postData) not in safeToDump:
data = json.dumps(postData.__dict__)
else:
raise Exception('Method ' + method + ' is not recognized.')
request = MethodRequest(method=method, url=url, headers=headers, data=data)
# Make the request
response = urllib2.urlopen(request)
if 'Set-Cookie' in response.headers:
self.cookie = response.headers['Set-Cookie']
string = response.read()
try:
data = json.loads(string)
except ValueError: # PUT requests don't return anything
data = None
return data
def toPathValue(self, obj):
"""Serialize a list to a CSV string, if necessary.
Args:
obj -- data object to be serialized
Returns:
string -- json serialization of object
"""
if type(obj) == list:
return ','.join(obj)
else:
return 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.
# print obj, objClass
if type(objClass) == str:
if 'list[' in objClass:
match = re.match('list\[(.*)\]', objClass)
subClass = match.group(1)
return [self.deserialize(subObj, subClass) for subObj in obj]
# print objClass + ' is str'
if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str']):
objClass = eval(objClass)
else: # not a native type, must be model class
objClass = eval(objClass + '.' + objClass)
if objClass in [str, int, long, float, bool]:
return objClass(obj)
instance = objClass()
for attr, attrType in instance.swaggerTypes.iteritems():
# print 'attr:', attr, 'obj:', obj
if attr in obj:
value = obj[attr]
if attrType in ['str', 'int', 'long', '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
class MethodRequest(urllib2.Request):
def __init__(self, *args, **kwargs):
"""Construct a MethodRequest. Usage is the same as for
`urllib2.Request` except it also takes an optional `method`
keyword argument. If supplied, `method` will be used instead of
the default."""
if 'method' in kwargs:
self.method = kwargs.pop('method')
return urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return getattr(self, 'method', urllib2.Request.get_method(self))

View File

@ -0,0 +1,9 @@
#!/usr/bin/env python
"""Add all of the modules in the current directory to __all__"""
import os
__all__ = []
for module in os.listdir(os.path.dirname(__file__)):
if module != '__init__.py' and module[-3:] == '.py':
__all__.append(module[:-3])

View File

@ -0,0 +1,95 @@
#!/usr/bin/env python
"""
WordAPI.py
Copyright 2012 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
from models import *
{{#operations}}
class {{classname}}(object):
def __init__(self, apiClient):
self.apiClient = apiClient
{{newline}}
{{#operation}}
def {{nickname}}(self, {{#requiredParams}}{{paramName}}{{#defaultValue}} = None{{/defaultValue}}, {{/requiredParams}}**kwargs):
"""{{summary}}
Args:
{{#allParams}}
{{paramName}}, {{dataType}}: {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}}
{{newline}}
{{/allParams}}
{{newline}}
Returns: {{returnType}}
"""
allParams = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}]
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key)
params[key] = val
del params['kwargs']
resourcePath = '{{path}}'
resourcePath = resourcePath.replace('{format}', 'json')
method = '{{httpMethod}}'
queryParams = {}
headerParams = {}
{{#queryParams}}
if ('{{paramName}}' in params):
queryParams['{{paramName}}'] = self.apiClient.toPathValue(params['{{paramName}}'])
{{/queryParams}}
{{#headerParams}}
if ('{{paramName}}' in params):
headerParams['{{paramName}}'] = params['{{paramName}}']
{{/headerParams}}
{{#pathParams}}
if ('{{paramName}}' in params):
resourcePath = resourcePath.replace('{' + '{{baseName}}' + '}',
self.apiClient.toPathValue(params['{{paramName}}']))
{{/pathParams}}
postData = (params['body'] if 'body' in params else None)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams)
{{#returnType}}
if not response:
return None
responseObject = self.apiClient.deserialize(response, '{{returnType}}')
return responseObject
{{/returnType}}
{{newline}}
{{newline}}
{{/operation}}
{{newline}}
{{/operations}}
{{newline}}

View File

@ -0,0 +1,40 @@
#!/usr/bin/env python
"""
Copyright 2012 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.
"""
{{#models}}
{{#model}}
class {{classname}}:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
{{#vars}}
'{{name}}': '{{{datatype}}}'{{#hasMore}},
{{/hasMore}}
{{/vars}}{{newline}}
}
{{#vars}}
{{#description}}#{{description}}
{{/description}}
self.{{name}} = None # {{{datatype}}}
{{/vars}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,168 @@
#!/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
from models import *
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
self.cookie = None
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['api_key'] = self.apiKey
if self.cookie:
headers['Cookie'] = self.cookie
data = None
# What can safely be JSON serialized?
safeToDump = [str, int, float, bool]
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)
if method in ['POST', 'PUT', 'DELETE']:
data = postData
if data:
headers['Content-type'] = 'application/json'
if type(postData) == list:
# Could be a list of objects
if type(postData[0]) in safeToDump:
data = json.dumps(postData)
else:
data = json.dumps([datum.__dict__ for datum in postData])
elif type(postData) not in safeToDump:
data = json.dumps(postData.__dict__)
else:
raise Exception('Method ' + method + ' is not recognized.')
request = MethodRequest(method=method, url=url, headers=headers, data=data)
# Make the request
response = urllib2.urlopen(request)
if 'Set-Cookie' in response.headers:
self.cookie = response.headers['Set-Cookie']
string = response.read()
try:
data = json.loads(string)
except ValueError: # PUT requests don't return anything
data = None
return data
def toPathValue(self, obj):
"""Serialize a list to a CSV string, if necessary.
Args:
obj -- data object to be serialized
Returns:
string -- json serialization of object
"""
if type(obj) == list:
return ','.join(obj)
else:
return 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.
# print obj, objClass
if type(objClass) == str:
if 'list[' in objClass:
match = re.match('list\[(.*)\]', objClass)
subClass = match.group(1)
return [self.deserialize(subObj, subClass) for subObj in obj]
# print objClass + ' is str'
if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str']):
objClass = eval(objClass)
else: # not a native type, must be model class
objClass = eval(objClass + '.' + objClass)
if objClass in [str, int, long, float, bool]:
return objClass(obj)
instance = objClass()
for attr, attrType in instance.swaggerTypes.iteritems():
# print 'attr:', attr, 'obj:', obj
if attr in obj:
value = obj[attr]
if attrType in ['str', 'int', 'long', '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
class MethodRequest(urllib2.Request):
def __init__(self, *args, **kwargs):
"""Construct a MethodRequest. Usage is the same as for
`urllib2.Request` except it also takes an optional `method`
keyword argument. If supplied, `method` will be used instead of
the default."""
if 'method' in kwargs:
self.method = kwargs.pop('method')
return urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return getattr(self, 'method', urllib2.Request.get_method(self))

View File

@ -0,0 +1,16 @@
import com.wordnik.swagger.codegen.BasicPythonGenerator
import com.wordnik.swagger.core._
import java.io.File
object PythonPetstoreCodegen extends BasicPythonGenerator {
def main(args: Array[String]) = generateClient(args)
override def destinationDir = "samples/petstore/python"
override def supportingFiles = List(
("__init__.mustache", destinationDir, "__init__.py"),
("swagger.mustache", destinationDir + File.separator + apiPackage.get, "swagger.py"),
("__init__.mustache", destinationDir + File.separator + modelPackage.get, "__init__.py"))
}