wizard_sync_news_data.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: UTF-8 -*-
  2. from datetime import datetime
  3. from odoo import models, fields, _
  4. from pymongo import MongoClient
  5. class SyncNewsData(models.TransientModel):
  6. _name = 'auto.news.sync'
  7. _description = 'Auto News Sync'
  8. message = fields.Text('Message', default='确认同步数据?', readonly=True)
  9. def btn_sync_data(self):
  10. client = MongoClient('mongodb://root:aaaAAA111!!!@home.erhe.link:38000/')
  11. # 指定数据库名称
  12. db_name = 'NEWS' # 替换为你的数据库名称
  13. # 选择数据库
  14. db = client[db_name]
  15. # 列出数据库中的所有集合
  16. collections = db.list_collection_names()
  17. all_data = []
  18. for collection_name in collections:
  19. # 选择集合
  20. collection = db[collection_name]
  21. # 读取集合中的所有数据
  22. for document in collection.find({}, {'_id': 0}):
  23. all_data.append(document)
  24. sorted_data = []
  25. if all_data:
  26. sorted_data = sorted(all_data, key=lambda x: x['create_time'], reverse=True)
  27. for doc in sorted_data:
  28. news_data_id = self.env['news.info'].search([('name', '=', doc['title'])], limit=1)
  29. if news_data_id:
  30. continue
  31. create_time_dt = None
  32. if doc.get('create_time'):
  33. create_time_dt = datetime.utcfromtimestamp(doc['create_time'])
  34. news_data = news_data_id.create({
  35. 'name': doc.get('title'),
  36. 'context': doc.get('context') or '',
  37. 'source_url': doc.get('source_url') or '',
  38. 'link': doc.get('line') or '',
  39. 'article_type': doc.get('article_type') or '',
  40. 'article_source': doc.get('article_source') or '',
  41. 'img_url': doc.get('img_url') or '',
  42. 'keyword': doc.get('keyword') or '',
  43. 'posted_date': doc.get('posted_date') or '',
  44. 'create_time_ts': doc.get('create_time') or '',
  45. 'create_time': create_time_dt,
  46. 'create_datetime': datetime.strptime(doc['create_datetime'], '%Y-%m-%d %H:%M:%S')
  47. })