Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace all f-strings to use .format #756

Merged
merged 6 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/scripts/populateCountiesCities/cities.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def pull_cities():
)
time.sleep(1)
except Exception as e:
print(f"Error: {e}")
print("Error: {}".format(e))
pass

df = pd.DataFrame(holding_pen, columns=["State", "County", "City", "URL"])
Expand Down
2 changes: 1 addition & 1 deletion backend/scripts/populateCountiesCities/counties.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def pull_counties():
}
)
except Exception as e:
print(f"Error: {e}")
print("Error: {}".format(e))
pass

time.sleep(1)
Expand Down
12 changes: 6 additions & 6 deletions backend/src/xfd_django/xfd_api/api_methods/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@

async def handle_okta_callback(request):
"""POST API LOGIC."""
print(f"Request from /auth/okta-callback: {str(request)}")
print("Request from /auth/okta-callback: {}".format(str(request)))
body = await request.json()
print(f"Request json from callback: {str(request)}")
print(f"Request json from callback: {body}")
print(f"Body type: {type(body)}")
print("Request json from callback: {}".format(str(request)))
print("Request json from callback: {}".format(body))
print("Body type: {}".format(type(body)))
code = body.get("code")
print(f"Code: {code}")
print("Code: {}".format(code))
if not code:
return HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Code not found in request body",
)
jwt_data = await get_jwt_from_code(code)
print(f"JWT Data: {jwt_data}")
print("JWT Data: {}".format(jwt_data))
if jwt_data is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
Expand Down
4 changes: 2 additions & 2 deletions backend/src/xfd_django/xfd_api/api_methods/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def export_domains(domain_search: DomainSearch, current_user):
for product in service.products.all():
if product.name:
product_entry = (
f"{product.name} {product.version}"
"{} {}".format(product.name, product.version)
if product.version
else product.name
)
Expand Down Expand Up @@ -221,5 +221,5 @@ def export_domains(domain_search: DomainSearch, current_user):

except Exception as e:
# Log the exception for debugging (optional)
print(f"Error exporting domains: {e}")
print("Error exporting domains: {}".format(e))
raise HTTPException(status_code=500, detail=str(e))
8 changes: 4 additions & 4 deletions backend/src/xfd_django/xfd_api/api_methods/organization.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def get_organization(organization_id, current_user):
raise http_exc

except Exception as e:
print(f"An error occurred: {e}")
print("An error occurred: {}".format(e))
raise HTTPException(status_code=500, detail=str(e))


Expand Down Expand Up @@ -715,7 +715,7 @@ def delete_organization(org_id: str, current_user):
# Return success response
return {
"status": "success",
"message": f"Organization {org_id} has been deleted successfully.",
"message": "Organization {} has been deleted successfully.".format(org_id),
}

except HTTPException as http_exc:
Expand Down Expand Up @@ -1064,7 +1064,7 @@ def search_organizations_task(search_body, current_user: User):
# Use match_all if searchTerm is empty
if search_body.searchTerm.strip():
query_body["query"]["bool"]["must"].append(
{"wildcard": {"name": f"*{search_body.searchTerm}*"}}
{"wildcard": {"name": "*{}*".format(search_body.searchTerm)}}
)
else:
query_body["query"]["bool"]["must"].append({"match_all": {}})
Expand All @@ -1076,7 +1076,7 @@ def search_organizations_task(search_body, current_user: User):
)

# Log the query for debugging
print(f"Query body: {query_body}")
print("Query body: {}".format(query_body))

