make it so
This commit is contained in:
71
api_builder.py
Normal file
71
api_builder.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import re
|
||||
import sys
|
||||
|
||||
import inflection
|
||||
import requests
|
||||
|
||||
|
||||
with open('prelude.py') as f:
|
||||
prelude = f.read()
|
||||
|
||||
|
||||
|
||||
reserved = dir(__builtins__)
|
||||
|
||||
|
||||
def download(url):
|
||||
return requests.get(url).json()
|
||||
|
||||
|
||||
def mkname(method, name, params):
|
||||
singular = inflection.singularize(name)
|
||||
if method == 'get' and 'id_' not in params:
|
||||
return 'list_{}'.format(name)
|
||||
elif method == 'get':
|
||||
return singular
|
||||
elif method == 'post':
|
||||
return 'create_{}'.format(singular)
|
||||
elif method == 'put' or method == 'PATCH':
|
||||
return 'update_{}'.format(singular)
|
||||
elif method == 'delete':
|
||||
return 'delete_{}'.format(singular)
|
||||
return name
|
||||
|
||||
|
||||
def mkparam(param):
|
||||
param = inflection.underscore(param)
|
||||
if param in reserved:
|
||||
return "{}_".format(param)
|
||||
return param
|
||||
|
||||
|
||||
def pretty_print(name, data):
|
||||
info = data['info']
|
||||
r = re.compile('\\/\\{([^\\}]*)\\}')
|
||||
r2 = re.compile('\\{([^\\}]*)\\}')
|
||||
print(prelude)
|
||||
print('class {}(Client):'.format(name))
|
||||
print(' """{}\n\n {}"""'.format(info['title'], info['description']))
|
||||
for path, fns in data['paths'].items():
|
||||
for method, body in fns.items():
|
||||
method = method.lower()
|
||||
fmt = r2.sub('{}', path)
|
||||
params = [mkparam(param) for param in r.findall(path)]
|
||||
name = r.sub('', path).replace("/", "_").replace('-', '_')[1:]
|
||||
name = mkname(method, name, params)
|
||||
params = ", {}".format(", ".join(params)) if params else ''
|
||||
print(' def {}(self{}):'.format(name, params))
|
||||
print(' """{}"""'.format(', '.join(body['tags'])))
|
||||
print(' return self.{}("{}"{})\n'.format(method, fmt, params))
|
||||
|
||||
|
||||
def generate(name, url):
|
||||
data = download(url)
|
||||
pretty_print(name, data)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) != 3:
|
||||
print("usage: {} <class-name> <url>".format(sys.argv[0]))
|
||||
sys.exit(1)
|
||||
generate(sys.argv[1], sys.argv[2])
|
Reference in New Issue
Block a user