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.
This is how I currently use my views.py file to display the data on a webpage.
import json
from django.utils import timezone
from django.db.models import Q
from django.http import JsonResponse
from django.views import View
from chpapi.models import BlockedList
class IPListJsonView(View):
def get(self, request):
json_response = {
"version": "",
"description": "",
"objects": [
{
"name": "",
"id": "",
"description": "",
"ranges": ["2.2.2.2"],
},
],
}
group_map = {}
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 group_id not in group_map:
group_map[group_id] = {
"name": ip.group.name,
"id": ip.group.group_id,
"description": ip.group.description,
"ranges": [],
}
group_map[group_id]["ranges"].append(ip.address)
json_response["objects"] = list(group_map.values())
return JsonResponse(json_response)
The above code does produce what I want, I have to leave out some objects, but basically the four columns I am grabbing from my models.py are the name, group_id, description and ranges which is an IP value which has its own definition as Django GenericIPAddress did not support certain attributes I wanted.
I thought a simple fix in terms of generating a file as well (This is for safety reasons; in case the database or backup could get corrupted) would be as simple as inserting this code below.
data = JsonResponse
with open('test_data.json', 'w') as fp:
json.dump(data, fp, indent=4)
What ends up happening is that I get a file produced, but it is empty, I am thinking I will have to write a new class in the views for writing a file. If possible if someone has any articles or even a solution in terms of extracting columns in the Sqlite3 database and writing it to a file in the json format that would be helpful. Or if it is possible to include the production of a file in the same views class.
Please let me know if I did not include enough information to go off of and I will edit and improve this post.
Steve-o is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.