# Execute the search
search_results = client.search_organizations(query_body)
Expand Down
4 changes: 2 additions & 2 deletions backend/src/xfd_django/xfd_api/api_methods/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ async def proxy_request(
if cookie_name:
cookies = manipulate_cookie(request, cookie_name)
if cookies:
headers["Cookie"] = f"{cookie_name}={cookies[cookie_name]}"
headers["Cookie"] = "{}={}".format(cookie_name, cookies[cookie_name])

# Make the request to the target URL
async with httpx.AsyncClient() as client:
proxy_response = await client.request(
method=request.method,
url=f"{target_url}/{path}",
url="{}/{}".format(target_url, path),
headers=headers,
params=request.query_params,
content=await request.body(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def delete_saved_search(saved_search_id, user):
return JsonResponse(
{
"status": "success",
"message": f"Saved search id:{saved_search_id} deleted.",
"message": "Saved search id:{} deleted.".format(saved_search_id),
}
)
except User.DoesNotExist:
Expand Down
9 changes: 6 additions & 3 deletions backend/src/xfd_django/xfd_api/api_methods/scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,10 @@ def delete_scan(scan_id: str, current_user):

scan.delete()

return {"status": "success", "message": f"Scan {scan_id} deleted successfully."}
return {
"status": "success",
"message": "Scan {} deleted successfully.".format(scan_id),
}

except HTTPException as http_exc:
raise http_exc
Expand All @@ -297,7 +300,7 @@ def run_scan(scan_id: str, current_user):
scan.save()
return {
"status": "success",
"message": f"Scan {scan_id} set to manualRunPending.",
"message": "Scan {} set to manualRunPending.".format(scan_id),
}

except HTTPException as http_exc:
Expand All @@ -320,7 +323,7 @@ async def invoke_scheduler(current_user):
lambda_client = LambdaClient()

# Form the lambda function name using environment variable
lambda_function_name = f"{os.getenv('SLS_LAMBDA_PREFIX')}-scheduler"
lambda_function_name = "{}-scheduler".format(os.getenv("SLS_LAMBDA_PREFIX"))
print(lambda_function_name)

# Run the Lambda command
Expand Down
8 changes: 4 additions & 4 deletions backend/src/xfd_django/xfd_api/api_methods/scan_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ def list_scan_tasks(search_data: Optional[ScanTaskSearch], current_user):

# Determine the correct ordering based on the 'order' field
ordering_field = (
f"-{search_data.sort}"
"-{}".format(search_data.sort)
if search_data.order and search_data.order.upper() == "DESC"
else search_data.sort
else "{}".format(search_data.sort)
)

# Construct query based on filters
Expand Down Expand Up @@ -71,7 +71,7 @@ def list_scan_tasks(search_data: Optional[ScanTaskSearch], current_user):
for task in qs:
# Ensure scan is not None before accessing its properties
if task.scan is None:
print(f"Warning: ScanTask {task.id} has no scan associated.")
print("Warning: ScanTask {} has no scan associated.".format(task.id))
scan_data = None
else:
scan_data = {
Expand Down Expand Up @@ -177,7 +177,7 @@ def kill_scan_task(scan_task_id, current_user):
utc_now = datetime.now(timezone.utc)
scan_task.status = "failed"
scan_task.finishedAt = utc_now
scan_task.output = f"Manually stopped at {utc_now.isoformat()}"
scan_task.output = "Manually stopped at {}".format(utc_now.isoformat())
scan_task.save()

return {"statusCode": 200, "message": "ScanTask successfully marked as failed."}
Expand Down
10 changes: 5 additions & 5 deletions backend/src/xfd_django/xfd_api/api_methods/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ async def fetch_all_results(
try:
response = client.search_domains(request)
except Exception as e:
print(f"Elasticsearch error: {e}")
print("Elasticsearch error: {}".format(e))
raise HTTPException(status_code=500, detail="Error querying Elasticsearch.")

hits = response.get("hits", {}).get("hits", [])
Expand Down Expand Up @@ -97,9 +97,9 @@ def process_results(results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
if "name" in product:
product_name = product["name"].lower()
product_version = product.get("version", "")
products[
product_name
] = f"{product['name']} {product_version}".strip()
products[product_name] = "{} {}".format(
product["name"], product_version
).strip()

res["products"] = ", ".join(products.values())
processed_results.append(res)
Expand Down Expand Up @@ -204,7 +204,7 @@ async def search_export(search_body: DomainSearchBody, current_user) -> Dict[str
try:
csv_url = s3_client.save_csv(csv_content, "domains")
except Exception as e:
print(f"S3 upload error: {e}")
print("S3 upload error: {}".format(e))
raise HTTPException(status_code=500, detail="Error uploading CSV to S3.")

return {"url": csv_url}
55 changes: 36 additions & 19 deletions backend/src/xfd_django/xfd_api/api_methods/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async def safe_fetch(fetch_fn, *args, **kwargs):
try:
return await fetch_fn(*args, **kwargs)
except Exception as e:
print(f"Error fetching stats with {fetch_fn.__name__}: {e}")
print("Error fetching stats with {}: {}".format(fetch_fn.__name__, e))
return []

filtered_org_ids = get_stats_org_ids(current_user, filter_data)
Expand Down Expand Up @@ -98,7 +98,7 @@ async def safe_fetch(fetch_fn, *args, **kwargs):
}
except Exception as e:
raise HTTPException(
status_code=500, detail=f"An unexpected error occurred: {e}"
status_code=500, detail="An unexpected error occurred: {}".format(e)
)


Expand Down Expand Up @@ -130,11 +130,13 @@ async def get_user_services_count(
return services_data

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500, detail=f"An unexpected error occurred: {e}"
status_code=500, detail="An unexpected error occurred: {}".format(e)
)


Expand Down Expand Up @@ -166,11 +168,13 @@ async def get_user_ports_count(
return ports_data

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500, detail=f"An unexpected error occurred: {e}"
status_code=500, detail="An unexpected error occurred: {}".format(e)
)


Expand Down Expand Up @@ -200,11 +204,13 @@ async def get_num_vulns(filter_data, current_user, redis_client, filtered_org_id
return num_vulns_data

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500, detail=f"An unexpected error occurred: {e}"
status_code=500, detail="An unexpected error occurred: {}".format(e)
)


Expand Down Expand Up @@ -236,11 +242,13 @@ async def get_severity_stats(
return severity_data

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500, detail=f"An unexpected error occurred: {e}"
status_code=500, detail="An unexpected error occurred: {}".format(e)
)


Expand All @@ -265,7 +273,9 @@ async def stats_latest_vulns(
)

# Generate all Redis keys at once
redis_keys = [f"latest_vulnerabilities:{org_id}" for org_id in filtered_org_ids]
redis_keys = [
"latest_vulnerabilities:{}".format(org_id) for org_id in filtered_org_ids
]

# Use MGET to fetch all keys in a single operation
results = await safe_redis_mget(
Expand Down Expand Up @@ -293,12 +303,14 @@ async def stats_latest_vulns(
return vulnerabilities

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500,
detail=f"An unexpected error occurred: {e}",
detail="An unexpected error occurred: {}".format(e),
)


Expand All @@ -324,7 +336,8 @@ async def stats_most_common_vulns(

# Generate all Redis keys at once
redis_keys = [
f"most_common_vulnerabilities:{org_id}" for org_id in filtered_org_ids
"most_common_vulnerabilities:{}".format(org_id)
for org_id in filtered_org_ids
]

# Use MGET to fetch all keys in a single operation
Expand All @@ -347,12 +360,14 @@ async def stats_most_common_vulns(
return vulnerabilities

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500,
detail=f"An unexpected error occurred: {e}",
detail="An unexpected error occurred: {}".format(e),
)


Expand All @@ -376,7 +391,7 @@ async def get_by_org_stats(

# Fetch data from Redis for each organization ID
for org_id in filtered_org_ids:
redis_key = f"by_org_stats:{org_id}"
redis_key = "by_org_stats:{}".format(org_id)
org_stats = await redis_client.get(redis_key)
if org_stats:
by_org_data.append(
Expand All @@ -392,10 +407,12 @@ async def get_by_org_stats(
return by_org_data

except aioredis.RedisError as redis_error:
raise HTTPException(status_code=500, detail=f"Redis error: {redis_error}")
raise HTTPException(
status_code=500, detail="Redis error: {}".format(redis_error)
)

except Exception as e:
raise HTTPException(
status_code=500,
detail=f"An unexpected error occurred: {e}",
detail="An unexpected error occurred: {}".format(e),
)
Loading
Loading