package python sdk using setuptools

This commit is contained in:
geekerzp
2015-04-09 17:56:49 +08:00
parent 70c14092f9
commit e6bf58a707
17 changed files with 154 additions and 56 deletions

View File

@@ -0,0 +1,15 @@
## Requirements.
Python 2.7 and later.
## Setuptools
You can install the bindings via [Setuptools](http://pypi.python.org/pypi/setuptools).
```sh
python setup.py install
```
Or you can install from Github via pip:
```sh
```

View File

@@ -0,0 +1,34 @@
#!/usr/bin/env python
"""Add all of the modules in the current directory to __all__"""
import os
# import models into package
from .models.user import User
from .models.category import Category
from .models.pet import Pet
from .models.tag import Tag
from .models.order import Order
# import apis into package
from .user_api import UserApi
from .pet_api import PetApi
from .store_api import StoreApi
# import ApiClient
from .swagger import ApiClient
__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,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,54 @@
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 Reverb Technologies, 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(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'id': 'long',
'name': 'str'
}
self.attributeMap = {
'id': 'id',
'name': 'name'
}
self.id = None # long
self.name = None # str

View File

@@ -0,0 +1,87 @@
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 Reverb Technologies, 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(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'id': 'long',
'pet_id': 'long',
'quantity': 'int',
'ship_date': 'DateTime',
'status': 'str',
'complete': 'bool'
}
self.attributeMap = {
'id': 'id',
'pet_id': 'petId',
'quantity': 'quantity',
'ship_date': 'shipDate',
'status': 'status',
'complete': 'complete'
}
self.id = None # long
self.pet_id = None # long
self.quantity = None # int
self.ship_date = None # DateTime
#Order Status
self.status = None # str
self.complete = None # bool

View File

@@ -0,0 +1,87 @@
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 Reverb Technologies, 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(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'id': 'long',
'category': 'Category',
'name': 'str',
'photo_urls': 'list[str]',
'tags': 'list[Tag]',
'status': 'str'
}
self.attributeMap = {
'id': 'id',
'category': 'category',
'name': 'name',
'photo_urls': 'photoUrls',
'tags': 'tags',
'status': 'status'
}
self.id = None # long
self.category = None # Category
self.name = None # str
self.photo_urls = None # list[str]
self.tags = None # list[Tag]
#pet status in the store
self.status = None # str

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 Reverb Technologies, 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(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'id': 'long',
'name': 'str'
}
self.attributeMap = {
'id': 'id',
'name': 'name'
}
self.id = None # long
self.name = None # str

View File

@@ -0,0 +1,103 @@
#!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 Reverb Technologies, 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(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'id': 'long',
'username': 'str',
'first_name': 'str',
'last_name': 'str',
'email': 'str',
'password': 'str',
'phone': 'str',
'user_status': 'int'
}
self.attributeMap = {
'id': 'id',
'username': 'username',
'first_name': 'firstName',
'last_name': 'lastName',
'email': 'email',
'password': 'password',
'phone': 'phone',
'user_status': 'userStatus'
}
self.id = None # long
self.username = None # str
self.first_name = None # str
self.last_name = None # str
self.email = None # str
self.password = None # str
self.phone = None # str
#User Status
self.user_status = None # int

View File

