~akretion-team/openobject-extension/openobject-extension-abstract-automatic-task

« back to all changes in this revision

Viewing changes to base_file_protocole/base_file_protocole.py

  • Committer: Sébastien Beau
  • Date: 2012-12-07 13:12:37 UTC
  • mfrom: (376.1.35 openobject-extension)
  • Revision ID: sebastien.beau@akretion.com-20121207131237-1u9znrzxdcc161ha
[MERGE] merge from cleanning branch : please do not forget to start an update on the module updated.
base_external_referential :
    REFACTOR
        - redesign the view and for commun fields between various e-commerce the visibility can be set withthe variable REF_VISIBLE_FIELD
        ex : REF_VISIBLE_FIELDS['Magento'] = ['location', 'apiusername', 'apipass']

    FIX
        - fix copy method on mapping
        - fix export resource when ids an empty tuple or an empty list
        - increase the size of the field action on the report line to avoid error
        - FIX Call the onchange correctly using args and kwargs

    ADD
        - add the type url in the mapping
        - improve reporting system, avoid the creation of unlimited error message on some object
        - add the posibility to send an email when an error occure


file_exchange / base_file_protocol:
    ADD
        - add support of xls

base_external_file_protocole 
    REFACTOR
        - improve file.buffer (need for amazon)

report_syncronizer
    REFACTOR
        - refactor the export of file (needed for exporting OpenERP PDf into magento)

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
#                                                                             #
20
20
###############################################################################
21
21
 
22
 
from osv import osv, fields
23
 
import netsvc
24
22
from tempfile import TemporaryFile
25
 
from ftplib import FTP
26
 
import sys
 
23
import ftplib
27
24
import os
28
 
import shutil
29
25
import csv
30
26
import paramiko
31
27
import errno
32
28
import functools
 
29
import logging
 
30
 
 
31
_logger = logging.getLogger(__name__)
 
32
try:
 
33
    import xlrd
 
34
except ImportError:
 
35
    _logger.warning('You must install xlrd, if you need to read xls file')
33
36
 
34
37
def open_and_close_connection(func):
35
38
    """
50
53
    return wrapper
51
54
 
52
55
# Extend paramiko lib with the method mkdirs
53
 
def mkdirs(self, path, mode=511):
 
56
def stfp_mkdirs(self, path, mode=511):
 
57
    current_dir = self.getcwd()
54
58
    try:
55
59
        self.stat(path)
56
60
    except IOError, e:
63
67
                    self.mkdir(path, mode)
64
68
                else:
65
69
                    raise
66
 
paramiko.SFTPClient.mkdirs = mkdirs
 
70
    self.stat(current_dir)
 
71
paramiko.SFTPClient.mkdirs = stfp_mkdirs
 
72
 
 
73
# Extend ftplib with the method mkdirs
 
74
def ftp_mkdirs(self, path):
 
75
    current_dir = self.pwd()
 
76
    try:
 
77
        self.cwd(path)
 
78
    except ftplib.error_perm, e:
 
79
        if "550" in str(e):
 
80
            try:
 
81
                self.mkd(path)
 
82
            except ftplib.error_perm, e:
 
83
                if "550" in str(e):
 
84
                    self.mkdirs(os.path.dirname(path))
 
85
                    self.mkd(path)
 
86
                else:
 
87
                    raise
 
88
    self.cwd(current_dir)
 
89
ftplib.FTP.mkdirs = ftp_mkdirs
67
90
 
68
91
 
69
92
class FileConnection(object):
75
98
        self.protocole = protocole
76
99
        self.allow_dir_creation = allow_dir_creation
77
100
        self.location = location
78
 
        self.home_folder = home_folder
 
101
        self.home_folder = home_folder or '/'
79
102
        self.port = port
80
103
        self.user = user
81
104
        self.pwd = pwd
 
105
        self.connection = None
82
106
 
83
107
 
84
108
    def connect(self):
85
109
        if self.is_('ftp'):
86
 
            self.connection = FTP(self.location)
 
110
            self.connection = ftplib.FTP(self.location)
87
111
            self.connection.login(self.user, self.pwd)
88
112
        elif self.is_('sftp'):
89
113
            transport = paramiko.Transport((self.location, self.port or 22))
91
115
            self.connection = paramiko.SFTPClient.from_transport(transport)
92
116
 
93
117
    def close(self):
94
 
        if self.is_('ftp') or self.is_('sftp'):
 
118
        if self.is_('ftp') or self.is_('sftp') and self.connection is not None:
95
119
            self.connection.close()
96
120
 
97
121
    @open_and_close_connection
98
122
    def send(self, filepath, filename, output_file, create_patch=None):
99
123
        if self.is_('ftp'):
 
124
            filepath = os.path.join(self.home_folder, filepath)
 
125
            if self.allow_dir_creation:
 
126
                self.connection.mkdirs(filepath)
100
127
            self.connection.cwd(filepath)
101
128
            self.connection.storbinary('STOR ' + filename, output_file)
102
129
            output_file.close()
157
184
    which is encoded in the given encoding.
158
185
    """
159
186
 
160
 
    def __init__(self, f, encoding="utf-8", **kwds):            
 
187
    def __init__(self, f, encoding="utf-8", **kwds):
161
188
        self.encoding = encoding
162
189
        self.reader = csv.DictReader(f, **kwds)
163
190
 
177
204
 
178
205
    def reorganize(self, field_structure=None, merge_keys=None, ref_field=None):
179
206
        """
180
 
        Function to reorganize the resource from the csv. It uses the mapping (field_structure) 
 
207
        Function to reorganize the resource from the csv. It uses the mapping (field_structure)
181
208
        to deal with the different architecture of an object (sale order with sale order line ...)
182
209
        the ref_field is used to merge the different lines (sale order with several sale order lines)
183
210
        """
236
263
    def writerows(self, rows):
237
264
        for row in rows:
238
265
            self.writerow(row)
 
266
 
 
267
 
 
268
class FileXlsReader(object):
 
269
 
 
270
    def __init__(self, file_contents):
 
271
        self.file_contents = file_contents
 
272
 
 
273
    def read(self):
 
274
        wb = xlrd.open_workbook(file_contents=self.file_contents)
 
275
        sheet_name = wb.sheet_names()[0]
 
276
        sh = wb.sheet_by_name(sheet_name)
 
277
        header = sh.row_values(0)
 
278
        result = []
 
279
        for rownum in range(1, sh.nrows):
 
280
            row = {}
 
281
            index = 0
 
282
            for val in sh.row_values(rownum):
 
283
                row[header[index]] = val
 
284
                index += 1
 
285
            result.append(row)
 
286
        return result
 
287
 
 
288
 
 
289