3

I have a controller that create a new record for a specific model.
This model contains a fields.Binary.

Here's what the controller looks like:

@http.route('/mymodel/create', type='json', method='POST', auth='user')
def create_record(self, **kwargs):
    """
    @params:
    'field1': string
    'field2': int
    'binaryField': binary
    """
    values = {'my_model_field_1': kwargs.get('field1'),
              'my_model_field_2': kwargs.get('field2'),
              'my_model_binary_field': kwargs.get('binaryField')}
    request.env['my_model'].create(values)

My question is how should I send my file from the remote app connected to the server?

I'll probably have to send it as a string since it's sent in the json format. How do I have to modify my controller to receive it correctly?
I would be grateful for an example of code converting the file in a string that can be sent throught Json. I'll also have to convert it from any language, as I'm building an API, what is the standard that will be recognized by the binary field?

T.Nel
  • 1,540
  • 2
  • 18
  • 34
  • 2
    Not familiar with Odoo, but its fairly common for file contents to be encoded using Base64 when sending files in JSON – najayaz Dec 21 '18 at 04:42
  • 1
    @G-man put that as answer, because you have to encode binary files for Odoo, too. – CZoellner Dec 21 '18 at 10:04

1 Answers1

5

As I said in my comment, you'll probably need to read the file contents as binary, encode it using base64, and then decode the encoded bytes to put it in the JSON.

Python3 snippet for accomplishing this:

import base64
import json

data = {}

# read raw file bytes
with open('filename','rb') as myfile:
        file_bytes = myfile.read()

# encode, decode and put it in the JSON
data['file'] = base64.encodebytes(file_bytes).decode('ascii')

# optionally serialize the JSON
serialized_json = json.dumps(data)
najayaz
  • 194
  • 3
  • 11