Skip to content

Commit

Permalink
Use 'black' everywhere (#1076)
Browse files Browse the repository at this point in the history
  • Loading branch information
javulticat authored Nov 12, 2021
1 parent 752ffbd commit ca8ca63
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 101 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ mypy:
mypy --show-error-codes --pretty --ignore-missing-imports --strict zappa tests

black:
black zappa tests
black .

black-check:
black zappa tests --check
black . --check
@echo "If this fails, simply run: make black"

isort:
Expand Down
10 changes: 6 additions & 4 deletions example/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

@app.route('/', methods=['GET', 'POST'])

@app.route("/", methods=["GET", "POST"])
def lambda_handler(event=None, context=None):
logger.info('Lambda function invoked index()')
logger.info("Lambda function invoked index()")

return "Flask says Hello!!"

return 'Flask says Hello!!'

if __name__ == '__main__':
if __name__ == "__main__":
app.run(debug=True)
104 changes: 60 additions & 44 deletions example/authmodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@


def lambda_handler(event, context):
print("Client token: " + event['authorizationToken'])
print("Method ARN: " + event['methodArn'])
print("Client token: " + event["authorizationToken"])
print("Method ARN: " + event["methodArn"])
"""validate the incoming token"""
"""and produce the principal user identifier associated with the token"""

Expand All @@ -38,8 +38,8 @@ def lambda_handler(event, context):
"""made with the same token"""

"""the example policy below denies access to all resources in the RestApi"""
tmp = event['methodArn'].split(':')
apiGatewayArnTmp = tmp[5].split('/')
tmp = event["methodArn"].split(":")
apiGatewayArnTmp = tmp[5].split("/")
awsAccountId = tmp[4]

policy = AuthPolicy(principalId, awsAccountId)
Expand All @@ -58,15 +58,17 @@ def lambda_handler(event, context):
"""finally, build the policy and exit the function using return"""
return policy.build()


class HttpVerb:
GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
HEAD = "HEAD"
DELETE = "DELETE"
GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
HEAD = "HEAD"
DELETE = "DELETE"
OPTIONS = "OPTIONS"
ALL = "*"
ALL = "*"


class AuthPolicy:
awsAccountId = ""
Expand Down Expand Up @@ -104,40 +106,52 @@ def _addMethod(self, effect, verb, resource, conditions):
the internal list contains a resource ARN and a condition statement. The condition
statement can be null."""
if verb != "*" and not hasattr(HttpVerb, verb):
raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class")
raise NameError(
"Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class"
)
resourcePattern = re.compile(self.pathRegex)
if not resourcePattern.match(resource):
raise NameError("Invalid resource path: " + resource + ". Path should match " + self.pathRegex)
raise NameError(
"Invalid resource path: "
+ resource
+ ". Path should match "
+ self.pathRegex
)

if resource[:1] == "/":
resource = resource[1:]

resourceArn = ("arn:aws:execute-api:" +
self.region + ":" +
self.awsAccountId + ":" +
self.restApiId + "/" +
self.stage + "/" +
verb + "/" +
resource)
resourceArn = (
"arn:aws:execute-api:"
+ self.region
+ ":"
+ self.awsAccountId
+ ":"
+ self.restApiId
+ "/"
+ self.stage
+ "/"
+ verb
+ "/"
+ resource
)

if effect.lower() == "allow":
self.allowMethods.append({
'resourceArn' : resourceArn,
'conditions' : conditions
})
self.allowMethods.append(
{"resourceArn": resourceArn, "conditions": conditions}
)
elif effect.lower() == "deny":
self.denyMethods.append({
'resourceArn' : resourceArn,
'conditions' : conditions
})
self.denyMethods.append(
{"resourceArn": resourceArn, "conditions": conditions}
)

def _getEmptyStatement(self, effect):
"""Returns an empty statement object prepopulated with the correct action and the
desired effect."""
statement = {
'Action': 'execute-api:Invoke',
'Effect': effect[:1].upper() + effect[1:].lower(),
'Resource': []
"Action": "execute-api:Invoke",
"Effect": effect[:1].upper() + effect[1:].lower(),
"Resource": [],
}

return statement
Expand All @@ -151,12 +165,12 @@ def _getStatementForEffect(self, effect, methods):
statement = self._getEmptyStatement(effect)

for curMethod in methods:
if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
statement['Resource'].append(curMethod['resourceArn'])
if curMethod["conditions"] is None or len(curMethod["conditions"]) == 0:
statement["Resource"].append(curMethod["resourceArn"])
else:
conditionalStatement = self._getEmptyStatement(effect)
conditionalStatement['Resource'].append(curMethod['resourceArn'])
conditionalStatement['Condition'] = curMethod['conditions']
conditionalStatement["Resource"].append(curMethod["resourceArn"])
conditionalStatement["Condition"] = curMethod["conditions"]
statements.append(conditionalStatement)

statements.append(statement)
Expand Down Expand Up @@ -198,19 +212,21 @@ def build(self):
conditions. This will generate a policy with two main statements for the effect:
one statement for Allow and one statement for Deny.
Methods that includes conditions will have their own statement in the policy."""
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
(self.denyMethods is None or len(self.denyMethods) == 0)):
if (self.allowMethods is None or len(self.allowMethods) == 0) and (
self.denyMethods is None or len(self.denyMethods) == 0
):
raise NameError("No statements defined for the policy")

