Exemplo n.º 1
0
 def output_csv(self, output_dir, model_param_list):
     """csvを出力.
     """
     columns = (
         (u'カラム名(物理名)', lambda field_param:field_param.name),
         (u'型', lambda field_param:field_param.db_type),
         (u'INDEX', lambda field_param:','.join(field_param.indexes)),
         (u'AUTO_INCREMENT', lambda field_param:u'◯' if field_param.auto_increment else u''),
         (u'NULL', lambda field_param:u'◯' if field_param.null else u''),
         (u'デフォルト値', lambda field_param:field_param.default),
         (u'カラム名(論理名)', lambda field_param:field_param.verbose_name),
         (u'補足', lambda field_param:field_param.help_text),
     )
     
     for model_param in model_param_list:
         filepath = os.path.join(output_dir, '{}.csv'.format(model_param.name))
         csv = CSVWriter(filepath)
         csv.add([u'#{}'.format(model_param.name)])
         csv.add([u'#{}'.format(StrUtil.to_u(model_param.description))])
         csv.add([column_name for column_name, _ in columns])
         
         for field in model_param.fields:
             csv.add([column_value_gettr(field) for _, column_value_gettr in columns])
         csv.output()
         print 'write...{}'.format(filepath)
     
     print 'Output csv...{}'.format(filepath)
Exemplo n.º 2
0
    def __proc_load_csv(self):
        if self.request.method == 'POST':
            fixture = None
            tmp_data = None
            if settings_sub.IS_LOCAL:
                # ローカルだとアップできないので..
                f = None
                try:
                    f = open(self.__local_datafileurl, 'r')
                    tmp_data = f.read()
                except IOError:
                    tmp_data = None
                finally:
                    if f:
                        f.close()
            else:
                request_files = self.request.files
                form = UploadFileForm(self.request.body, request_files)
                if form.is_valid():
                    req_file = request_files['data_file']
                    csv_name = self.__get_csv_name()
                    if req_file.name != csv_name:
                        url = self.makeModelEditLinkUrl()
                        url = self.setAlert(
                            url, u'ファイル名が不正です.正しいファイル名は%sです.' % csv_name,
                            AlertCode.ERROR)
                        self.redirect(url)
                        return
                    tmp_data = req_file.read()
            if tmp_data:
                src_enc = StrUtil.guess_charset(tmp_data)
                fixture = io.StringIO(StrUtil.to_u(tmp_data, src_enc),
                                      newline=None)

            sheet_columns = AdminModelEditHandler.__make_sheet_columns(
                self.model_form_cls)
            pkey_name = self.model_cls.get_primarykey_column()
            sheet_pkey_name = pkey_name.replace('_', '')

            model_all = self.model_cls.fetchValues(using=settings.DB_DEFAULT)
            model_dict = {}
            for model in model_all:
                model_dict[model.key()] = model

            save_models = []

            if fixture:
                cnt = 0
                indexes = {}
                for row in csv.reader(fixture):
                    if cnt == 0:
                        # ここはカラム名.
                        index = 0
                        for column_name in row:
                            indexes[column_name] = index
                            index += 1
                    else:
                        # ここは値.
                        pkey = row[indexes.get(sheet_pkey_name, 0)]
                        model = model_dict.get(
                            pkey, self.model_cls(**{pkey_name: pkey}))
                        field_dict = dict([
                            (field.attname, field)
                            for field in self.model_cls.get_fields()
                        ])
                        for column in self.get_formfields():
                            sheet_column = column.replace('_', '')
                            if not sheet_column in sheet_columns:
                                continue
                            field = field_dict.get(
                                column
                            ) or self.model_form_cls.declared_fields.get(
                                column)

                            index = indexes.get(sheet_column, None)
                            if index is not None:
                                str_v = row[index]
                                try:
                                    v = self.str_to_fieldvalue(field, str_v)
                                except Exception, e:
                                    raise CabaretError(
                                        '[field=%s,value=%s,row=%s,data=%s]%s:%s'
                                        % (column, str_v, cnt, row,
                                           e.__class__.__name__, e))
                            else:
                                # modelにはあるが実際のシートに無い場合.
                                v = getattr(model, column, None)
                                if v is None:
                                    raise CabaretError(
                                        u'dataError:[field=%s,pkey=%s,data=%s]'
                                        % (column, pkey, row))
                            if hasattr(model, 'set_%s' % column):
                                getattr(model, 'set_%s' % column)(v)
                            else:
                                setattr(model, column, v)
                        save_models.append(model)
                    cnt += 1
            url = self.__write_instances(save_models)
            if not url:
                url = self.makeModelEditLinkUrl()
                url = self.setAlert(url, u'データがありません', AlertCode.ERROR)
            self.redirect(url)