2
0

wizard_sync_news_data.py 2.3 KB

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