I am able to get the data from my sqlite3 database and project it in a webpage in Json but am having trouble replicating that when wanting to create a file. I am new to python, Django and working with databases. I have been looking around and tried several pieces of code, but the information I could find pertained to what I have already achieved, which is displaying the data on a webpage.
import json
import os
json_utils.py
def get_ip_list_json() -> dict:
# Initialize the JSON response with a version, description, and a default object
json_response = {
"version": "",
"description": "",
"objects": [
{
"name": "",
"id": "",
"description": "",
"ranges": ["2.2.2.2"],
},
],
}
# Dictionary to map group IDs to their details and IP ranges
group_map = {}
# Query the BlockedList for active IPs (end_date is null or in the future)
for ip in BlockedList.objects.filter(
Q(end_date__isnull=True) | Q(end_date__gte=timezone.now())
).select_related("group"):
group_id = str(ip.group.id)
# If the group is not already in the map, add it
if group_id not in group_map:
group_map[group_id] = {
"name": ip.group.name,
"id": ip.group.group_id,
"description": ip.group.description,
"ranges": [],
}
# Append the IP address to the group's ranges
group_map[group_id]["ranges"].append(ip.address)
# Convert the group map to a list of objects for the JSON response
json_response["objects"] = list(group_map.values())
return json_response
Edit: This is how you would go about answering this.
def create_ip_file():
try:
base_dir_json = ""
filename = ""
full_path_json = os.path.join(base_dir_json, filename)
# Create the JSON file using the get_ip_list_json function
with open(full_path_json, "w") as f:
json_data = get_ip_list_json()
f.write(json.dumps(json_data, indent=4))
You already have your JSONable data in json_response
, so all that's left to do is to write that to a file. Since you can't quite rely on the working directory of your server to be correct, I would recommend specifying a directory for those dumps explicitly in your settings, and using it.
from django.conf import settings
import json
import time
# ...
dump_path = os.path.join(settings.DUMPS_DIRECTORY, f"dump-{int(time.time())}.json")
with open(dump_path, "w") as fp:
json.dump(json_response, fp)
return JsonResponse({"message": f"ok, saved {dump_path}"})
On the other hand, if you want to tell send the data to the user but tell the user's browser that it should handle this as a file, use the Content-Disposition
header to say so:
filename = f"dump-{int(time.time())}.json"
response = JsonResponse(json_response)
response["Content-Disposition"] = f"attachment; filename={filename}"
return response