Skip to content

Commit

Permalink
PEP8 compliance
Browse files Browse the repository at this point in the history
  • Loading branch information
BenjamenMeyer committed Feb 2, 2015
1 parent 1912b99 commit 6fe763e
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 90 deletions.
1 change: 1 addition & 0 deletions stackinabox/httpretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def httpretty_callback(request, uri, headers):
uri,
headers)


def httpretty_registration(uri):
logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty'
.format(uri))
Expand Down
3 changes: 2 additions & 1 deletion stackinabox/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ def responses_callback(request):
method = request.method
headers = request.headers
uri = request.url
return (200, headers, 'Hello')
return (200, headers, 'Hello')


def responses_registration(uri):
logger.debug('Registering Stack-In-A-Box at {0} under Python Responses'
Expand Down
132 changes: 72 additions & 60 deletions stackinabox/services/keystone/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,52 +28,52 @@
"""

schema = [
'''
CREATE TABLE keystone_tenants
(
tenantid INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
enabled INTEGER DEFAULT 1
)
''',
'''
CREATE TABLE keystone_users
(
tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid),
userid INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
apikey TEXT NOT NULL,
enabled INTEGER DEFAULT 1
)
''',
'''
CREATE TABLE keystone_tokens
(
tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid),
userid INTEGER NOT NULL REFERENCES keystone_users(userid),
token TEXT NOT NULL UNIQUE,
ttl DATETIME NOT NULL,
revoked INTEGER DEFAULT 0
)
''',
'''
CREATE TABLE keystone_roles
(
roleid INTEGER PRIMARY KEY AUTOINCREMENT,
rolename TEXT NOT NULL UNIQUE
)
''',
'''
CREATE TABLE keystone_user_roles
(
tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid),
userid INTEGER NOT NULL REFERENCES keystone_users(userid),
roleid INTEGER NOT NULL REFERENCES keystone_roles(roleid)
)
'''
'''
CREATE TABLE keystone_tenants
(
tenantid INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
enabled INTEGER DEFAULT 1
)
''',
'''
CREATE TABLE keystone_users
(
tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid),
userid INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
apikey TEXT NOT NULL,
enabled INTEGER DEFAULT 1
)
''',
'''
CREATE TABLE keystone_tokens
(
tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid),
userid INTEGER NOT NULL REFERENCES keystone_users(userid),
token TEXT NOT NULL UNIQUE,
ttl DATETIME NOT NULL,
revoked INTEGER DEFAULT 0
)
''',
'''
CREATE TABLE keystone_roles
(
roleid INTEGER PRIMARY KEY AUTOINCREMENT,
rolename TEXT NOT NULL UNIQUE
)
''',
'''
CREATE TABLE keystone_user_roles
(
tenantid INTEGER NOT NULL REFERENCES keystone_tenants(tenantid),
userid INTEGER NOT NULL REFERENCES keystone_users(userid),
roleid INTEGER NOT NULL REFERENCES keystone_roles(roleid)
)
'''
]

SQL_ADD_TENANT = '''
Expand Down Expand Up @@ -131,7 +131,7 @@
SELECT tenantid, userid, username, email, password, apikey, enabled
FROM keystone_users
WHERE tenantid = :tenantid AND
username = :username
username = :username
'''

SQL_GET_USER_BY_USERID = '''
Expand Down Expand Up @@ -172,7 +172,8 @@
'''

SQL_GET_TOKEN_BY_USER_NAME = '''
SELECT keystone_tokens.tenantid, keystone_tokens.userid, keystone_tokens.token, keystone_tokens.ttl, keystone_tokens.revoked
SELECT keystone_tokens.tenantid, keystone_tokens.userid,
keystone_tokens.token, keystone_tokens.ttl, keystone_tokens.revoked
FROM keystone_tokens, keystone_users
WHERE keystone_tokens.tenantid = keystone_users.tenantid
AND keystone_tokens.userid = keystone_users.userid
Expand Down Expand Up @@ -225,6 +226,7 @@
AND keystone_user_roles.userid = :userid
'''


class KeystoneError(Exception):
pass

Expand Down Expand Up @@ -266,7 +268,7 @@ class KeystoneBackend(object):
IDENTITY_ADMIN_ROLE = 'identity:user-admin'

def __init__(self):
self.__admin_token = 'adminstrate_with_this_{0}'.format(uuid.uuid4())
self.__admin_token = 'adminstrate_with_this_{0}'.format(uuid.uuid4())
self.database = sqlite3.connect(':memory:')
self.init_database()

Expand All @@ -292,8 +294,13 @@ def init_database(self):
dbcursor.execute(table_sql)

# Create an admin user and add the admin token to that user
self.__admin_tenant_id = self.add_tenant('system', 'system administrator')
self.__admin_user_id = self.add_user(self.__admin_tenant_id, 'system', 'system@stackinabox', 'stackinabox','537461636b496e41426f78')
self.__admin_tenant_id = self.add_tenant('system',
'system administrator')
self.__admin_user_id = self.add_user(self.__admin_tenant_id,
'system',
'system@stackinabox',
'stackinabox',
'537461636b496e41426f78')
role_data = self.add_role(KeystoneBackend.IDENTITY_ADMIN_ROLE)
self.__admin_role_id = role_data['roleid']
self.add_user_role_by_roleid(self.__admin_tenant_id,
Expand All @@ -307,7 +314,7 @@ def init_database(self):
self.database.commit()

def get_admin_token(self):
return self.__admin_token
return self.__admin_token

def add_tenant(self, tenantname=None, description=None, enabled=True):
args = {
Expand All @@ -325,7 +332,8 @@ def add_tenant(self, tenantname=None, description=None, enabled=True):
dbcursor.execute(SQL_GET_MAX_TENANT_ID)
tenant_data = dbcursor.fetchone()
if tenant_data is None:
raise KeystoneTenantError('Unable to retrieve tenantid for newly created tenant')
raise KeystoneTenantError(
'Unable to retrieve tenantid for newly created tenant')

tenantid = tenant_data[0]
return tenantid
Expand Down Expand Up @@ -400,7 +408,8 @@ def update_tenant_status(self, tenantid=None, enabled=None):

self.database.commit()

def add_user(self, tenantid=None, username=None, email=None, password=None, apikey=None, enabled=True):
def add_user(self, tenantid=None, username=None, email=None,
password=None, apikey=None, enabled=True):
args = {
'tenantid': tenantid,
'username': username,
Expand Down Expand Up @@ -481,7 +490,8 @@ def get_users_for_tenant_id(self, tenantid=None):
})
return results

def add_token(self, tenantid=None, userid=None, expire_time=None, token=None):
def add_token(self, tenantid=None, userid=None,
expire_time=None, token=None):
if token is None:
token = uuid.uuid4()

Expand All @@ -493,7 +503,8 @@ def add_token(self, tenantid=None, userid=None, expire_time=None, token=None):
}
if expire_time is not None:
if not isinstance(expire_time, datetime.datetime):
raise TypeError('expire_time must be a datetime.datetime object')
raise TypeError(
'expire_time must be a datetime.datetime object')

'''2015-02-03 02:31:17'''
utc_expire_time = expire_time.utctimetuple()
Expand All @@ -503,8 +514,7 @@ def add_token(self, tenantid=None, userid=None, expire_time=None, token=None):
utc_expire_time[2],
utc_expire_time[3],
utc_expire_time[4],
utc_expire_time[5]
)
utc_expire_time[5])
dbcursor.execute(SQL_INSERT_TOKEN_AND_EXPIRATION, args)
else:
dbcursor.execute(SQL_INSERT_TOKEN, args)
Expand All @@ -527,7 +537,8 @@ def revoke_token(self, tenantid=None, userid=None, reset=False):
dbcursor.execute(SQL_REVOKE_TOKEN, args)

if not dbcursor.rowcount:
raise KeystoneTokenError('Unknown tenantid or userid; or no associated token')
raise KeystoneTokenError(
'Unknown tenantid or userid; or no associated token')

self.database.commit()

Expand Down Expand Up @@ -622,7 +633,8 @@ def add_user_role_by_roleid(self, tenantid=None, userid=None, roleid=None):
if not dbcursor.rowcount:
raise KeystoneRoleError('Unable to assign role to tenantid/userid')

def add_user_role_by_rolename(self, tenantid=None, userid=None, rolename=None):
def add_user_role_by_rolename(self, tenantid=None, userid=None,
rolename=None):
role_data = self.get_role_id(rolename)
self.add_user_role_by_roleid(tenantid, userid, role_data['roleid'])

Expand Down
32 changes: 23 additions & 9 deletions stackinabox/services/keystone/v2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ def __init__(self):
self.__id = uuid.uuid4()
self.__backend = KeystoneBackend()

self.register(StackInABoxService.GET, '/tenants', KeystoneV2Service.handle_list_tenants)
self.register(StackInABoxService.GET, '/users', KeystoneV2Service.handle_list_users)
self.register(StackInABoxService.GET,
'/tenants',
KeystoneV2Service.handle_list_tenants)
self.register(StackInABoxService.GET,
'/users',
KeystoneV2Service.handle_list_users)

@property
def backend(self):
Expand All @@ -38,7 +42,8 @@ def handle_list_tenants(self, request, uri, headers):
'''
200, 203 -> OK
400 -> Bad Request: one or more required parameters is missing or invalid
400 -> Bad Request: one or more required parameters
are missing or invalid
401 -> not authorized
403 -> forbidden (no permission)
404 -> Not found
Expand All @@ -56,12 +61,17 @@ def handle_list_tenants(self, request, uri, headers):
"""
Body on success:
body = {
'tenants' : [ {'id': 01234, 'name': 'bob', 'description': 'joe bob', 'enabled': True }]
'tenants' : [ {'id': 01234,
'name': 'bob',
'description': 'joe bob',
'enabled': True }]
'tenants_links': []
}
"""
response_body = {
'tenants' : [tenant_info for tenant_info in self.backend.get_tenants()],
'tenants': [tenant_info
for tenant_info in
self.backend.get_tenants()],
'tenants_links': []
}
return (200, headers, json.dumps(response_body))
Expand Down Expand Up @@ -92,21 +102,25 @@ def user_data_filter(user):

if 'x-auth-token' in req_headers:
try:
user_data = self.backend.validate_token_admin(req_headers['x-auth-token'])
user_data = self.backend.validate_token_admin(
req_headers['x-auth-token'])

if user_data:
logger.debug('KeystoneV2Service({0}): Token Valid for tenantid {1}'
logger.debug('KeystoneV2Service({0}): Token Valid for '
'tenantid {1}'
.format(self.__id, user_data['tenantid']))
response_body = {
'users': [user_data_filter(user_info)
for user_info in
self.backend.get_users_for_tenant_id(user_data['tenantid'])]
self.backend.get_users_for_tenant_id(
user_data['tenantid'])]
}
return (200, headers, json.dumps(response_body))

else:
return (200, headers, json.dumps({'users': []}))

except Exception as ex:
return (401, headers, 'Not Authorized - {0} {1}'.format(ex, type(ex)))
return (401, headers, 'Not Authorized')
else:
return (403, headers, 'Forbidden')
32 changes: 21 additions & 11 deletions stackinabox/services/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,12 @@ def base_url(self):

@base_url.setter
def base_url(self, value):
logger.debug('StackInABoxService ({0}:{1}) Updating Base URL from {2} to {3}'
.format(self.__id, self.name, self.__base_url, value))
logger.debug('StackInABoxService ({0}:{1}) Updating Base URL '
'from {2} to {3}'
.format(self.__id,
self.name,
self.__base_url,
value))
self.__base_url = value
for k, v in self.routes.items():
v['regex'] = StackInABoxService.__get_service_regex(value,
Expand All @@ -70,21 +74,27 @@ def reset(self):
self.base_url = '/{0}'.format(self.name)
logger.debug('StackInABoxService ({0}): Hosting Service {1}'
.format(self.__id, self.name))



def request(self, method, request, uri, headers):
logger.debug('StackInABoxService ({0}:{1}): Received {2} - {3}'
.format(self.__id, self.name, method, uri))
for k, v in self.routes.items():
logger.debug('StackInABoxService ({0}:{1}): Checking if route {1} handles...'
logger.debug('StackInABoxService ({0}:{1}): Checking if '
'route {1} handles...'
.format(self.__id, self.name, v['uri']))
logger.debug('StackInABoxService ({0}:{1}): ...using regex pattern {1} against {2}'
.format(self.__id, self.name, v['regex'].pattern, uri))
logger.debug('StackInABoxService ({0}:{1}): ...using regex '
'pattern {1} against {2}'
.format(self.__id,
self.name,
v['regex'].pattern,
uri))
if v['regex'].match(uri):
logger.debug('StackInABoxService ({0}:{1}): Checking if method {2} is handled...'
logger.debug('StackInABoxService ({0}:{1}): Checking if '
'method {2} is handled...'
.format(self.__id, self.name, method))
if method in v['handlers']:
logger.debug('StackInABoxService ({0}:{1}): Calling handler for method {2}...'
logger.debug('StackInABoxService ({0}:{1}): Calling '
'handler for method {2}...'
.format(self.__id, self.name, method))
return v['handlers'][method](self,
request,
Expand All @@ -95,7 +105,7 @@ def request(self, method, request, uri, headers):
def register(self, method, uri, call_back):
found = False

if not uri in self.routes.keys():
if uri not in self.routes.keys():
logger.debug('Service ({0}): Creating routes'
.format(self.name))
self.routes[uri] = {
Expand All @@ -106,7 +116,7 @@ def register(self, method, uri, call_back):
}
}

if not method in self.routes[uri]['handlers'].keys():
if method not in self.routes[uri]['handlers'].keys():
logger.debug('Service ({0}): Adding route for {1}'
.format(self.name, method))
self.routes[uri]['handlers'][method] = call_back
Expand Down
Loading

0 comments on commit 6fe763e

Please sign in to comment.