Fixed PEP8 violations

This commit is contained in:
John Wood 2013-04-08 19:07:17 -05:00
parent 1fd044edcc
commit 6f3531d8ec
12 changed files with 90 additions and 47 deletions

View File

@ -37,20 +37,19 @@ def abort(status=falcon.HTTP_500, message=None):
raise falcon.HTTPError(status, message) raise falcon.HTTPError(status, message)
def load_body(req, required=[]): def load_body(req):
""" """
Helper function for loading an HTTP request body from JSON into a Helper function for loading an HTTP request body from JSON into a
Python dictionary Python dictionary
""" """
try: try:
raw_json = req.stream.read() raw_json = req.stream.read()
except IOError:
except Exception:
abort(falcon.HTTP_500, 'Read Error') abort(falcon.HTTP_500, 'Read Error')
try: try:
parsed_body = json.loads(raw_json, 'utf-8') parsed_body = json.loads(raw_json, 'utf-8')
except ValueError as ve: except ValueError:
abort(falcon.HTTP_400, 'Malformed JSON') abort(falcon.HTTP_400, 'Malformed JSON')
return parsed_body return parsed_body

View File

@ -1,12 +1,36 @@
# Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
# 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.
"""
API application handler for Cloudkeep's Barbican
"""
import falcon import falcon
from barbican.api.resources import * from barbican.api.resources import VersionResource
from barbican.api.resources import TenantsResource, TenantResource
from config import config from barbican.api.resources import SecretsResource, SecretResource
from sqlalchemy import create_engine, MetaData from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.orm import scoped_session, sessionmaker
from barbican.model.tenant import Base from barbican.model.tenant import Base
# TBD: Remove this odd dependency
from config import config
""" """
Locally scoped db session Locally scoped db session
""" """
@ -52,12 +76,10 @@ secrets = SecretsResource(db_session())
secret = SecretResource(db_session()) secret = SecretResource(db_session())
# Routing # Routing
application = api = falcon.API() application = falcon.API()
api = application
api.add_route('/', versions) api.add_route('/', versions)
api.add_route('/v1', tenants) api.add_route('/v1', tenants)
api.add_route('/v1/{tenant_id}', tenant) api.add_route('/v1/{tenant_id}', tenant)
api.add_route('/v1/{tenant_id}/secrets', secrets) api.add_route('/v1/{tenant_id}/secrets', secrets)
api.add_route('/v1/{tenant_id}/secrets/{secret_id}', secret) api.add_route('/v1/{tenant_id}/secrets/{secret_id}', secret)

View File

@ -13,12 +13,15 @@ from barbican.model.tenant import Tenant, Secret
def _tenant_not_found(): def _tenant_not_found():
abort(falcon.HTTP_404, 'Unable to locate tenant.') abort(falcon.HTTP_404, 'Unable to locate tenant.')
def _tenant_already_exists(): def _tenant_already_exists():
abort(falcon.HTTP_400, 'Tenant already exists.') abort(falcon.HTTP_400, 'Tenant already exists.')
def _secret_not_found(): def _secret_not_found():
abort(falcon.HTTP_400, 'Unable to locate secret profile.') abort(falcon.HTTP_400, 'Unable to locate secret profile.')
def format_tenant(tenant): def format_tenant(tenant):
if not isinstance(tenant, dict): if not isinstance(tenant, dict):
tenant = tenant.__dict__ tenant = tenant.__dict__
@ -105,8 +108,9 @@ class SecretsResource(ApiResource):
# Check if the tenant already has a secret with this name # Check if the tenant already has a secret with this name
for secret in tenant.secrets: for secret in tenant.secrets:
if secret.name == secret_name: if secret.name == secret_name:
abort(falcon.HTTP_400, 'Secret with name {0} already exists.' abort(falcon.HTTP_400,
.format(secret.name, secret.id)) 'Secret with name {0} already exists.'.format(
secret.name, secret.id))
# Create the new secret # Create the new secret
new_secret = Secret(tenant.id, secret_name) new_secret = Secret(tenant.id, secret_name)
@ -133,7 +137,7 @@ class SecretResource(ApiResource):
#verify the secret exists #verify the secret exists
secret = find_secret(self.db, id=secret_id, secret = find_secret(self.db, id=secret_id,
when_not_found=_secret_not_found) when_not_found=_secret_not_found)
#verify the secret belongs to the tenant #verify the secret belongs to the tenant
if not secret in tenant.secrets: if not secret in tenant.secrets:

