diff --git a/CHANGELOG b/CHANGELOG index 382c4dfd30..e0bced7c31 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,4 @@ +* Refactoring by validation with pylint * Modify ondelete attribute of Many2One according to required attribute value * Refactor import_data of ModelStorage * Raise exception when search function is missing on Function fields diff --git a/bin/trytond b/bin/trytond index 3baa30d7ac..1673bba703 100755 --- a/bin/trytond +++ b/bin/trytond @@ -1,7 +1,8 @@ #!/usr/bin/env python #This file is part of Tryton. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. -import sys, os +import sys +import os DIR = os.path.abspath(os.path.normpath(os.path.join(__file__, '..', '..', 'trytond'))) if os.path.isdir(DIR): @@ -11,7 +12,6 @@ if '--profile' in sys.argv: import profile import pstats import tempfile - import os sys.argv.remove('--profile') statfile = tempfile.mkstemp(".stat","trytond-")[1] diff --git a/trytond/backend/fields.py b/trytond/backend/fields.py index 1936905a99..9176c5b5ed 100644 --- a/trytond/backend/fields.py +++ b/trytond/backend/fields.py @@ -23,7 +23,7 @@ class Field(object): @staticmethod def sql_type(field): - return None + raise NotImplementedError class Boolean(Field): diff --git a/trytond/backend/postgresql/database.py b/trytond/backend/postgresql/database.py index 7be319b01f..f9d7cc9a7a 100644 --- a/trytond/backend/postgresql/database.py +++ b/trytond/backend/postgresql/database.py @@ -5,7 +5,7 @@ from trytond.backend.database import DatabaseInterface, CursorInterface from trytond.config import CONFIG from trytond.session import Session from psycopg2.pool import ThreadedConnectionPool -from psycopg2.extensions import cursor +from psycopg2.extensions import cursor as PsycopgCursor from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from psycopg2.extensions import register_type, register_adapter @@ -238,7 +238,7 @@ class Database(DatabaseInterface): (0, module_id, dependency)) -class _Cursor(cursor): +class _Cursor(PsycopgCursor): def __build_dict(self, row): return dict((desc[0], row[i]) diff --git a/trytond/backend/postgresql/table.py b/trytond/backend/postgresql/table.py index a2dbdc7433..f435e79ee1 100644 --- a/trytond/backend/postgresql/table.py +++ b/trytond/backend/postgresql/table.py @@ -2,7 +2,6 @@ #this repository contains the full copyright notices and license terms. from trytond.backend.table import TableHandlerInterface -from trytond.backend.postgresql.fields import FIELDS import logging @@ -25,8 +24,8 @@ class TableHandler(TableHandlerInterface): if not self.table_exist(self.cursor, self.table_name): self.cursor.execute('CREATE TABLE "%s" ()' % self.table_name) - self.cursor.execute('COMMENT ON TABLE "%s" IS \'%s\'' % (self.table_name, - model._description.replace("'", "''"))) + self.cursor.execute('COMMENT ON TABLE "%s" IS \'%s\'' % + (self.table_name, model._description.replace("'", "''"))) self._update_definitions() if 'id' not in self._columns: @@ -140,9 +139,10 @@ class TableHandler(TableHandlerInterface): self.cursor.execute("SELECT co.contype, co.confdeltype, at.attname, "\ "cl2.relname, co.conname "\ "FROM pg_constraint co "\ - "LEFT JOIN pg_class cl on (co.conrelid = cl.oid) "\ - "LEFT JOIN pg_class cl2 on (co.confrelid = cl2.oid) "\ - "LEFT JOIN pg_attribute at on (co.conkey[1] = at.attnum) "\ + "LEFT JOIN pg_class cl ON (co.conrelid = cl.oid) "\ + "LEFT JOIN pg_class cl2 ON (co.confrelid = cl2.oid) "\ + "LEFT JOIN pg_attribute at ON " \ + "(co.conkey[1] = at.attnum) "\ "WHERE cl.relname = %s AND at.attrelid = cl.oid", (self.table_name,)) self._constraints = [] @@ -237,7 +237,6 @@ class TableHandler(TableHandlerInterface): if field_size == None: if self._columns[column_name]['size'] > 0: self.alter_size(column_name, base_type) - pass elif self._columns[column_name]['size'] == field_size: pass elif self._columns[column_name]['size'] > 0 and \ @@ -318,7 +317,7 @@ class TableHandler(TableHandlerInterface): return self.cursor.execute('CREATE INDEX "' + index_name + '" ' \ 'ON "' + self.table_name + '" ( ' + \ - ','.join(['"' + x + '"' for x in column_name]) + \ + ','.join(['"' + x + '"' for x in column_name]) +\ ')') self._update_definitions() elif action == 'remove': @@ -354,9 +353,11 @@ class TableHandler(TableHandlerInterface): 'of table %s not null !\n'\ 'Try to re-run: ' \ 'trytond.py --update=module\n' \ - 'If it doesn\'t work, update records and execute manually:\n' \ - 'ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % \ - (column_name, self.table_name, self.table_name, column_name)) + 'If it doesn\'t work, update records ' \ + 'and execute manually:\n' \ + 'ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % + (column_name, self.table_name, self.table_name, + column_name)) elif action == 'remove': if not self._columns[column_name]['notnull']: return @@ -424,7 +425,7 @@ class TableHandler(TableHandlerInterface): self._update_definitions() @staticmethod - def dropTable(cursor, model, table, cascade=False): + def drop_table(cursor, model, table, cascade=False): cursor.execute('DELETE from ir_model_data where '\ 'model = \'%s\'' % model) diff --git a/trytond/backend/sqlite/database.py b/trytond/backend/sqlite/database.py index 6d11388fe3..73e8a1d1e6 100644 --- a/trytond/backend/sqlite/database.py +++ b/trytond/backend/sqlite/database.py @@ -4,7 +4,6 @@ from trytond.backend.database import DatabaseInterface, CursorInterface from trytond.config import CONFIG from trytond.session import Session -import logging import os import re from decimal import Decimal @@ -180,12 +179,12 @@ class Database(DatabaseInterface): @staticmethod def list(cursor): res = [] - for file in os.listdir(CONFIG['data_path']) + [':memory:']: - if file.endswith('.sqlite') or file == ':memory:': - if file == ':memory:': + for db_file in os.listdir(CONFIG['data_path']) + [':memory:']: + if db_file.endswith('.sqlite') or db_file == ':memory:': + if db_file == ':memory:': db_name = ':memory:' else: - db_name = file[:-7] + db_name = db_file[:-7] try: database = Database(db_name) except: @@ -270,12 +269,12 @@ class Cursor(CursorInterface): def execute(self, sql, params=None): buf = "" - for nq, q in QUOTE_SEPARATION.findall(sql+"''"): - nq = nq.replace('?', '??') - nq = nq.replace('%s', '?') - nq = nq.replace('ilike', 'like') - nq = re.sub(EXTRACT_PATTERN, r'EXTRACT("\1",', nq) - buf += nq + q + for nquote, quote in QUOTE_SEPARATION.findall(sql+"''"): + nquote = nquote.replace('?', '??') + nquote = nquote.replace('%s', '?') + nquote = nquote.replace('ilike', 'like') + nquote = re.sub(EXTRACT_PATTERN, r'EXTRACT("\1",', nquote) + buf += nquote + quote sql = buf[:-2] try: if params: @@ -345,8 +344,8 @@ class Cursor(CursorInterface): return select sqlite.register_converter('NUMERIC', lambda val: Decimal(str(val))) -sqlite.register_adapter(Decimal, lambda val: float(val)) -sqlite.register_adapter(Session, lambda val: int(val)) +sqlite.register_adapter(Decimal, float) +sqlite.register_adapter(Session, int) def adapt_datetime(val): return val.replace(tzinfo=None).isoformat(" ") sqlite.register_adapter(datetime.datetime, adapt_datetime) diff --git a/trytond/backend/sqlite/table.py b/trytond/backend/sqlite/table.py index 75c1aa8700..d90734b644 100644 --- a/trytond/backend/sqlite/table.py +++ b/trytond/backend/sqlite/table.py @@ -2,7 +2,6 @@ #this repository contains the full copyright notices and license terms. from trytond.backend.table import TableHandlerInterface -from trytond.backend.sqlite.fields import FIELDS import logging import re @@ -160,7 +159,6 @@ class TableHandler(TableHandlerInterface): if field_size == None: if self._columns[column_name]['size'] > 0: self.alter_size(column_name, base_type) - pass elif self._columns[column_name]['size'] == field_size: pass elif self._columns[column_name]['size'] > 0 and \ @@ -268,7 +266,7 @@ class TableHandler(TableHandlerInterface): (column_name, self.table_name)) @staticmethod - def dropTable(cursor, model, table, cascade=False): + def drop_table(cursor, model, table, cascade=False): cursor.execute('DELETE from ir_model_data where '\ 'model = \'%s\'' % model) diff --git a/trytond/backend/table.py b/trytond/backend/table.py index 07a247535d..9bc2e9db78 100644 --- a/trytond/backend/table.py +++ b/trytond/backend/table.py @@ -206,7 +206,7 @@ class TableHandlerInterface(object): raise @staticmethod - def dropTable(cursor, model, table, cascade=False): + def drop_table(cursor, model, table, cascade=False): ''' Remove a table and clean ir_model_data from the given model. diff --git a/trytond/config.py b/trytond/config.py index e23eea54a4..a70beefb57 100644 --- a/trytond/config.py +++ b/trytond/config.py @@ -1,7 +1,7 @@ #This file is part of Tryton. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. import ConfigParser, optparse, os, sys -from version import VERSION +from trytond.version import VERSION class ConfigManager(object): @@ -52,6 +52,7 @@ class ConfigManager(object): 'init': {}, 'update': {}, } + self.configfile = None def parse(self): parser = optparse.OptionParser(version=VERSION) @@ -75,7 +76,7 @@ class ConfigManager(object): parser.add_option("--logfile", dest="logfile", help="file where the server log will be stored") - (opt, args) = parser.parse_args() + (opt, _) = parser.parse_args() if opt.config: self.configfile = opt.config diff --git a/trytond/model/browse.py b/trytond/model/browse.py index c608122141..01ce6384ee 100644 --- a/trytond/model/browse.py +++ b/trytond/model/browse.py @@ -16,7 +16,7 @@ class BrowseRecordList(list): res = [] for record in self: res2 = {} - for field_name, field in record._model._columns.iteritems(): + for field_name, _ in record._model._columns.iteritems(): if not isinstance(record[field_name], BrowseRecordList): res2[field_name] = record.get_eval(field_name) res.append(res2) @@ -68,7 +68,7 @@ class BrowseRecord(object): self._data[record_id] = {'id': record_id} self._cache = cache if local_cache is None: - local_cache ={} + local_cache = {} self._local_cache = local_cache self._local_cache.setdefault(model._name, {}) self._local_cache.setdefault('_language_cache', {}) @@ -145,8 +145,8 @@ class BrowseRecord(object): for data in datas: for i, j in ffields: model = None - if hasattr(j, 'model_name') \ - and j.model_name in self._model.pool.object_name_list(): + if hasattr(j, 'model_name') and \ + j.model_name in self._model.pool.object_name_list(): model = self._model.pool.get(j.model_name) elif hasattr(j, 'get_target'): model = j.get_target(self._model.pool) @@ -156,12 +156,13 @@ class BrowseRecord(object): data[i] = BrowseRecordNull() else: ctx = self._context - if hasattr(j, 'datetime_field') and j.datetime_field: + if hasattr(j, 'datetime_field') and \ + j.datetime_field: ctx = self._context.copy() ctx['_datetime'] = data[j.datetime_field] data[i] = BrowseRecord(self._cursor, self._user, - data[i], model, local_cache=self._local_cache, - context=ctx) + data[i], model, + local_cache=self._local_cache, context=ctx) elif model and j._type in ('one2many', 'many2many') \ and len(data[i]): ctx = self._context diff --git a/trytond/model/cacheable.py b/trytond/model/cacheable.py index ca9c75c150..12fa9aa079 100644 --- a/trytond/model/cacheable.py +++ b/trytond/model/cacheable.py @@ -6,6 +6,7 @@ import time class Cacheable(object): + _name = None def __init__(self): super(Cacheable, self).__init__() diff --git a/trytond/model/fields/binary.py b/trytond/model/fields/binary.py index 2cfc29d256..5aaaa3e314 100644 --- a/trytond/model/fields/binary.py +++ b/trytond/model/fields/binary.py @@ -10,7 +10,8 @@ class Binary(Field): ''' _type = 'binary' - def get(self, cursor, user, ids, model, name, values=None, context=None): + @staticmethod + def get(cursor, user, ids, model, name, values=None, context=None): ''' Convert the binary value into ``str`` diff --git a/trytond/model/fields/property.py b/trytond/model/fields/property.py index 95e3bd6692..c624d25751 100644 --- a/trytond/model/fields/property.py +++ b/trytond/model/fields/property.py @@ -13,9 +13,10 @@ class Property(Function): def __init__(self, type='float', model_name=None, selection=None, digits=None, relation=None, add_remove=None, string='', help='', - required=False, readonly=False, domain=None, states=None, priority=0, - change_default=False, translate=False, select=0, on_change=None, - on_change_with=None, depends=None, order_field=None, context=None): + required=False, readonly=False, domain=None, states=None, + priority=0, change_default=False, translate=False, select=0, + on_change=None, on_change_with=None, depends=None, + order_field=None, context=None): ''' :param type: The type of the field. :param fnct_search: The name of the search function. @@ -69,8 +70,8 @@ class Property(Function): ''' property_obj = model.pool.get('ir.property') return property_obj.set(cursor, user, name, model._name, record_id, - (value and (self.model_name or '') + ',' + str(value)) or False, - context=context) + (value and (self.model_name or '') + ',' + str(value)) or + False, context=context) def search(self, cursor, user, model, name, args, context=None): @@ -106,16 +107,21 @@ class Property(Function): #Fetch res ids that comply with the domain cursor.execute( - 'SELECT cast(split_part("' + property_obj._table + '".res,\',\',2) as integer), ' + \ + 'SELECT CAST(' \ + 'SPLIT_PART("' + property_obj._table + '".res,\',\',2) ' \ + 'AS INTEGER), '\ '"' + property_obj._table + '".id '\ 'FROM "' + property_obj._table + '" '\ - 'JOIN "' + field_obj._table + '" on ("' + field_obj._table + '"'+ \ - '.id = "' + property_obj._table + '".field) '\ - 'JOIN "' + model_obj._table +'" on ("' + model_obj._table + \ - '".id = "' + field_obj._table + '".model) '\ + 'JOIN "' + field_obj._table + '" ON ' \ + '("' + field_obj._table + '"'+ \ + '.id = "' + property_obj._table + '".field) '\ + 'JOIN "' + model_obj._table +'" ON ' \ + '("' + model_obj._table + \ + '".id = "' + field_obj._table + '".model) '\ 'WHERE '\ 'CASE WHEN "' +\ - model_obj._table + '".model = %s AND "' + field_obj._table + '".name = %s AND ' \ + model_obj._table + '".model = %s ' \ + 'AND "' + field_obj._table + '".name = %s AND ' \ + property_query + \ ' THEN ' + \ conditions + \ @@ -126,9 +132,9 @@ class Property(Function): props = cursor.fetchall() default = None - for x in props: - if not x[0]: - default = x[1] + for prop in props: + if not prop[0]: + default = prop[1] break if not default: diff --git a/trytond/model/model.py b/trytond/model/model.py index c11be55784..3361928f0a 100644 --- a/trytond/model/model.py +++ b/trytond/model/model.py @@ -3,7 +3,7 @@ from trytond.model import fields from trytond.pool import Pool -from trytond.pyson import PYSONEncoder, CONTEXT +from trytond.pyson import PYSONEncoder import copy @@ -20,6 +20,9 @@ class Model(object): :_error_messages: a dictionary mapping keywords to an error message. Eg.: ``{'recursive_categories': 'You can not create recursive categories!'}`` + :_rec_name: The name of the main field of the model. + By default the field ``name``. + :id: An Integer field for unique identifier. """ _name = None _inherits = {} @@ -28,6 +31,9 @@ class Model(object): __columns = None __xxx2many_targets = None __defaults = None + _rec_name = 'name' + + id = fields.Integer('ID', readonly=True) def _reset_columns(self): self.__columns = None @@ -245,9 +251,9 @@ class Model(object): 'WHERE f.model = m.id ' \ 'AND m.model = %s ', (self._name,)) - fields = {} + model_fields = {} for field in cursor.dictfetchall(): - fields[field['name']] = field + model_fields[field['name']] = field # Prefetch field translations if self._columns: @@ -278,17 +284,17 @@ class Model(object): relation = field.model_name elif hasattr(field, 'relation_name'): relation = field.relation_name - if field_name not in fields: + if field_name not in model_fields: cursor.execute("INSERT INTO ir_model_field " \ "(model, name, field_description, ttype, " \ "relation, help, module) " \ "VALUES (%s, %s, %s, %s, %s, %s, %s)", (model_id, field_name, field.string, field._type, relation, field.help, module_name)) - elif fields[field_name]['field_description'] != field.string \ - or fields[field_name]['ttype'] != field._type \ - or fields[field_name]['relation'] != relation \ - or fields[field_name]['help'] != field.help: + elif model_fields[field_name]['field_description'] != field.string \ + or model_fields[field_name]['ttype'] != field._type \ + or model_fields[field_name]['relation'] != relation \ + or model_fields[field_name]['help'] != field.help: cursor.execute('UPDATE ir_model_field ' \ 'SET field_description = %s, ' \ 'ttype = %s, ' \ @@ -296,7 +302,7 @@ class Model(object): 'help = %s ' \ 'WHERE id = %s ', (field.string, field._type, relation, - field.help, fields[field_name]['id'])) + field.help, model_fields[field_name]['id'])) trans_name = self._name + ',' + field_name if trans_name not in trans_fields: if field_name not in ('create_uid', 'create_date', @@ -328,7 +334,7 @@ class Model(object): and ((hasattr(field, 'translate_selection') \ and field.translate_selection) or not hasattr(field, 'translate_selection')): - for (key, val) in field.selection: + for (_, val) in field.selection: if trans_name not in trans_selection \ or val not in trans_selection[trans_name]: cursor.execute('INSERT INTO ir_translation ' \ @@ -338,13 +344,14 @@ class Model(object): (trans_name, 'en_US', 'selection', val, '', module_name, False)) # Clean ir_model_field from field that are no more existing. - for field_name in fields: - if fields[field_name]['module'] == module_name \ + for field_name in model_fields: + if model_fields[field_name]['module'] == module_name \ and field_name not in self._columns: - # XXX This delete field even when it is defined later in the module + #XXX This delete field even when it is defined later + # in the module cursor.execute('DELETE FROM ir_model_field '\ 'WHERE id = %s', - (fields[field_name]['id'],)) + (model_fields[field_name]['id'],)) # Add error messages in ir_translation cursor.execute('SELECT id, src FROM ir_translation ' \ diff --git a/trytond/model/modelsql.py b/trytond/model/modelsql.py index b7ea54e8b7..2472f96dc3 100644 --- a/trytond/model/modelsql.py +++ b/trytond/model/modelsql.py @@ -5,7 +5,6 @@ from trytond.model import ModelStorage from trytond.model import fields from trytond.backend import FIELDS, TableHandler from trytond.backend import DatabaseIntegrityError, Database -from trytond.model.browse import BrowseRecord, BrowseRecordNull from trytond.tools import reduce_ids from trytond.const import OPERATORS import datetime @@ -62,7 +61,8 @@ class ModelSQL(ModelStorage): # create/update table in the database table = TableHandler(cursor, self, module_name) if self._history: - history_table = TableHandler(cursor, self, module_name, history=True) + history_table = TableHandler(cursor, self, module_name, + history=True) timestamp_field = FIELDS['timestamp'] integer_field = FIELDS['integer'] logs = ( @@ -168,7 +168,7 @@ class ModelSQL(ModelStorage): and field.left and field.right: self._rebuild_tree(cursor, 0, field_name, False, 0) - for ident, constraint, msg in self._sql_constraints: + for ident, constraint, _ in self._sql_constraints: table.add_constraint(ident, constraint) if self._history: @@ -179,7 +179,8 @@ class ModelSQL(ModelStorage): if not cursor.fetchone(): columns = ['"' + str(x) + '"' for x in self._columns if not hasattr(self._columns[x], 'set')] - cursor.execute('INSERT INTO "' + self._table + '__history" '\ + cursor.execute('INSERT ' \ + 'INTO "' + self._table + '__history" '\ '(' + ','.join(columns) + ') ' \ 'SELECT ' + ','.join(columns) + \ ' FROM "' + self._table + '"') @@ -204,6 +205,24 @@ class ModelSQL(ModelStorage): res.append(error) return res + def default_sequence(self, cursor, user, context=None): + ''' + Return the default value for sequence field. + ''' + table = self._table + if 'sequence' not in self._columns: + for model in self._inherits: + model_obj = self.pool.get(model) + if 'sequence' in model_obj._columns: + table = model_obj._table + break + cursor.execute('SELECT MAX(sequence) ' \ + 'FROM "' + table + '"') + res = cursor.fetchone() + if res: + return res[0] + return 0 + def table_query(self, context=None): ''' Return None if the model is a real table in the database @@ -269,7 +288,7 @@ class ModelSQL(ModelStorage): for i in values.keys(): if i in self._inherit_fields: - (inherits, col, col_detail) = self._inherit_fields[i] + (inherits, _, _) = self._inherit_fields[i] if i in self._columns: continue if inherits in tocreate: @@ -388,8 +407,8 @@ class ModelSQL(ModelStorage): upd_todo.sort(lambda x, y: self._columns[x].priority - \ self._columns[y].priority) for field in upd_todo: - self._columns[field].set(cursor, user, id_new, self, field, values[field], - context=context) + self._columns[field].set(cursor, user, id_new, self, field, + values[field], context=context) if self._history: cursor.execute('INSERT INTO "' + self._table + '__history" ' \ @@ -406,7 +425,8 @@ class ModelSQL(ModelStorage): if isinstance(field, fields.Many2One) \ and field.model_name == self._name \ and field.left and field.right: - self._update_tree(cursor, user, id_new, k, field.left, field.right) + self._update_tree(cursor, user, id_new, k, field.left, + field.right) return id_new @@ -502,7 +522,7 @@ class ModelSQL(ModelStorage): else: cursor.execute('SELECT ' + \ ','.join(fields_pre2 + ['id']) + \ - ' FROM ' + table_query + '\"' + self._table + '\" ' \ + ' FROM ' + table_query + '\"' + self._table + '\" '\ 'WHERE ' + red_sql + \ history_clause + history_order + history_limit, table_args + red_ids + history_args) @@ -647,8 +667,8 @@ class ModelSQL(ModelStorage): record_id = record2['id'] del record2['id'] fields_related2values[field].setdefault(record_id, {}) - fields_related2values[field][record_id][record['id']] = \ - record2 + fields_related2values[ + field][record_id][record['id']] = record2 else: for record in obj.read(cursor, user, [x[field] for x in res if x[field]], fields_related[field], context=context): @@ -876,9 +896,9 @@ class ModelSQL(ModelStorage): .get(field.model_name, set()) if not ((model_obj.search(cursor2, 0, [ ('id', '=', values[field_name]), - ], order=[], context=context) \ - or values[field_name] in create_records) \ - and values[field_name] not in delete_records): + ], order=[], context=context) or + values[field_name] in create_records) and + values[field_name] not in delete_records): self.raise_user_error(cursor2, 'foreign_model_missing', error_args=self._get_error_args( @@ -948,8 +968,9 @@ class ModelSQL(ModelStorage): and field.model_name == self._name \ and field.left and field.right: if field.left in values or field.right in values: - raise Exception('ValidateError', 'You can not update fields: ' \ - '"%s", "%s"' % (field.left, field.right)) + raise Exception('ValidateError', + 'You can not update fields: "%s", "%s"' % + (field.left, field.right)) if len(ids) == 1: self._update_tree(cursor, user, ids[0], k, field.left, field.right) @@ -1104,10 +1125,12 @@ class ModelSQL(ModelStorage): error_args = [] error_args.append(self._get_error_args(cursor2, user, 'id', context=context)[1]) - error_args.extend(list(model._get_error_args(cursor2, - user, field_name, context=context))) - self.raise_user_error(cursor2, 'foreign_model_exist', - error_args=tuple(error_args), context=context) + error_args.extend(list(model._get_error_args( + cursor2, user, field_name, context=context))) + self.raise_user_error(cursor2, + 'foreign_model_exist', + error_args=tuple(error_args), + context=context) for name, _, error in self._sql_constraints: if name in exception[0]: self.raise_user_error(cursor2, error, @@ -1269,7 +1292,8 @@ class ModelSQL(ModelStorage): return [x['id'] for x in datas] - def search_domain(self, cursor, user, domain, active_test=True, context=None): + def search_domain(self, cursor, user, domain, active_test=True, + context=None): ''' Return SQL clause and arguments for the domain @@ -1377,7 +1401,7 @@ class ModelSQL(ModelStorage): self._inherits[itable._name]) if table_join not in tables: tables.append(table_join) - tables_args += table_arg + tables_args.extend(table_arg) field = table._columns.get(fargs[0], False) if not field: if not fargs[0] in self._inherit_fields: @@ -1389,21 +1413,25 @@ class ModelSQL(ModelStorage): if field._type == 'many2one': if hasattr(field, 'search'): domain.extend([(fargs[0], 'in', - self.pool.get(field.model_name).search(cursor, user, - [(fargs[1], domain[i][1], domain[i][2])], - order=[], context=context))]) + self.pool.get(field.model_name).search(cursor, + user,[ + (fargs[1], domain[i][1], domain[i][2]), + ], order=[], context=context))]) domain.pop(i) else: domain[i] = (fargs[0], 'inselect', - self.pool.get(field.model_name).search(cursor, user, - [(fargs[1], domain[i][1], domain[i][2])], - order=[], context=context, query_string=True), + self.pool.get(field.model_name).search(cursor, + user, [ + (fargs[1], domain[i][1], domain[i][2]), + ], order=[], context=context, + query_string=True), table) i += 1 continue else: raise Exception('ValidateError', 'Clause on field "%s" ' \ - 'doesn\'t work on "%s"' % (domain[i][0], self._name)) + 'doesn\'t work on "%s"' % + (domain[i][0], self._name)) if hasattr(field, 'search'): arg = [domain.pop(i)] domain.extend(field.search(cursor, user, table, @@ -1427,7 +1455,8 @@ class ModelSQL(ModelStorage): if ids2 == True or ids2 == False: query1 = 'SELECT "' + field.field + '" ' \ - 'FROM ' + table_query + '"' + field_obj._table + '" ' \ + 'FROM ' + table_query + \ + '"' + field_obj._table + '" ' \ 'WHERE "' + field.field + '" IS NOT NULL' query2 = table_args clause = 'inselect' @@ -1440,7 +1469,8 @@ class ModelSQL(ModelStorage): if len(ids2) < cursor.IN_MAX: red_sql, red_ids = reduce_ids('id', ids2) query1 = 'SELECT "' + field.field + '" ' \ - 'FROM ' + table_query + '"' + field_obj._table + '" ' \ + 'FROM ' + table_query + \ + '"' + field_obj._table + '" ' \ 'WHERE ' + red_sql query2 = table_args + red_ids domain[i] = ('id', 'inselect', (query1, query2)) @@ -1450,8 +1480,9 @@ class ModelSQL(ModelStorage): sub_ids2 = ids2[i:i + cursor.IN_MAX] red_sql, red_ids = reduce_ids('id', sub_ids2) cursor.execute( - 'SELECT "' + field.field + \ - '" FROM ' + table_query + '"' + field_obj._table + '" ' \ + 'SELECT "' + field.field + '" ' \ + 'FROM ' + table_query + \ + '"' + field_obj._table + '" ' \ 'WHERE ' + red_sql, table_args + red_ids) @@ -1570,9 +1601,10 @@ class ModelSQL(ModelStorage): raise Exception('Error', 'Programming error: ' \ 'child_of on field "%s" is not allowed!' % \ (domain[i][0],)) - ids2 = self.pool.get(field.model_name).search(cursor, user, - [(domain[i][3], 'child_of', ids2)], order=[], - context=context) + ids2 = self.pool.get(field.model_name).search(cursor, + user, [ + (domain[i][3], 'child_of', ids2), + ], order=[], context=context) if domain[i][1] == 'child_of': domain[i] = (domain[i][0], 'in', ids2, table) else: @@ -1667,7 +1699,8 @@ class ModelSQL(ModelStorage): query1 = 'SELECT "' + table._table + '".id ' \ 'FROM ' + table_query + '"' + table._table + '" ' \ + table_join + ' ' \ - 'WHERE (' + trans_field + ' ' + domain[i][1] + ' %s)' + 'WHERE ' \ + '(' + trans_field + ' ' + domain[i][1] + ' %s)' query2 = table_args + table_join_args + [domain[i][2]] domain[i] = ('id', 'inselect', (query1, query2), table) else: @@ -1684,8 +1717,8 @@ class ModelSQL(ModelStorage): clause = 'IN' if arg[1] == 'notinselect': clause = 'NOT IN' - qu1.append('("%s"."%s" %s (%s))' % (table._table, arg[0], clause, - arg[2][0])) + qu1.append('("%s"."%s" %s (%s))' % (table._table, arg[0], + clause, arg[2][0])) qu2 += arg[2][1] elif arg[1] in ('in', 'not in'): if len(arg[2]) > 0: @@ -1793,13 +1826,15 @@ class ModelSQL(ModelStorage): add_null = True else: if arg[0] in table._columns: - qu2.append(FIELDS[table._columns[arg[0]]._type].\ - sql_format(arg[2])) + qu2.append(FIELDS[ + table._columns[arg[0]]._type + ].sql_format(arg[2])) qu1.append('("%s"."%s" %s %%s)' % (table._table, arg[0], arg[1])) if add_null: - qu1[-1] = '(' + qu1[-1] + ' OR ' + \ - '"' + table._table + '".' + arg[0] +' IS NULL)' + qu1[-1] = '(' + qu1[-1] + ' OR ' \ + '"' + table._table + '".' + arg[0] + \ + ' IS NULL)' return qu1, qu2 @@ -1963,7 +1998,8 @@ class ModelSQL(ModelStorage): FIELDS['boolean'].sql_format(False)) if table_join not in tables: tables.append(table_join) - tables_args[table_join] = [context.get('language') or 'en_US'] + tables_args[table_join] = [ + context.get('language') or 'en_US'] order_by.append('COALESCE(NULLIF(' \ + '"' + translation_table + '".value, \'\'), ' \ + '"' + table_name + '".' + field_name + ') ' + otype) @@ -1992,7 +2028,8 @@ class ModelSQL(ModelStorage): 'order': otype, }) else: - order_by.append('"' + table_name + '".' + field_name + ' ' + otype) + order_by.append('"' + table_name + '".' + field_name + \ + ' ' + otype) return order_by, tables, tables_args if field in self._inherit_fields.keys(): @@ -2126,14 +2163,14 @@ class ModelSQL(ModelStorage): ], context={'active_test': False}) if brother_ids[-1] != object_id: next_id = brother_ids[brother_ids.index(object_id) + 1] - cursor.execute('SELECT "' + left + '", "' + right + '" ' \ + cursor.execute('SELECT "' + left + '" ' \ 'FROM "' + self._table + '" ' \ 'WHERE id = %s', (next_id,)) - next_left, next_right = cursor.fetchone() - cursor.execute('SELECT "' + left + '", "' + right + '" '\ + next_left = cursor.fetchone()[0] + cursor.execute('SELECT "' + left + '" '\ 'FROM "' + self._table + '" ' \ 'WHERE id = %s', (object_id,)) - current_left, current_right = cursor.fetchone() + current_left = cursor.fetchone()[0] cursor.execute('UPDATE "' + self._table + '" ' \ @@ -2157,9 +2194,9 @@ class ModelSQL(ModelStorage): return # Works only for a single transaction for _, sql, error in self._sql_constraints: - m = _RE_UNIQUE.match(sql) - if m: - sql = m.group(1) + match = _RE_UNIQUE.match(sql) + if match: + sql = match.group(1) sql_clause = ' AND '.join('%s = %%s' % \ i for i in sql.split(',')) sql_clause = '(id != %s AND ' + sql_clause + ')' @@ -2182,9 +2219,9 @@ class ModelSQL(ModelStorage): if cursor.fetchone(): self.raise_user_error(cursor, error, context=context) continue - m = _RE_CHECK.match(sql) - if m: - sql = m.group(1) + match = _RE_CHECK.match(sql) + if match: + sql = match.group(1) for i in range(0, len(ids), cursor.IN_MAX): sub_ids = ids[i:i + cursor.IN_MAX] red_sql, red_ids = reduce_ids('id', sub_ids) diff --git a/trytond/model/modelstorage.py b/trytond/model/modelstorage.py index 810130a9e9..4836b28326 100644 --- a/trytond/model/modelstorage.py +++ b/trytond/model/modelstorage.py @@ -3,7 +3,8 @@ from trytond.model import Model from trytond.model import fields -from trytond.model.browse import BrowseRecordList, BrowseRecord, BrowseRecordNull +from trytond.model.browse import BrowseRecordList, BrowseRecord, \ + BrowseRecordNull from trytond.model.browse import EvalEnvironment from trytond.tools import safe_eval from trytond.pyson import PYSONEncoder, PYSONDecoder, PYSON @@ -15,7 +16,7 @@ import logging from itertools import chain try: import cStringIO as StringIO -except ImprotError: +except ImportError: import StringIO import csv @@ -24,9 +25,6 @@ class ModelStorage(Model): """ Define a model with storage capability in Tryton. - :_rec_name: The name of the main field of the model. - By default the field ``name``. - :id: An Integer field for unique identifier. :create_uid: A Many2One that points to the user who created the record. :create_date: A Date field for date of creation of the record. @@ -40,9 +38,7 @@ class ModelStorage(Model): violated). ``error_keyword`` must be one of the key of ``_sql_error_messages``. """ - _rec_name = 'name' - id = fields.Integer('ID', readonly=True) create_uid = fields.Many2One('res.user', 'Create User', readonly=True) create_date = fields.DateTime('Create Date', readonly=True) write_uid = fields.Many2One('res.user', 'Write User', readonly=True) @@ -74,24 +70,6 @@ class ModelStorage(Model): "Default value for create_date field." return datetime.datetime.today() - def default_sequence(self, cursor, user, context=None): - ''' - Return the default value for sequence field. - ''' - table = self._table - if 'sequence' not in self._columns: - for model in self._inherits: - model_obj = self.pool.get(model) - if 'sequence' in model_obj._columns: - table = model_obj._table - break - cursor.execute('SELECT MAX(sequence) ' \ - 'FROM "' + table + '"') - res = cursor.fetchone() - if res: - return res[0] - return 0 - def __clean_xxx2many_cache(self, cursor, user, context=None): # Clean cursor cache to_clean = [(model._name, field_name) @@ -157,8 +135,6 @@ class ModelStorage(Model): :return: True if succeed ''' model_access_obj = self.pool.get('ir.model.access') - rule_group_obj = self.pool.get('ir.rule.group') - rule_obj = self.pool.get('ir.rule') model_access_obj.check(cursor, user, self._name, 'write', context=context) @@ -241,11 +217,11 @@ class ModelStorage(Model): default['state'] = self._defaults['state'](cursor, user, context) - def convert_data(fields, data): + def convert_data(field_defs, data): data = data.copy() data_o2m = {} - for field_name in fields: - ftype = fields[field_name]['type'] + for field_name in field_defs: + ftype = field_defs[field_name]['type'] if field_name in ( 'create_date', @@ -280,21 +256,22 @@ class ModelStorage(Model): fields_names = self._columns.keys() datas = self.read(cursor, user, ids, fields_names=fields_names, context=context) - fields = self.fields_get(cursor, user, fields_names=fields_names, + field_defs = self.fields_get(cursor, user, fields_names=fields_names, context=context) for data in datas: data_id = data['id'] - data, data_o2m = convert_data(fields, data) + data, data_o2m = convert_data(field_defs, data) new_ids[data_id] = self.create(cursor, user, data, context=context) for field_name in data_o2m: - relation_model = self.pool.get(fields[field_name]['relation']) - relation_field = fields[field_name]['relation_field'] + relation_model = self.pool.get( + field_defs[field_name]['relation']) + relation_field = field_defs[field_name]['relation_field'] relation_model.copy(cursor, user, data_o2m[field_name], default={relation_field: new_ids[data_id]}, context=context) fields_translate = {} - for field_name, field in fields.iteritems(): + for field_name, field in field_defs.iteritems(): if field_name in self._columns and \ self._columns[field_name].translate: fields_translate[field_name] = field @@ -317,7 +294,8 @@ class ModelStorage(Model): for data in datas: data_id = data['id'] data, _ = convert_data(fields_translate, data) - self.write(cursor, user, new_ids[data_id], data, context=ctx) + self.write(cursor, user, new_ids[data_id], data, + context=ctx) if int_id: return new_ids.values()[0] return new_ids.values() @@ -367,8 +345,8 @@ class ModelStorage(Model): return len(res) return res - def search_read(self, cursor, user, domain, offset=0, limit=None, order=None, - context=None, fields_names=None): + def search_read(self, cursor, user, domain, offset=0, limit=None, + order=None, context=None, fields_names=None): ''' Call search and read functions at once. Useful for the client to reduce the number of calls. @@ -400,9 +378,9 @@ class ModelStorage(Model): for model in self.browse(cursor, user, ids, context=context): record = {} for fields_name in set(fields_names): - fields = fields_name.split('.') - while fields: - field_name = fields.pop(0) + fields_split = fields_name.split('.') + while fields_split: + field_name = fields_split.pop(0) if fields_name not in record: record[fields_name] = model[field_name] else: @@ -602,7 +580,7 @@ class ModelStorage(Model): if not isinstance(selection, (tuple, list)): selection = getattr(self, selection)(cursor, user, context=context) - for key, val in selection: + for key, _ in selection: if str(key) == value: res = key break @@ -673,11 +651,11 @@ class ModelStorage(Model): if not value: return False relation = None - type = fields_def[field[-1][:-3]]['type'] - if type == 'many2many': + ftype = fields_def[field[-1][:-3]]['type'] + if ftype == 'many2many': value = csv.reader(StringIO.StringIO(value), delimiter=',', quoting=csv.QUOTE_NONE, escapechar='\\').next() - elif type == 'reference': + elif ftype == 'reference': try: relation, value = value.split(',', 1) except: @@ -696,9 +674,9 @@ class ModelStorage(Model): db_id = ir_model_data_obj.get_id(cursor, user, module, xml_id) res_ids.append(db_id) - if type == 'many2many' and res_ids: + if ftype == 'many2many' and res_ids: return [('set', res_ids)] - elif type == 'reference' and res_ids: + elif ftype == 'reference' and res_ids: return '%s,%s' % (relation, str(res_ids[0])) return res_ids and res_ids[0] or False @@ -763,7 +741,7 @@ class ModelStorage(Model): cursor, user, context=context) res = process_lines(self, datas, prefix + [field], newfd, position) - (newrow, max2, translate2) = res + (newrow, max2, _) = res nbrmax = max(nbrmax, max2) reduce(lambda x, y: x and y, newrow) row[field] = (reduce(lambda x, y: x or y, newrow.values()) and @@ -778,7 +756,7 @@ class ModelStorage(Model): break if not test: break - (newrow, max2, translate2) = \ + (newrow, max2, _) = \ process_lines(self, datas, prefix + [field], newfd, position + i) if reduce(lambda x, y: x or y, newrow.values()): @@ -810,7 +788,7 @@ class ModelStorage(Model): while len(datas): res = {} try: - (res, other, translate) = \ + (res, _, translate) = \ process_lines(self, datas, [], fields_def) warning = warning_stream.getvalue() if warning: @@ -909,12 +887,12 @@ class ModelStorage(Model): walker = record[parent] while walker: if parent_type == 'many2many': - for w in walker: - walked.add(w.id) - if w.id == record.id: + for walk in walker: + walked.add(walk.id) + if walk.id == record.id: return False - walker = list(chain(*(w[parent] for w in walker - if w.id not in visited))) + walker = list(chain(*(walk[parent] for walk in walker + if walk.id not in visited))) else: walked.add(walker.id) if walker.id == record.id: @@ -952,8 +930,6 @@ class ModelStorage(Model): return self._validate(cursor, context['user'], ids, context=ctx) context = context.copy() - field_error = [] - field_err_str = [] for field in self._constraints: if not getattr(self, field[0])(cursor, user, ids): self.raise_user_error(cursor, field[1], context=context) diff --git a/trytond/model/modelview.py b/trytond/model/modelview.py index f1a03dc89d..fd4a2668b7 100644 --- a/trytond/model/modelview.py +++ b/trytond/model/modelview.py @@ -30,10 +30,10 @@ def _inherit_apply(src, inherit): pos = element2.get('position', 'inside') if pos == 'replace': parent = element.getparent() - next = element.getnext() - if next is not None: + enext = element.getnext() + if enext is not None: for child in element2: - index = parent.index(next) + index = parent.index(enext) parent.insert(index, child) else: parent.extend(element2.getchildren()) @@ -46,10 +46,10 @@ def _inherit_apply(src, inherit): element.extend(element2.getchildren()) elif pos == 'after': parent = element.getparent() - next = element.getnext() - if next is not None: + enext = element.getnext() + if enext is not None: for child in element2: - index = parent.index(next) + index = parent.index(enext) parent.insert(index, child) else: parent.extend(element2.getchildren()) diff --git a/trytond/model/modelworkflow.py b/trytond/model/modelworkflow.py index 2b860d5d75..4d4ed52830 100644 --- a/trytond/model/modelworkflow.py +++ b/trytond/model/modelworkflow.py @@ -66,7 +66,7 @@ class ModelWorkflow(ModelStorage): ], context=context) for res_id in ids: for wkf_id in workflow_ids: - instance_id = instance_obj.create(cursor, user, { + instance_obj.create(cursor, user, { 'res_type': self._name, 'res_id': res_id, 'workflow': wkf_id, diff --git a/trytond/monitor.py b/trytond/monitor.py index f42072eb40..e1adb67bf8 100644 --- a/trytond/monitor.py +++ b/trytond/monitor.py @@ -6,30 +6,28 @@ import subprocess from threading import Lock from trytond.modules import get_module_list -_lock = Lock() -_times = {} -_modules = None +_LOCK = Lock() +_TIMES = {} +_MODULES = None def _modified(path): - global _times - global _lock - _lock.acquire() + _LOCK.acquire() try: try: if not os.path.isfile(path): - return path in _times + return path in _TIMES mtime = os.stat(path).st_mtime - if path not in _times: - _times[path] = mtime + if path not in _TIMES: + _TIMES[path] = mtime - if mtime != _times[path]: - _times[path] = mtime + if mtime != _TIMES[path]: + _TIMES[path] = mtime return True except: return True finally: - _lock.release() + _LOCK.release() return False def monitor(): @@ -38,7 +36,7 @@ def monitor(): :return: True if at least one file has changed ''' - global _modules + global _MODULES modified = False for module in sys.modules.keys(): if not module.startswith('trytond.'): @@ -58,13 +56,13 @@ def monitor(): break modified = True modules = set(get_module_list()) - if _modules is None: - _modules = modules - for module in modules.difference(_modules): + if _MODULES is None: + _MODULES = modules + for module in modules.difference(_MODULES): if subprocess.call((sys.executable, '-c', 'import trytond.modules.%s' % module)): modified = False break modified = True - _modules = modules + _MODULES = modules return modified diff --git a/trytond/pool.py b/trytond/pool.py index 96ce8485d2..c2ec48a388 100644 --- a/trytond/pool.py +++ b/trytond/pool.py @@ -42,17 +42,19 @@ class Pool(object): lock.release() @staticmethod - def register(cls, type='model'): + def register(klass, type='model'): ''' Register a class - :param cls: the class + :param klass: the class :param type: the type ''' - for module in cls.__module__.split('.'): + module = None + for module in klass.__module__.split('.'): if module != 'trytond' and module != 'modules': break - Pool.classes[type].setdefault(module, []).append(cls) + if module: + Pool.classes[type].setdefault(module, []).append(klass) @staticmethod def start(): diff --git a/trytond/protocols/dispatcher.py b/trytond/protocols/dispatcher.py index 6962fe104e..bfe08d7745 100644 --- a/trytond/protocols/dispatcher.py +++ b/trytond/protocols/dispatcher.py @@ -3,8 +3,8 @@ #this repository contains the full copyright notices and license terms. from trytond.pool import Pool from trytond import security -from trytond.tools import Cache, find_language_context -from trytond.backend import Database, DatabaseIntegrityError +from trytond.tools import Cache +from trytond.backend import Database from trytond.config import CONFIG from trytond.version import VERSION from trytond.monitor import monitor @@ -39,7 +39,8 @@ def dispatch(host, port, protocol, database_name, user, session, object_type, elif method == 'logout': name = security.logout(database_name, user, session) logger = logging.getLogger('dispatcher') - logger.info('logout \'%s\' from %s:%d using %s on database \'%s\'' % \ + logger.info('logout \'%s\' from %s:%d ' \ + 'using %s on database \'%s\'' % (name, host, port, protocol, database_name)) return True elif method == 'version': @@ -206,7 +207,6 @@ def create(database_name, password, lang, admin_password): res = True except: logger.error('CREATE DB: %s failed' % (database_name,)) - import traceback, sys tb_s = reduce(lambda x, y: x+y, traceback.format_exception(*sys.exc_info())) logger.error('Exception in call: \n' + tb_s) @@ -233,7 +233,6 @@ def drop(database_name, password): cursor.commit() except: logger.error('DROP DB: %s failed' % (database_name,)) - import traceback, sys tb_s = reduce(lambda x, y: x+y, traceback.format_exception(*sys.exc_info())) logger.error('Exception in call: \n' + tb_s) diff --git a/trytond/protocols/jsonrpc.py b/trytond/protocols/jsonrpc.py index c3f34ab467..bff602b9f3 100644 --- a/trytond/protocols/jsonrpc.py +++ b/trytond/protocols/jsonrpc.py @@ -6,7 +6,6 @@ from trytond.config import CONFIG import SimpleXMLRPCServer import SimpleHTTPServer import SocketServer -from xmlrpclib import Fault import threading import traceback import socket @@ -56,7 +55,7 @@ class JSONEncoder(json.JSONEncoder): } elif isinstance(obj, Decimal): return float(obj) - return json.JSONEncoder.default(self, obj) + return super(JSONEncoder, self).default(obj) class SimpleJSONRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher): @@ -80,11 +79,11 @@ class SimpleJSONRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher): """ rawreq = json.loads(data, object_hook=object_hook) - id = rawreq.get('id', 0) + req_id = rawreq.get('id', 0) method = rawreq['method'] params = rawreq.get('params', []) - response = {'id': id} + response = {'id': req_id} try: #generate response @@ -210,8 +209,8 @@ class SimpleJSONRPCRequestHandler(GenericJSONRPCRequestHandler, """ # abandon query parameters - path = path.split('?',1)[0] - path = path.split('#',1)[0] + path = path.split('?', 1)[0] + path = path.split('#', 1)[0] path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) @@ -252,12 +251,14 @@ class SimpleJSONRPCServer(SocketServer.TCPServer, _send_traceback_header = False def __init__(self, addr, requestHandler=SimpleJSONRPCRequestHandler, - logRequests=True, allow_none=False, encoding=None, bind_and_activate=True): + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True): self.logRequests = logRequests SimpleJSONRPCDispatcher.__init__(self, allow_none, encoding) try: - SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) + SocketServer.TCPServer.__init__(self, addr, requestHandler, + bind_and_activate) except TypeError: SocketServer.TCPServer.__init__(self, addr, requestHandler) diff --git a/trytond/protocols/netrpc.py b/trytond/protocols/netrpc.py index f5034746d2..06d5b810a9 100644 --- a/trytond/protocols/netrpc.py +++ b/trytond/protocols/netrpc.py @@ -29,7 +29,7 @@ class NetRPCClientThread(threading.Thread): return False timeout = 0 while self.running: - (rlist, wlist, xlist) = select.select([self.sock], [], [], 1) + (rlist, _, _) = select.select([self.sock], [], [], 1) if not rlist: timeout += 1 if timeout > 600: @@ -61,7 +61,8 @@ class NetRPCClientThread(threading.Thread): tback = sys.exc_info()[2] pdb.post_mortem(tback) try: - pysocket.send(exception.args, exception=True, traceback=tb_s) + pysocket.send(exception.args, exception=True, + traceback=tb_s) except: pysocket.disconnect() self.threads.remove(self) @@ -101,7 +102,7 @@ class NetRPCServerThread(threading.Thread): while self.running: if not int(CONFIG['max_thread']) \ or len(self.threads) < int(CONFIG['max_thread']): - (clientsocket, address) = self.socket.accept() + (clientsocket, _) = self.socket.accept() c_thread = NetRPCClientThread(clientsocket, self.threads, self.secure) self.threads.append(c_thread) diff --git a/trytond/protocols/webdav.py b/trytond/protocols/webdav.py index 9930f54697..af5c0cb9b5 100644 --- a/trytond/protocols/webdav.py +++ b/trytond/protocols/webdav.py @@ -14,11 +14,10 @@ import socket import os import BaseHTTPServer import urlparse -import base64 import time from DAV import AuthServer, WebDAVServer, iface from DAV.errors import * -from DAV.constants import COLLECTION, OBJECT, DAV_VERSION_1, DAV_VERSION_2 +from DAV.constants import COLLECTION, DAV_VERSION_1, DAV_VERSION_2 from DAV.utils import get_uriparentpath, get_urifilename, quote_uri from DAV.davcmd import copyone, copytree, moveone, movetree, delone, deltree import urllib @@ -36,6 +35,7 @@ DAV_VERSION_2['version'] += ',access-control' class LocalInt(local): def __init__(self, value=0): + super(LocalInt, self).__init__() self.value = value def __int__(self): @@ -153,7 +153,8 @@ class TrytonDAVInterface(iface.dav_interface): protocol = 'https' else: protocol = 'http' - self.baseuri = '%s://%s:%s/' % (protocol, interface or socket.gethostname(), port) + self.baseuri = '%s://%s:%s/' % (protocol, interface or + socket.gethostname(), port) self.verbose = False def _log_exception(self, exception): @@ -221,10 +222,12 @@ class TrytonDAVInterface(iface.dav_interface): def get_data(self, uri): dbname, dburi = self._get_dburi(uri) if not dbname or (self.exists(uri) and self.is_collection(uri)): - res = '' + res = '' res += '' res += '
' - res += '' + res += '' res += '