Skip to content

Commit

Permalink
Python: Format with black and switch superlint (#5513)
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidSouther authored Oct 18, 2023
1 parent 3cf0a1b commit afb3309
Show file tree
Hide file tree
Showing 506 changed files with 30,608 additions and 19,139 deletions.
8 changes: 5 additions & 3 deletions .doc_gen/readmes/multi.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

Expand Down Expand Up @@ -42,12 +43,13 @@ def main():
help="When set, output verbose debugging info.",
)
parser.add_argument(
"--dry_run",
"--dry-run",
action="store_true",
help="This tool is in development. You must pass --dry_run=false to have it run.",
dest="dry_run",
help="This tool is in development. You must pass --dry-run=false to have it run.",
default=True, # Change this to default false when we're ready to use this generally.
)
parser.add_argument("--no_dry_run", dest="dry_run", action="store_false")
parser.add_argument("--no-dry-run", dest="dry_run", action="store_false")
args = parser.parse_args()

if "all" in args.languages:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/super-linter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VALIDATE_PHP_PHPCS: true
VALIDATE_PYTHON: true
VALIDATE_PYTHON_PYLINT: true
VALIDATE_PYTHON_BLACK: true
VALIDATE_RUBY: true
VALIDATE_CSHARP: true
VALIDATE_KOTLIN: true
Expand Down
38 changes: 21 additions & 17 deletions python/cross_service/apigateway_covid-19_tracker/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import chalice
import chalicelib.covid_data

app = chalice.Chalice(app_name='fictional-covid')
app = chalice.Chalice(app_name="fictional-covid")
app.debug = True # Set this to False for production use.

logger = logging.getLogger()
Expand Down Expand Up @@ -53,14 +53,16 @@ def verify_input(state, date=None, data=None):
if state not in storage.STATES:
raise chalice.BadRequestError(
f"Unknown state '{state}'.\nYour choices are: "
f"{', '.join(sorted(storage.STATES))}")
f"{', '.join(sorted(storage.STATES))}"
)

if data is not None and state != data['state']:
if data is not None and state != data["state"]:
raise chalice.BadRequestError(
f"The state '{data['state']}' specified in the request body does not "
f"match the state '{state}' specified in the URL.")
f"match the state '{state}' specified in the URL."
)

test_date = date if date is not None else None if data is None else data['date']
test_date = date if date is not None else None if data is None else data["date"]
if test_date is not None:
try:
iso_date = datetime.date.fromisoformat(test_date)
Expand All @@ -69,23 +71,24 @@ def verify_input(state, date=None, data=None):
if iso_date < earliest_date or iso_date > today:
raise chalice.BadRequestError(
f"Date must be between {earliest_date} and {today}. "
f"{test_date} is outside that range.")
f"{test_date} is outside that range."
)
except ValueError as error:
raise chalice.BadRequestError from error


@app.route('/states', methods=['GET'])
@app.route("/states", methods=["GET"])
def list_states():
"""
Lists the allowed states.
:return: The list of states allowed by the Storage class.
"""
# Chalice automatically serializes the returned dict to JSON.
return {'states': ', '.join(sorted(storage.STATES))}
return {"states": ", ".join(sorted(storage.STATES))}


@app.route('/states/{state}', methods=['DELETE', 'GET', 'POST', 'PUT'])
@app.route("/states/{state}", methods=["DELETE", "GET", "POST", "PUT"])
def state_cases(state):
"""
Handles requests for a specific state.
Expand All @@ -106,21 +109,22 @@ def state_cases(state):
verify_input(state, data=app.current_request.json_body)

response = None
if app.current_request.method == 'GET':
if app.current_request.method == "GET":
# To use a custom converter, serialize the response to JSON here.
response = json.dumps(
storage.get_state_data(state), default=convert_decimal_to_int)
elif app.current_request.method == 'PUT':
storage.get_state_data(state), default=convert_decimal_to_int
)
elif app.current_request.method == "PUT":
storage.put_state_data(state, app.current_request.json_body)
elif app.current_request.method == 'DELETE':
elif app.current_request.method == "DELETE":
storage.delete_state_data(state)
elif app.current_request.method == 'POST':
elif app.current_request.method == "POST":
storage.post_state_data(state, app.current_request.json_body)

return response


@app.route('/states/{state}/{date}', methods=['DELETE', 'GET'])
@app.route("/states/{state}/{date}", methods=["DELETE", "GET"])
def state_date_cases(state, date):
"""
Handles requests for a specific state and date. Dates must be in ISO format and
Expand All @@ -145,13 +149,13 @@ def state_date_cases(state, date):
verify_input(state, date=date)