View File

@ -1,8 +1,10 @@
#from oslo.config import cfg #from oslo.config import cfg
#from barbican.config import get_config #from barbican.config import get_config
# Handler configuration options # Handler configuration options
#datasource_group = cfg.OptGroup(name='datasource', title='Datasource Configuration Options') # datasource_group = cfg.OptGroup(name='datasource', title='Datasource
# Configuration Options')
#get_config().register_group(datasource_group) #get_config().register_group(datasource_group)
#HANDLER_OPTIONS = [ #HANDLER_OPTIONS = [
@ -53,6 +55,7 @@ class DatasourceHandlerManager():
_DATASOURCE_HANDLERS = DatasourceHandlerManager() _DATASOURCE_HANDLERS = DatasourceHandlerManager()
class DatasourceHandler(): class DatasourceHandler():
status = STATUS_NEW status = STATUS_NEW
@ -74,4 +77,3 @@ class DatasourceHandler():
def delete(self, object_name, object_id): def delete(self, object_name, object_id):
raise NotImplementedError raise NotImplementedError

View File

@ -2,14 +2,18 @@ from barbican.data.adapters.handler import datasource_handler
handler = datasource_handler handler = datasource_handler
def get_tenant(tenant_id): def get_tenant(tenant_id):
pass pass
def save_tenant(tenant_object): def save_tenant(tenant_object):
pass pass
def create_tenant(tenant_id): def create_tenant(tenant_id):
pass pass
def delete_tenant(tenant_id): def delete_tenant(tenant_id):
pass pass

View File

@ -29,7 +29,7 @@ from sqlalchemy.ext.declarative import declarative_base, declared_attr
# #
# class Secret(Base): # class Secret(Base):
# """ # """
# A secret is any information that needs to be stored and protected within # A secret is any information that needs to be stored and protected within
# Cloudkeep's Barbican. # Cloudkeep's Barbican.
# """ # """
# #
@ -40,4 +40,3 @@ from sqlalchemy.ext.declarative import declarative_base, declared_attr
# #
# def __init__(self, secret_id): # def __init__(self, secret_id):
# self.secret_id = secret_id # self.secret_id = secret_id

View File

@ -29,7 +29,8 @@ from sqlalchemy.ext.declarative import declarative_base, declared_attr
class Tenant(Base): class Tenant(Base):
""" """
Tenants are users that wish to store secret information within Cloudkeep's Barbican. Tenants are users that wish to store secret information within
Cloudkeep's Barbican.
""" """
logging.debug('In Tenant table setup') logging.debug('In Tenant table setup')
@ -44,7 +45,6 @@ class Tenant(Base):
# order_by="desc(Secret.name)", # order_by="desc(Secret.name)",
# primaryjoin="Secret.tenant_id==Tenant.id") # primaryjoin="Secret.tenant_id==Tenant.id")
def __init__(self, username): def __init__(self, username):
self.username = username self.username = username
@ -54,12 +54,13 @@ class Tenant(Base):
def format(self): def format(self):
return {'id': self.id, return {'id': self.id,
'username': self.username} 'username': self.username}
class Secret(Base): class Secret(Base):
""" """
A secret is any information that needs to be stored and protected within Cloudkeep's Barbican. A secret is any information that needs to be stored and protected within
Cloudkeep's Barbican.
""" """
__tablename__ = "secrets" __tablename__ = "secrets"
@ -83,4 +84,3 @@ class Secret(Base):
return {'id': self.id, return {'id': self.id,
'name': self.username, 'name': self.username,
'tenant_id': self.tenant_id} 'tenant_id': self.tenant_id}

View File

