| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- # -*- coding: UTF-8 -*-
- from datetime import datetime
- from odoo import models, fields, _
- from pymongo import MongoClient
- from odoo.exceptions import UserError
- class SyncNewsData(models.TransientModel):
- _name = 'auto.news.sync'
- _description = 'Auto News Sync'
- message = fields.Text('Message', default='确认同步数据?', readonly=True)
- def btn_sync_data(self):
- try:
- client = MongoClient('mongodb://root:aaaAAA111!!!@erhe.top:38000/')
- # 指定数据库名称
- db_name = 'NEWS' # 替换为你的数据库名称
- # 选择数据库
- db = client[db_name]
- # 列出数据库中的所有集合
- collections = db.list_collection_names()
- except Exception as e:
- raise UserError('连接数据库失败: {}'.format(e))
- all_data = []
- for collection_name in collections:
- # 选择集合
- collection = db[collection_name]
- # 读取集合中的所有数据
- for document in collection.find({}, {'_id': 0}):
- all_data.append(document)
- sorted_data = []
- if all_data:
- sorted_data = sorted(all_data, key=lambda x: x['create_time'], reverse=True)
- for doc in sorted_data:
- news_data_id = self.env['news.info'].search([('name', '=', doc['title'])], limit=1)
- if news_data_id:
- continue
- create_time_dt = None
- if doc.get('create_time'):
- create_time_dt = datetime.utcfromtimestamp(doc['create_time'])
- news_data = news_data_id.create({
- 'name': doc.get('title'),
- 'context': doc.get('context') or '',
- 'source_url': doc.get('source_url') or '',
- 'link': doc.get('line') or '',
- 'article_type': doc.get('article_type') or '',
- 'article_source': doc.get('article_source') or '',
- 'img_url': doc.get('img_url') or '',
- 'keyword': doc.get('keyword') or '',
- 'posted_date': doc.get('posted_date') or '',
- 'create_time_ts': doc.get('create_time') or '',
- 'create_time': create_time_dt,
- 'create_datetime': datetime.strptime(doc['create_datetime'], '%Y-%m-%d %H:%M:%S')
- })
|