forked from zhanghe06/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.py
More file actions
77 lines (64 loc) · 1.86 KB
/
export.py
File metadata and controls
77 lines (64 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# encoding: utf-8
__author__ = 'zhanghe'
import json
import time
import os
class ExportBulk(object):
"""
导出bulk文件工具类
"""
def __init__(self, index_name, type_name, file_name=None):
self._index = index_name
self._type = type_name
if file_name is None:
file_name = 'bulk_%s.bulk' % time.time()
file_path = os.path.dirname(file_name)
if not os.path.isdir(file_path):
os.mkdir(file_path)
self.bulk_fp = open(file_name, 'a')
def write(self, index_id, body):
"""
文件写入
"""
self.bulk_fp.write(json.dumps({"index": {"_index": self._index, '_type': self._type, '_id': index_id}})+"\n")
self.bulk_fp.write(json.dumps(body)+"\n")
def close(self):
"""
关闭文件资源
"""
self.bulk_fp.close()
class ExportFile(object):
"""
导出json/csv文件工具类
"""
def __init__(self, file_name):
if file_name is None:
file_name = 'json_%s.json' % time.time()
file_path = os.path.dirname(file_name)
if not os.path.isdir(file_path):
os.mkdir(file_path)
self.json_fp = open(file_name, 'a')
def write(self, data, file_type='json'):
"""
文件写入
"""
if file_type == 'json':
self.json_fp.write(json.dumps(data).decode('raw_unicode_escape')+"\n")
if file_type == 'csv':
self.json_fp.write(','.join(data)+"\n")
def close(self):
"""
关闭文件资源
"""
self.json_fp.close()
def test_bulk():
"""
测试ExportBulk
"""
export_bulk = ExportBulk('service', 'provider')
test_id = '1'
test_body = {'a': '001', 'b': '002'}
export_bulk.write(test_id, test_body)
export_bulk.close()
if __name__ == '__main__':
test_bulk()