[PEP8] - pingen

This commit is contained in:
Laetitia Gangloff
2015-09-28 12:33:55 +02:00
parent 4d567c52c0
commit 5e46167775
4 changed files with 79 additions and 43 deletions

View File

@@ -91,8 +91,8 @@ you will need to manually handle the case, either from the pingen.com backend,
or by changing the document on OpenERP and resolving the error on the Pingen or by changing the document on OpenERP and resolving the error on the Pingen
Document. Document.
When a connection error occurs, the action will be retried on the next scheduler When a connection error occurs, the action will be retried on the next
run. scheduler run.
Dependencies Dependencies
------------ ------------

View File

@@ -41,8 +41,10 @@ class ir_attachment(orm.Model):
'pingen_speed': fields.selection( 'pingen_speed': fields.selection(
[('1', 'Priority'), ('2', 'Economy')], [('1', 'Priority'), ('2', 'Economy')],
'Speed', 'Speed',
help="Defines the sending speed if the document is automatically sent"), help="Defines the sending speed if the document is "
'pingen_color': fields.selection([('0', 'B/W'), ('1', 'Color')], 'Type of print'), "automatically sent"),
'pingen_color': fields.selection([('0', 'B/W'), ('1', 'Color')],
'Type of print'),
} }
_defaults = { _defaults = {
@@ -56,14 +58,15 @@ class ir_attachment(orm.Model):
'config': 'created from attachment'} 'config': 'created from attachment'}
def _handle_pingen_document(self, cr, uid, attachment_id, context=None): def _handle_pingen_document(self, cr, uid, attachment_id, context=None):
""" Reponsible of the related ``pingen.document`` when the ``send_to_pingen`` """ Reponsible of the related ``pingen.document``
field is modified. when the ``send_to_pingen`` field is modified.
Only one pingen document can be created per attachment. Only one pingen document can be created per attachment.
When ``send_to_pingen`` is activated: When ``send_to_pingen`` is activated:
* Create a ``pingen.document`` if it does not already exist * Create a ``pingen.document`` if it does not already exist
* Put the related ``pingen.document`` to ``pending`` if it already exist * Put the related ``pingen.document`` to ``pending`` if
it already exist
When it is deactivated: When it is deactivated:
* Do nothing if no related ``pingen.document`` exists * Do nothing if no related ``pingen.document`` exists
* Or cancel it * Or cancel it
@@ -72,7 +75,8 @@ class ir_attachment(orm.Model):
""" """
pingen_document_obj = self.pool.get('pingen.document') pingen_document_obj = self.pool.get('pingen.document')
attachment = self.browse(cr, uid, attachment_id, context=context) attachment = self.browse(cr, uid, attachment_id, context=context)
document = attachment.pingen_document_ids[0] if attachment.pingen_document_ids else None document = attachment.pingen_document_ids[
0] if attachment.pingen_document_ids else None
if attachment.send_to_pingen: if attachment.send_to_pingen:
if document: if document:
document.write({'state': 'pending'}, context=context) document.write({'state': 'pending'}, context=context)
@@ -87,22 +91,26 @@ class ir_attachment(orm.Model):
if document.state == 'pushed': if document.state == 'pushed':
raise osv.except_osv( raise osv.except_osv(
_('Error'), _('Error'),
_('The attachment %s is already pushed to pingen.com.') % _('The attachment %s is already pushed to '
attachment.name) 'pingen.com.') % attachment.name)
document.write({'state': 'canceled'}, context=context) document.write({'state': 'canceled'}, context=context)
return return
def create(self, cr, uid, vals, context=None): def create(self, cr, uid, vals, context=None):
attachment_id = super(ir_attachment, self).create(cr, uid, vals, context=context) attachment_id = super(ir_attachment, self).create(
cr, uid, vals, context=context)
if 'send_to_pingen' in vals: if 'send_to_pingen' in vals:
self._handle_pingen_document(cr, uid, attachment_id, context=context) self._handle_pingen_document(
cr, uid, attachment_id, context=context)
return attachment_id return attachment_id
def write(self, cr, uid, ids, vals, context=None): def write(self, cr, uid, ids, vals, context=None):
res = super(ir_attachment, self).write(cr, uid, ids, vals, context=context) res = super(ir_attachment, self).write(
cr, uid, ids, vals, context=context)
if 'send_to_pingen' in vals: if 'send_to_pingen' in vals:
for attachment_id in ids: for attachment_id in ids:
self._handle_pingen_document(cr, uid, attachment_id, context=context) self._handle_pingen_document(
cr, uid, attachment_id, context=context)
return res return res
def _decoded_content(self, cr, uid, attachment, context=None): def _decoded_content(self, cr, uid, attachment, context=None):

