Wednesday, December 13, 2017

Odoo XMLRPC: create ir.attachment with non-ascii datas

Consider the following Python 3 code:

import xmlrpc.client
import functools
import base64

url = 'http://myodoo:8069'
db = 'a_database'
username = 'admin'
password = 'admin'

common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})

models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))
call = functools.partial(models.execute_kw, db, uid, password)

vals = {'res_model': 'crm.lead', 'company_id': 1, 'res_name': 'A Name', 
        'res_id': 1, 'datas_fname': 'TEST.txt', 'name': 'TEST.txt'}
  
vals.update({
  'datas': 'Hi!'
})
call('ir.attachment', 'create', [vals])


This should work fine. However, if the data contains non-ASCII characters, the server side complains:

ValueError: string argument should contain only ASCII characters


So we must encode the data, but it must stay ASCII. To do that, use this:

'datas': base64.b64encode("allĂ´!".encode()).decode('ascii')