netbox-community / pynetbox

Python API client library for Netbox.
Apache License 2.0
567 stars 168 forks source link

Extras Image Attachment fails due to incorrect content type #520

Open egreenspan2 opened 1 year ago

egreenspan2 commented 1 year ago

Attempting to attach an image to dcim.device using this sample code:

  with open("file_file.jpg", "rb") as file_handle:

        image_data = file_handle.read()

    base_encoded = base64.b64encode(image_data).decode("utf8")

    image_data = dict(
        content_type="dcim.device",
        object_id=1234,
        name="Test image",
        image=base_encoded,
        image_height=1234,
        image_width=1234,
    )
    try:
        nb_api.extras.image_attachments.create(image_data)
    except pynetbox.RequestError:
        log.exception(f"Failed to attach image")

Catching RequestError

   File "blah/venv/lib/python3.10/site-packages/pynetbox/core/query.py", line 287, in _make_call
       raise RequestError(req)
  pynetbox.core.query.RequestError: The request failed with code 400 Bad Request: {'image': ['The submitted data was not a file. Check the encoding type on the form.']}`

I believe the issue is that the Content-Type should be set to "multipart/form-data" for this to work.

Any suggestions are appreciated, is there a way to change content-type here? Or am I missing something simple?