response = None
if app.current_request.method == 'GET':
if app.current_request.method == "GET":
response = storage.get_state_date_data(state, date)
if response is not None:
response = json.dumps(response, default=convert_decimal_to_int)
else:
raise chalice.NotFoundError(f"No data found for {state} on {date}.")
elif app.current_request.method == 'DELETE':
elif app.current_request.method == "DELETE":
storage.delete_state_date_data(state, date)

return response
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,58 @@ class Storage:
"""
Handles basic storage functions, backed by an Amazon DynamoDB table.
"""

STATES = {
'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',
'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho',
'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine',
'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey',
'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio',
'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina',
'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia',
'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming",
}

def __init__(self, table):
Expand All @@ -43,8 +85,8 @@ def from_env(cls):
:return: The newly created Storage object.
"""
table_name = os.environ.get('TABLE_NAME', '')
table = boto3.resource('dynamodb').Table(table_name)
table_name = os.environ.get("TABLE_NAME", "")
table = boto3.resource("dynamodb").Table(table_name)
return cls(table)

@staticmethod
Expand All @@ -56,10 +98,10 @@ def _generate_random_data(state):
:return: The newly created data.
"""
return {
'state': state,
'date': datetime.date.today().isoformat(),
'cases': random.randint(1, 1000),
'deaths': random.randint(1, 100)
"state": state,
"date": datetime.date.today().isoformat(),
"cases": random.randint(1, 1000),
"deaths": random.randint(1, 100),
}

def get_state_data(self, state):
Expand All @@ -71,10 +113,8 @@ def get_state_data(self, state):
:param state: The state to retrieve.
:return: The retrieved data.
"""
response = self._table.query(
KeyConditionExpression=Key('state').eq(state)
)
items = response.get('Items', [])
response = self._table.query(KeyConditionExpression=Key("state").eq(state))
items = response.get("Items", [])
if len(items) == 0:
items.append(self._generate_random_data(state))
self._table.put_item(Item=items[0])
Expand All @@ -95,13 +135,11 @@ def delete_state_data(self, state):
:param state: The state to delete.
"""
response = self._table.query(
KeyConditionExpression=Key('state').eq(state)
)
items = response.get('Items', [])
response = self._table.query(KeyConditionExpression=Key("state").eq(state))
items = response.get("Items", [])
with self._table.batch_writer() as batch:
for item in items:
batch.delete_item(Key={'state': item['state'], 'date': item['date']})
batch.delete_item(Key={"state": item["state"], "date": item["date"]})

def post_state_data(self, state, state_data):
"""
Expand All @@ -120,8 +158,8 @@ def get_state_date_data(self, state, date):
:param date: The date of the record to retrieve.
:return: The retrieved record, or None if no record exists.
"""
response = self._table.get_item(Key={'state': state, 'date': date})
item = response.get('Item', None)
response = self._table.get_item(Key={"state": state, "date": date})
item = response.get("Item", None)
return item

def delete_state_date_data(self, state, date):
Expand All @@ -131,4 +169,4 @@ def delete_state_date_data(self, state, date):
:param state: The state of the record to remove.
:param date: The date of the record to remove.
"""
self._table.delete_item(Key={'state': state, 'date': date})
self._table.delete_item(Key={"state": state, "date": date})
Loading

0 comments on commit afb3309

Please sign in to comment.