View File

@@ -58,19 +58,23 @@ def pingen_datetime_to_utc(dt):
class PingenException(RuntimeError): class PingenException(RuntimeError):
"""There was an ambiguous exception that occurred while handling your """There was an ambiguous exception that occurred while handling your
request.""" request."""
class ConnectionError(PingenException): class ConnectionError(PingenException):
"""An Error occured with the pingen API""" """An Error occured with the pingen API"""
class APIError(PingenException): class APIError(PingenException):
"""An Error occured with the pingen API""" """An Error occured with the pingen API"""
class Pingen(object): class Pingen(object):
""" Interface to the pingen.com API """ """ Interface to the pingen.com API """
def __init__(self, token, staging=True): def __init__(self, token, staging=True):
@@ -132,11 +136,13 @@ class Pingen(object):
if response.json['error']: if response.json['error']:
raise APIError( raise APIError(
"%s: %s" % (response.json['errorcode'], response.json['errormessage'])) "%s: %s" % (response.json['errorcode'],
response.json['errormessage']))
return response return response
def push_document(self, filename, filestream, send=None, speed=None, color=None): def push_document(self, filename, filestream, send=None, speed=None,
color=None):
""" Upload a document to pingen.com and eventually ask to send it """ Upload a document to pingen.com and eventually ask to send it
:param str filename: name of the file to push :param str filename: name of the file to push

View File