@ -24,7 +24,7 @@ def find_tenant(db_session, id=None, username=None,
def find_secret(db_session, id, when_not_found=_empty_condition, def find_secret(db_session, id, when_not_found=_empty_condition,
when_multiple_found=_empty_condition): when_multiple_found=_empty_condition):
try: try:
return db_session.query(Secret).filter_by(id=id).one() return db_session.query(Secret).filter_by(id=id).one()
except NoResultFound: except NoResultFound:

9
config.py Normal file
View File

@ -0,0 +1,9 @@
config = {
'sqlalchemy': {
'url': 'sqlite:////tmp/barbican.db',
'echo': True,
'echo_pool': False,
'pool_recycle': 3600,
'encoding': 'utf-8'
}
}

View File

@ -1,9 +1,9 @@
config = { config = {
'sqlalchemy' : { 'sqlalchemy': {
'url' : 'sqlite:////tmp/barbican.db', 'url': 'sqlite:////tmp/barbican.db',
'echo' : True, 'echo': True,
'echo_pool' : False, 'echo_pool': False,
'pool_recycle' : 3600, 'pool_recycle': 3600,
'encoding' : 'utf-8' 'encoding': 'utf-8'
} }
} }

View File

@ -25,18 +25,20 @@ except ImportError:
from setuptools.command.sdist import sdist from setuptools.command.sdist import sdist
# Determine version of this application. # Determine version of this application.
# TBD: Revisit version flows and processing once integrating with OpenStack, see glance setup.py # TBD: Revisit version flows and processing once integrating with OpenStack,
# see glance setup.py
PKG = "barbican" PKG = "barbican"
VERSIONFILE = os.path.join(PKG, "version.py") VERSIONFILE = os.path.join(PKG, "version.py")
version = "unknown" version = "unknown"
try: try:
version_file = open(VERSIONFILE, "r") version_file = open(VERSIONFILE, "r")
for line in version_file: for line in version_file:
if '__version__' in line: if '__version__' in line:
version = line.split("'")[1] version = line.split("'")[1]
break break
except EnvironmentError: except EnvironmentError:
pass # Okay, there is no version file. pass # Okay, there is no version file.
class local_sdist(sdist): class local_sdist(sdist):
"""Customized sdist hook - builds the ChangeLog file from VC first""" """Customized sdist hook - builds the ChangeLog file from VC first"""
@ -46,19 +48,20 @@ class local_sdist(sdist):
cmdclass = {'sdist': local_sdist} cmdclass = {'sdist': local_sdist}
# TDB: Revisit sphinx documentation needs once move to OpenStack...see glance setup.py # TDB: Revisit sphinx documentation needs once move to OpenStack...
# see glance setup.py
setup( setup(
name = 'barbican', name='barbican',
version = version, version=version,
description = 'The Barbican project provides a service for storing ' description='The Barbican project provides a service for storing '
'sensitive client information such as encryption keys', 'sensitive client information such as encryption keys',
license='Apache License (2.0)', license='Apache License (2.0)',
author = 'OpenStack', author='OpenStack',
author_email = 'john.wood@rackspace.com', author_email='john.wood@rackspace.com',
url='http://barbican.openstack.org/', url='http://barbican.openstack.org/',
packages = find_packages(exclude=['bin']), packages=find_packages(exclude=['bin']),
test_suite = 'nose.collector', test_suite='nose.collector',
cmdclass=cmdclass, cmdclass=cmdclass,
include_package_data=True, include_package_data=True,
classifiers=[ classifiers=[

View File

@ -58,7 +58,7 @@ def run_command(cmd, redirect_output=True, check_exit_code=True):
HAS_EASY_INSTALL = bool(run_command(['which', 'easy_install'], HAS_EASY_INSTALL = bool(run_command(['which', 'easy_install'],
check_exit_code=False).strip()) check_exit_code=False).strip())
HAS_VIRTUALENV = bool(run_command(['which', 'virtualenv'], HAS_VIRTUALENV = bool(run_command(['which', 'virtualenv'],
check_exit_code=False).strip()) check_exit_code=False).strip())
def check_dependencies(): def check_dependencies():
@ -108,7 +108,8 @@ def install_dependencies(venv=VENV):
# Tell the virtual env how to "import barbican" # Tell the virtual env how to "import barbican"
py_ver = _detect_python_version(venv) py_ver = _detect_python_version(venv)
pthfile = os.path.join(venv, "lib", py_ver, "site-packages", "barbican.pth") pthfile = os.path.join(venv, "lib", py_ver,
"site-packages", "barbican.pth")
f = open(pthfile, 'w') f = open(pthfile, 'w')
f.write("%s\n" % ROOT) f.write("%s\n" % ROOT)
@ -128,8 +129,8 @@ def print_help():
Barbican development uses virtualenv to track and manage Python dependencies Barbican development uses virtualenv to track and manage Python dependencies
while in development and testing. while in development and testing.
To activate the Barbican virtualenv for the extent of your current shell session To activate the Barbican virtualenv for the extent of your current shell
you can run: session you can run:
$ source .venv/bin/activate $ source .venv/bin/activate