@@ -0,0 +1,545 @@
#!/usr/bin/env python
# coding: utf-8
"""
PetApi.py
Copyright 2015 Reverb Technologies, 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
import urllib
from models import *
class PetApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def updatePet(self, **kwargs):
"""Update an existing pet
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 updatePet" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'PUT'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = 'application/json,application/xml,'
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def addPet(self, **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'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = 'application/json,application/xml,'
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def findPetsByStatus(self, **kwargs):
"""Finds Pets by status
Args:
status, list[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/findByStatus'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('status' in params):
queryParams['status'] = self.apiClient.toPathValue(params['status'])
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'list[Pet]')
return responseObject
def findPetsByTags(self, **kwargs):
"""Finds Pets by tags
Args:
tags, list[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/findByTags'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('tags' in params):
queryParams['tags'] = self.apiClient.toPathValue(params['tags'])
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'list[Pet]')
return responseObject
def getPetById(self, **kwargs):
"""Find pet by ID
Args:
pet_id, long: ID of pet that needs to be fetched (required)
Returns: Pet
"""
allParams = ['pet_id']
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/{petId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('pet_id' in params):
replacement = str(self.apiClient.toPathValue(params['pet_id']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'petId' + '}',
replacement)
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'Pet')
return responseObject
def updatePetWithForm(self, **kwargs):
"""Updates a pet in the store with form data
Args:
pet_id, str: ID of pet that needs to be updated (required)
name, str: Updated name of the pet (required)
status, str: Updated status of the pet (required)
Returns:
"""
allParams = ['pet_id', 'name', '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 updatePetWithForm" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet/{petId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = 'application/x-www-form-urlencoded,'
if ('pet_id' in params):
replacement = str(self.apiClient.toPathValue(params['pet_id']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'petId' + '}',
replacement)
if ('name' in params):
formParams['name'] = params['name']
if ('status' in params):
formParams['status'] = params['status']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def deletePet(self, **kwargs):
"""Deletes a pet
Args:
api_key, str: (required)
pet_id, long: Pet id to delete (required)
Returns:
"""
allParams = ['api_key', 'pet_id']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method deletePet" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet/{petId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'DELETE'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('api_key' in params):
headerParams['api_key'] = params['api_key']
if ('pet_id' in params):
replacement = str(self.apiClient.toPathValue(params['pet_id']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'petId' + '}',
replacement)
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def uploadFile(self, **kwargs):
"""uploads an image
Args:
pet_id, long: ID of pet to update (required)
additional_metadata, str: Additional data to pass to server (required)
file, file: file to upload (required)
Returns:
"""
allParams = ['pet_id', 'additional_metadata', 'file']
params = locals()
for (key, val) in params['kwargs'].iteritems():
if key not in allParams:
raise TypeError("Got an unexpected keyword argument '%s' to method uploadFile" % key)
params[key] = val
del params['kwargs']
resourcePath = '/pet/{petId}/uploadImage'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = 'multipart/form-data,'
if ('pet_id' in params):
replacement = str(self.apiClient.toPathValue(params['pet_id']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'petId' + '}',
replacement)
if ('additional_metadata' in params):
formParams['additionalMetadata'] = params['additional_metadata']
if ('file' in params):
files['file'] = params['file']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)

View File

@@ -0,0 +1,279 @@
#!/usr/bin/env python
# coding: utf-8
"""
StoreApi.py
Copyright 2015 Reverb Technologies, 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
import urllib
from models import *
class StoreApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def getInventory(self, **kwargs):
"""Returns pet inventories by status
Args:
Returns: map(String, int)
"""
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 getInventory" % key)
params[key] = val
del params['kwargs']
resourcePath = '/store/inventory'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'map(String, int)')
return responseObject
def placeOrder(self, **kwargs):
"""Place an order for a pet
Args:
body, Order: order placed for purchasing the pet (required)
Returns: Order
"""
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/order'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'Order')
return responseObject
def getOrderById(self, **kwargs):
"""Find purchase order by ID
Args:
order_id, str: ID of pet that needs to be fetched (required)
Returns: Order
"""
allParams = ['order_id']
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/order/{orderId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('order_id' in params):
replacement = str(self.apiClient.toPathValue(params['order_id']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'orderId' + '}',
replacement)
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'Order')
return responseObject
def deleteOrder(self, **kwargs):
"""Delete purchase order by ID
Args:
order_id, str: ID of the order that needs to be deleted (required)
Returns:
"""
allParams = ['order_id']
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/order/{orderId}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'DELETE'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('order_id' in params):
replacement = str(self.apiClient.toPathValue(params['order_id']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'orderId' + '}',
replacement)
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)

View File

@@ -0,0 +1,274 @@
#!/usr/bin/env python
# coding: utf-8
"""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
import datetime
import mimetypes
import random
import string
from models import *
class ApiClient(object):
"""Generic API client for Swagger client library builds
Attributes:
host: The base path for the server to call
headerName: a header to pass when making calls to the API
headerValue: a header value to pass when making calls to the API
"""
def __init__(self, host=None, headerName=None, headerValue=None):
self.defaultHeaders = {}
if (headerName is not None):
self.defaultHeaders[headerName] = headerValue
self.host = host
self.cookie = None
self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30))
# Set default User-Agent.
self.user_agent = 'Python-Swagger'
@property
def user_agent(self):
return self.defaultHeaders['User-Agent']
@user_agent.setter
def user_agent(self, value):
self.defaultHeaders['User-Agent'] = value
def setDefaultHeader(self, headerName, headerValue):
self.defaultHeaders[headerName] = headerValue
def callAPI(self, resourcePath, method, queryParams, postData,
headerParams=None, files=None):
url = self.host + resourcePath
mergedHeaderParams = self.defaultHeaders.copy()
mergedHeaderParams.update(headerParams)
headers = {}
if mergedHeaderParams:
for param, value in mergedHeaderParams.iteritems():
headers[param] = ApiClient.sanitizeForSerialization(value)
if self.cookie:
headers['Cookie'] = ApiClient.sanitizeForSerialization(self.cookie)
data = None
if queryParams:
# Need to remove None values, these should not be sent
sentQueryParams = {}
for param, value in queryParams.items():
if value is not None:
sentQueryParams[param] = ApiClient.sanitizeForSerialization(value)
url = url + '?' + urllib.urlencode(sentQueryParams)
if method in ['GET']:
#Options to add statements later on and for compatibility
pass
elif method in ['POST', 'PUT', 'DELETE']:
if postData:
postData = ApiClient.sanitizeForSerialization(postData)
if 'Content-type' not in headers:
headers['Content-type'] = 'application/json'
data = json.dumps(postData)
elif headers['Content-type'] == 'multipart/form-data':
data = self.buildMultipartFormData(postData, files)
headers['Content-type'] = 'multipart/form-data; boundary={0}'.format(self.boundary)
headers['Content-length'] = str(len(data))
else:
data = urllib.urlencode(postData)
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):
"""Convert a string or object to a path-friendly value
Args:
obj -- object or string value
Returns:
string -- quoted value
"""
if type(obj) == list:
return ','.join(obj)
else:
return str(obj)
@staticmethod
def sanitizeForSerialization(obj):
"""
Sanitize an object for Request.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date convert to string in iso8601 format.
If obj is list, santize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
"""
if isinstance(obj, type(None)):
return None
elif isinstance(obj, (str, int, long, float, bool, file)):
return obj
elif isinstance(obj, list):
return [ApiClient.sanitizeForSerialization(subObj) for subObj in obj]
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
else:
if isinstance(obj, dict):
objDict = obj
else:
# Convert model obj to dict except attributes `swaggerTypes`, `attributeMap`
# and attributes which value is not None.
# Convert attribute name to json key in model definition for request.
objDict = {obj.attributeMap[key]: val
for key, val in obj.__dict__.iteritems()
if key != 'swaggerTypes' and key != 'attributeMap' and val is not None}
return {key: ApiClient.sanitizeForSerialization(val)
for (key, val) in objDict.iteritems()}
def buildMultipartFormData(self, postData, files):
def escape_quotes(s):
return s.replace('"', '\\"')
lines = []
for name, value in postData.items():
lines.extend((
'--{0}'.format(self.boundary),
'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)),
'',
str(value),
))
for name, filepath in files.items():
f = open(filepath, 'r')
filename = filepath.split('/')[-1]
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
lines.extend((
'--{0}'.format(self.boundary),
'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)),
'Content-Type: {0}'.format(mimetype),
'',
f.read()
))
lines.extend((
'--{0}--'.format(self.boundary),
''
))
return '\r\n'.join(lines)
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:
if 'list[' in objClass:
match = re.match('list\[(.*)\]', objClass)
subClass = match.group(1)
return [self.deserialize(subObj, subClass) for subObj in obj]
if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']):
objClass = eval(objClass)
else: # not a native type, must be model class
objClass = eval(objClass + '.' + objClass)
if objClass in [int, long, float, dict, list, str, bool]:
return objClass(obj)
elif objClass == datetime:
return self.__parse_string_to_datetime(obj)
instance = objClass()
for attr, attrType in instance.swaggerTypes.iteritems():
if obj is not None and instance.attributeMap[attr] in obj and type(obj) in [list, dict]:
value = obj[instance.attributeMap[attr]]
if attrType in ['str', 'int', 'long', 'float', 'bool']:
attrType = eval(attrType)
try:
value = attrType(value)
except UnicodeEncodeError:
value = unicode(value)
except TypeError:
value = value
setattr(instance, attr, value)
elif (attrType == 'datetime'):
setattr(instance, attr, self.__parse_string_to_datetime(value))
elif 'list[' in attrType:
match = re.match('list\[(.*)\]', attrType)
subClass = match.group(1)
subValues = []
if not value:
setattr(instance, attr, None)
else:
for subValue in value:
subValues.append(self.deserialize(subValue, subClass))
setattr(instance, attr, subValues)
else:
setattr(instance, attr, self.deserialize(value, attrType))
return instance
def __parse_string_to_datetime(self, string):
"""
Parse datetime in string to datetime.
The string should be in iso8601 datetime format.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
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,512 @@
#!/usr/bin/env python
# coding: utf-8
"""
UserApi.py
Copyright 2015 Reverb Technologies, 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
import urllib
from models import *
class UserApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def createUser(self, **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'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def createUsersWithArrayInput(self, **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/createWithArray'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def createUsersWithListInput(self, **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 createUsersWithListInput" % key)
params[key] = val
del params['kwargs']
resourcePath = '/user/createWithList'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def loginUser(self, **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/login'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('username' in params):
queryParams['username'] = self.apiClient.toPathValue(params['username'])
if ('password' in params):
queryParams['password'] = self.apiClient.toPathValue(params['password'])
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
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/logout'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def getUserByName(self, **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/{username}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('username' in params):
replacement = str(self.apiClient.toPathValue(params['username']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'username' + '}',
replacement)
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
if not response:
return None
responseObject = self.apiClient.deserialize(response, 'User')
return responseObject
def updateUser(self, **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/{username}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'PUT'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('username' in params):
replacement = str(self.apiClient.toPathValue(params['username']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'username' + '}',
replacement)
if ('body' in params):
bodyParam = params['body']
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)
def deleteUser(self, **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/{username}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'DELETE'
queryParams = {}
headerParams = {}
formParams = {}
files = {}
bodyParam = None
headerParams['Accept'] = 'application/json,application/xml'
headerParams['Content-Type'] = ''
if ('username' in params):
replacement = str(self.apiClient.toPathValue(params['username']))
replacement = urllib.quote(replacement)
resourcePath = resourcePath.replace('{' + 'username' + '}',
replacement)
postData = (formParams if formParams else bodyParam)
response = self.apiClient.callAPI(resourcePath, method, queryParams,
postData, headerParams, files=files)

View File

@@ -0,0 +1,32 @@
import sys
from setuptools import setup, find_packages
# To install the library, open a Terminal shell, then run this
# file by typing:
#
# python setup.py install
#
# You need to have the setuptools module installed.
# Try reading the setuptools documentation:
# http://pypi.python.org/pypi/setuptools
REQUIRES = []
setup(
name="SwaggerPetstore",
version="1.0.0",
description="Swagger Petstore",
author_email="apiteam@wordnik.com",
url="",
keywords=["Swagger", "Swagger Petstore"],
install_requires=REQUIRES,
packages=find_packages(),
include_package_data=True,
long_description="""\
This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters
"""
)