@@ -34,6 +34,7 @@ _logger = logging.getLogger(__name__)
class pingen_document(orm.Model): class pingen_document(orm.Model):
""" A pingen document is the state of the synchronization of """ A pingen document is the state of the synchronization of
an attachment with pingen.com an attachment with pingen.com
@@ -75,7 +76,8 @@ class pingen_document(orm.Model):
'post_status': fields.char('Post Status', size=128, readonly=True), 'post_status': fields.char('Post Status', size=128, readonly=True),
'parsed_address': fields.text('Parsed Address', readonly=True), 'parsed_address': fields.text('Parsed Address', readonly=True),
'cost': fields.float('Cost', readonly=True), 'cost': fields.float('Cost', readonly=True),
'currency_id': fields.many2one('res.currency', 'Currency', readonly=True), 'currency_id': fields.many2one('res.currency', 'Currency',
readonly=True),
'country_id': fields.many2one('res.country', 'Country', readonly=True), 'country_id': fields.many2one('res.country', 'Country', readonly=True),
'send_date': fields.datetime('Date of sending', readonly=True), 'send_date': fields.datetime('Date of sending', readonly=True),
'pages': fields.integer('Pages', readonly=True), 'pages': fields.integer('Pages', readonly=True),
@@ -95,7 +97,8 @@ class pingen_document(orm.Model):
""" Returns a pingen session for a user """ """ Returns a pingen session for a user """
company = self.pool.get('res.users').browse( company = self.pool.get('res.users').browse(
cr, uid, uid, context=context).company_id cr, uid, uid, context=context).company_id
return self.pool.get('res.company')._pingen(cr, uid, company, context=context) return self.pool.get('res.company')._pingen(cr, uid, company,
context=context)
def _push_to_pingen(self, cr, uid, document, pingen=None, context=None): def _push_to_pingen(self, cr, uid, document, pingen=None, context=None):
""" Push a document to pingen.com """ Push a document to pingen.com
@@ -141,11 +144,13 @@ class pingen_document(orm.Model):
document.write( document.write(
{'last_error_message': error, {'last_error_message': error,
'state': state, 'state': state,
'push_date': push_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT), 'push_date': push_date.strftime(
tools.DEFAULT_SERVER_DATETIME_FORMAT),
'pingen_id': doc_id, 'pingen_id': doc_id,
'post_id': post_id}, 'post_id': post_id},
context=context) context=context)
_logger.info('Pingen Document %s: pushed to %s' % (document.id, pingen.url)) _logger.info('Pingen Document %s: pushed to %s' % (document.id,
pingen.url))
def push_to_pingen(self, cr, uid, ids, context=None): def push_to_pingen(self, cr, uid, ids, context=None):
""" Push a document to pingen.com """ Push a document to pingen.com
@@ -164,7 +169,8 @@ class pingen_document(orm.Model):
except ConnectionError as e: except ConnectionError as e:
raise osv.except_osv( raise osv.except_osv(
_('Pingen Connection Error'), _('Pingen Connection Error'),
_('Connection Error when asking for sending the document %s to Pingen') % document.name) _('Connection Error when asking for sending the '
'document %s to Pingen') % document.name)
except APIError as e: except APIError as e:
raise osv.except_osv( raise osv.except_osv(
@@ -174,11 +180,13 @@ class pingen_document(orm.Model):
except: except:
_logger.exception( _logger.exception(
'Unexcepted Error when updating the status of pingen.document %s: ' % 'Unexcepted Error when updating the status of '
'pingen.document %s: ' %
document.id) document.id)
raise osv.except_osv( raise osv.except_osv(
_('Error'), _('Error'),
_('Unexcepted Error when updating the status of Document %s') % document.name) _('Unexcepted Error when updating the status '
'of Document %s') % document.name)
return True return True
def _push_and_send_to_pingen_cron(self, cr, uid, ids, context=None): def _push_and_send_to_pingen_cron(self, cr, uid, ids, context=None):
@@ -209,11 +217,13 @@ class pingen_document(orm.Model):
try: try:
if document.state == 'pending': if document.state == 'pending':
self._push_to_pingen( self._push_to_pingen(
loc_cr, uid, document, pingen=session, context=context) loc_cr, uid, document, pingen=session,
context=context)
elif document.state == 'pushed': elif document.state == 'pushed':
self._ask_pingen_send( self._ask_pingen_send(
loc_cr, uid, document, pingen=session, context=context) loc_cr, uid, document, pingen=session,
context=context)
except ConnectionError as e: except ConnectionError as e:
document.write({'last_error_message': e, document.write({'last_error_message': e,
'state': 'error'}, 'state': 'error'},
@@ -264,11 +274,13 @@ class pingen_document(orm.Model):
document.pingen_speed, document.pingen_speed,
document.pingen_color) document.pingen_color)
except ConnectionError: except ConnectionError:
_logger.exception('Connection Error when asking for sending Pingen Document %s to %s.' % _logger.exception('Connection Error when asking for sending '
'Pingen Document %s to %s.' %
(document.id, pingen.url)) (document.id, pingen.url))
raise raise
except APIError: except APIError:
_logger.exception('API Error when asking for sending Pingen Document %s to %s.' % _logger.exception('API Error when asking for sending '
'Pingen Document %s to %s.' %
(document.id, pingen.url)) (document.id, pingen.url))
raise raise
@@ -277,7 +289,8 @@ class pingen_document(orm.Model):
'state': 'sendcenter', 'state': 'sendcenter',
'post_id': post_id}, 'post_id': post_id},
context=context) context=context)
_logger.info('Pingen Document %s: asked for sending to %s' % (document.id, pingen.url)) _logger.info('Pingen Document %s: asked for sending to %s' %
(document.id, pingen.url))
return True return True
@@ -291,7 +304,8 @@ class pingen_document(orm.Model):
with self._get_pingen_session(cr, uid, context=context) as session: with self._get_pingen_session(cr, uid, context=context) as session:
for document in self.browse(cr, uid, ids, context=context): for document in self.browse(cr, uid, ids, context=context):
try: try:
self._ask_pingen_send(cr, uid, document, pingen=session, context=context) self._ask_pingen_send(
cr, uid, document, pingen=session, context=context)
except ConnectionError as e: except ConnectionError as e:
raise osv.except_osv( raise osv.except_osv(
_('Pingen Connection Error'), _('Pingen Connection Error'),
@@ -306,11 +320,13 @@ class pingen_document(orm.Model):
except: except:
_logger.exception( _logger.exception(
'Unexcepted Error when updating the status of pingen.document %s: ' % 'Unexcepted Error when updating the status of '
'pingen.document %s: ' %
document.id) document.id)
raise osv.except_osv( raise osv.except_osv(
_('Error'), _('Error'),
_('Unexcepted Error when updating the status of Document %s') % document.name) _('Unexcepted Error when updating the status '
'of Document %s') % document.name)
return True return True
def _update_post_infos(self, cr, uid, document, pingen, context=None): def _update_post_infos(self, cr, uid, document, pingen, context=None):
@@ -348,7 +364,8 @@ class pingen_document(orm.Model):
'currency_id': currency_ids[0] if currency_ids else False, 'currency_id': currency_ids[0] if currency_ids else False,
'parsed_address': post_infos['address'], 'parsed_address': post_infos['address'],
'country_id': country_ids[0] if country_ids else False, 'country_id': country_ids[0] if country_ids else False,
'send_date': send_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT), 'send_date': send_date.strftime(
tools.DEFAULT_SERVER_DATETIME_FORMAT),
'pages': post_infos['pages'], 'pages': post_infos['pages'],
'last_error_message': False, 'last_error_message': False,
} }
@@ -381,7 +398,8 @@ class pingen_document(orm.Model):
loc_cr, uid, document, pingen=session, context=context) loc_cr, uid, document, pingen=session, context=context)
except (ConnectionError, APIError): except (ConnectionError, APIError):
# will be retried the next time # will be retried the next time
# In any case, the error has been logged by _update_post_infos # In any case, the error has been logged by
# _update_post_infos
loc_cr.rollback() loc_cr.rollback()
except: except:
_logger.error('Unexcepted error in pingen cron') _logger.error('Unexcepted error in pingen cron')
@@ -406,20 +424,24 @@ class pingen_document(orm.Model):
except ConnectionError as e: except ConnectionError as e:
raise osv.except_osv( raise osv.except_osv(
_('Pingen Connection Error'), _('Pingen Connection Error'),
_('Connection Error when updating the status of Document %s' _('Connection Error when updating the status of '
'Document %s'
' from Pingen') % document.name) ' from Pingen') % document.name)
except APIError as e: except APIError as e:
raise osv.except_osv( raise osv.except_osv(
_('Pingen Error'), _('Pingen Error'),
_('Error when updating the status of Document %s from Pingen: ' _('Error when updating the status of Document %s '
'from Pingen: '
'\n%s') % (document.name, e)) '\n%s') % (document.name, e))
except: except:
_logger.exception( _logger.exception(
'Unexcepted Error when updating the status of pingen.document %s: ' % 'Unexcepted Error when updating the status of '
'pingen.document %s: ' %
document.id) document.id)
raise osv.except_osv( raise osv.except_osv(
_('Error'), _('Error'),
_('Unexcepted Error when updating the status of Document %s') % document.name) _('Unexcepted Error when updating the status of '
'Document %s') % document.name)
return True return True