There are several issues with your current approach. Here's how to fix them:
Main Issues:
- You're opening the file in write mode (
'w') but trying to read from it with json.load()
- You're accessing
artykul.url as an attribute, but it's a dictionary key
- You need to write the data back to the file
Corrected Function:
import json
from datetime import datetime
def dodajAdresArtykulu(urlArtykulu):
# First, try to read existing data
try:
with open(SPIS_ARTYKULOW, 'r') as sp:
spisArtykulow = json.load(sp)
except (FileNotFoundError, json.JSONDecodeError):
# File doesn't exist or is empty/invalid
spisArtykulow = []
# Check if article already exists
artykulIstnieje = False
for artykul in spisArtykulow:
if artykul["url"] == urlArtykulu: # Use dictionary key, not attribute
artykulIstnieje = True
break
if not artykulIstnieje:
logger.debug(f"Dadaję nowy adres do bazy ({urlArtykulu})")
# Create new article entry
nowy_artykul = {
"url": urlArtykulu,
"index_timestamp": datetime.now().isoformat(),
"title": "",
"text": "",
"date": "",
"tags": ""
}
spisArtykulow.append(nowy_artykul)
# Write back to file
with open(SPIS_ARTYKULOW, 'w') as sp:
json.dump(spisArtykulow, sp, indent=2)
else:
logger.debug(f"Adres już w bazie ({urlArtykulu})")
Alternative Approach Using a Class:
If you prefer using a constructor pattern:
import json
from datetime import datetime
class Artykul:
def __init__(self, url, title="", text="", date="", tags=""):
self.url = url
self.index_timestamp = datetime.now().isoformat()
self.title = title
self.text = text
self.date = date
self.tags = tags
def to_dict(self):
return {
"url": self.url,
"index_timestamp": self.index_timestamp,
"title": self.title,
"text": self.text,
"date": self.date,
"tags": self.tags
}
def dodajAdresArtykulu(urlArtykulu):
try:
with open(SPIS_ARTYKULOW, 'r') as sp:
spisArtykulow = json.load(sp)
except (FileNotFoundError, json.JSONDecodeError):
spisArtykulow = []
# Check if exists
if not any(artykul["url"] == urlArtykulu for artykul in spisArtykulow):
logger.debug(f"Dadaję nowy adres do bazy ({urlArtykulu})")
nowy_artykul = Artykul(urlArtykulu)
spisArtykulow.append(nowy_artykul.to_dict())
with open(SPIS_ARTYKULOW, 'w') as sp:
json.dump(spisArtykulow, sp, indent=2)
else:
logger.debug(f"Adres już w bazie ({urlArtykulu})")
Recommendation:
For your use case, I'd recommend the first approach (raw dictionaries) since it's simpler and you're already working with JSON data. The class approach adds complexity without much benefit unless you need methods to manipulate the article data.