db.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from pymongo import MongoClient,errors
  2. from bson.objectid import ObjectId
  3. import re
  4. class db():
  5. DB="alexis"
  6. def __init__(self):
  7. self.client = MongoClient('localhost', 27017)
  8. self.c_sources=self.client[self.DB]["sources"]
  9. self.c_articles=self.client[self.DB]["articles"]
  10. def jsonable(self, el):
  11. if el is None or "_id" not in el:
  12. return el
  13. el["_id"]=str(el["_id"])
  14. return el
  15. def articles(self, id=None):
  16. if id is None:
  17. return [ self.jsonable(p) for p in self.c_articles.find() ]
  18. ret=self.c_articles.find_one({"_id":ObjectId(id)})
  19. return self.jsonable(ret)
  20. def sources(self,id=None):
  21. if id is None:
  22. return [ self.jsonable(p) for p in self.c_sources.find() ]
  23. ret=self.c_sources.find_one({"_id":ObjectId(id)})
  24. return self.jsonable(ret)
  25. def rss_sources(self):
  26. return [ p for p in self.c_sources.find({"rss":1}) ]
  27. def insert_article(self,o):
  28. try:
  29. self.c_articles.insert_one(o)
  30. return True
  31. except errors.DuplicateKeyError:
  32. print("Dup")
  33. return False
  34. def article_exists(self,url):
  35. ret=self.c_articles.find_one({'url':url})
  36. if ret is None:
  37. return False
  38. return True
  39. def lower_arr(self,arr):
  40. return [a.lower() for a in arr]
  41. def get_keywords(self,category):
  42. kw=self.client[self.DB]["keywords"]
  43. #FIXME, split on "|" or regex
  44. ret = [ {"weight":k["weight"],
  45. "kw": k["keyword"],
  46. "pattern": self.lower_arr(k["keyword"].split("|")) } for k in kw.find({}) ]#FIXME, categories
  47. return ret