db.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from pymongo import MongoClient,errors
  2. from bson.objectid import ObjectId
  3. class db():
  4. def __init__(self):
  5. self.client = MongoClient('localhost', 27017)
  6. self.c_sources=self.client.alexis["sources"]
  7. self.c_articles=self.client.alexis["articles"]
  8. def jsonable(self, el):
  9. if el is None or "_id" not in el:
  10. return el
  11. el["_id"]=str(el["_id"])
  12. return el
  13. def articles(self, id=None):
  14. if id is None:
  15. return [ self.jsonable(p) for p in self.c_articles.find() ]
  16. ret=self.c_articles.find_one({"_id":ObjectId(id)})
  17. return self.jsonable(ret)
  18. def sources(self,id=None):
  19. if id is None:
  20. return [ self.jsonable(p) for p in self.c_sources.find() ]
  21. ret=self.c_sources.find_one({"_id":ObjectId(id)})
  22. return self.jsonable(ret)
  23. def rss_sources(self):
  24. return [ p for p in self.c_sources.find({"rss":1}) ]
  25. def insert_article(self,o):
  26. try:
  27. self.c_articles.insert_one(o)
  28. return True
  29. except errors.DuplicateKeyError:
  30. print("Dup")
  31. return False
  32. def article_exists(self,url):
  33. ret=self.c_articles.find_one({'url':url})
  34. if ret is None:
  35. return False
  36. return True