UndefinedError: 'mappingproxy object' has no attribute for my template

I am seeing the below error repeat regularly in the log.

ERROR (MainThread) [homeassistant.components.template.sensor] Could not render template horizon_gpu_memory: UndefinedError: 'mappingproxy object' has no attribute 'mem'

I’ve seen solutions to avoid getting this error. However, I haven’t figured out how to adapt my template to avoid getting the error successfully. I’m also not sure why this error even happens.

Could someone please tell me how to change my template to avoid getting this error?

This is my current code below:

  - platform: rest
    name: gpu
    resource: http://192.168.1.2:61208/api/3/gpu
    value_template: '{{ ( value_json ) }}'
    json_attributes:
      - name
      - mem
      - proc
      - temperature
    scan_interval: 15


  - platform: template
    sensors:
      horizon_gpu_memory:
        value_template: '{{ states.sensor.gpu.attributes["mem"] | round }}'
        unit_of_measurement: "%"

Typically, the response from the respective REST sensor API endpoint is below:

[
    {
        "key": "gpu_id",
        "gpu_id": 0,
        "name": "GeForce GTX 1050 Ti",
        "mem": 3.8414955139160156,
        "proc": 0,
        "temperature": 39
    }
]

are you sure that there is always a “mem” attribute in the sensor?

I’m not really sure what you mean by “fixing my template” but if you mean switching to a function style instead of a states then try:

value_template: '{{ state_attr("sensor.gpu", "mem") | round }}'
1 Like

It appears the the response from the API end-point doesn’t always produce a valid “mem” value (for whatever reason). When it doesn’t, it produces the error message I posted.

Update: It seems like the reason I’m getting that error is because the API endpoint for the REST sensor is timing out once in a while. Below, is the error preceding the ’mappingproxy object’ has no attribute error message:

[homeassistant.components.rest.sensor] Error fetching data: http://192.168.1.2:61208/api/3/gpu failed with HTTPConnectionPool(host='192.168.1.2', port=61208): Read timed out. (read timeout=10)

So, if I were to replace my value_template with the one you posted, it should avoid getting the error message when there isn’t a “mem” attribute? I’m just looking for a way to avoid getting this error if possible. I’m not sure how to avoid not getting the read timeout error. So, if there’s a way to avoid getting the subsequent error, I’d like to know.

I’m not completely sure but try it and see.