policy = {
'principalId' : self.principalId,
'policyDocument' : {
'Version' : self.version,
'Statement' : []
}
"principalId": self.principalId,
"policyDocument": {"Version": self.version, "Statement": []},
}

policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Allow", self.allowMethods))
policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Deny", self.denyMethods))
policy["policyDocument"]["Statement"].extend(
self._getStatementForEffect("Allow", self.allowMethods)
)
policy["policyDocument"]["Statement"].extend(
self._getStatementForEffect("Deny", self.denyMethods)
)

return policy
8 changes: 4 additions & 4 deletions example/mymodule.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
def myfunc():
print('Running my function in a schedule!')
print("Running my function in a schedule!")


def myfunc_with_events(event, context):
print('Event time was', event['time'])
print('This log is', context.log_group_name, context.log_stream_name)
print('Time left for execution:', context.get_remaining_time_in_millis())
print("Event time was", event["time"])
print("This log is", context.log_group_name, context.log_stream_name)
print("Time left for execution:", context.get_remaining_time_in_millis())
59 changes: 29 additions & 30 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,52 @@
import os
import sys
from setuptools import setup
from io import open
from zappa import __version__

with open('README.md', encoding='utf-8') as readme_file:
with open("README.md", encoding="utf-8") as readme_file:
long_description = readme_file.read()

with open(os.path.join(os.path.dirname(__file__), 'requirements.in')) as f:
with open(os.path.join(os.path.dirname(__file__), "requirements.in")) as f:
required = f.read().splitlines()

with open(os.path.join(os.path.dirname(__file__), 'test_requirements.in')) as f:
with open(os.path.join(os.path.dirname(__file__), "test_requirements.in")) as f:
test_required = f.read().splitlines()

setup(
name='zappa',
name="zappa",
version=__version__,
packages=['zappa'],
packages=["zappa"],
install_requires=required,
tests_require=test_required,
test_suite='nose.collector',
test_suite="nose.collector",
include_package_data=True,
license='MIT License',
description='Server-less Python Web Services for AWS Lambda and API Gateway',
license="MIT License",
description="Server-less Python Web Services for AWS Lambda and API Gateway",
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/zappa/Zappa',
author='Rich Jones',
author_email='rich@openwatch.net',
long_description_content_type="text/markdown",
url="https://github.com/zappa/Zappa",
author="Rich Jones",
author_email="rich@openwatch.net",
entry_points={
'console_scripts': [
'zappa=zappa.cli:handle',
'z=zappa.cli:handle',
"console_scripts": [
"zappa=zappa.cli:handle",
"z=zappa.cli:handle",
]
},
classifiers=[
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 3.0',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
"Environment :: Console",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Framework :: Django",
"Framework :: Django :: 1.11",
"Framework :: Django :: 2.0",
"Framework :: Django :: 3.0",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
)
35 changes: 18 additions & 17 deletions test_settings.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
APP_MODULE = 'tests.test_app'
APP_FUNCTION = 'hello_world'
APP_MODULE = "tests.test_app"
APP_FUNCTION = "hello_world"
DJANGO_SETTINGS = None
DEBUG = 'True'
LOG_LEVEL = 'DEBUG'
SCRIPT_NAME = 'hello_world'
DEBUG = "True"
LOG_LEVEL = "DEBUG"
SCRIPT_NAME = "hello_world"
DOMAIN = None
API_STAGE = 'ttt888'
PROJECT_NAME = 'ttt888'
API_STAGE = "ttt888"
PROJECT_NAME = "ttt888"

REMOTE_ENV='s3://lmbda/test_env.json'
REMOTE_ENV = "s3://lmbda/test_env.json"
## test_env.json
#{
# {
# "hello": "world"
#}
# }
#

AWS_EVENT_MAPPING = {
'arn:aws:s3:1': 'test_settings.aws_s3_event',
'arn:aws:sns:1': 'test_settings.aws_sns_event',
'arn:aws:dynamodb:1': 'test_settings.aws_dynamodb_event',
'arn:aws:kinesis:1': 'test_settings.aws_kinesis_event',
'arn:aws:sqs:1': 'test_settings.aws_sqs_event'
"arn:aws:s3:1": "test_settings.aws_s3_event",
"arn:aws:sns:1": "test_settings.aws_sns_event",
"arn:aws:dynamodb:1": "test_settings.aws_dynamodb_event",
"arn:aws:kinesis:1": "test_settings.aws_kinesis_event",
"arn:aws:sqs:1": "test_settings.aws_sqs_event",
}

ENVIRONMENT_VARIABLES={'testenv': 'envtest'}
ENVIRONMENT_VARIABLES = {"testenv": "envtest"}

AUTHORIZER_FUNCTION='test_settings.authorizer_event'
AUTHORIZER_FUNCTION = "test_settings.authorizer_event"


def prebuild_me():
Expand All @@ -43,6 +43,7 @@ def aws_s3_event(event, content):
def aws_sns_event(event, content):
return "AWS SNS EVENT"


def aws_async_sns_event(arg1, arg2, arg3):
return "AWS ASYNC SNS EVENT"

Expand Down

0 comments on commit ca8ca63

Please sign in to comment.