payload is a comma separated chunk of data that represents the readings from an inverter. These readings need to be stored in a table called InverterHistory. There will not always be a value for each field. The model already has been setup to allow null/blank for the fields. So I am trying to check to see if there is a value present before assigning it to a field. Here is what I have so far:
i = Inverter.objects.get(mac=u)
payload.reverse()
try:
ac_volts_a = str(payload.pop())
ac_volts_b = str(payload.pop())
ac_volts_c = str(payload.pop())
ac_current_a = str(payload.pop())
ac_current_b = str(payload.pop())
ac_current_c = str(payload.pop())
dc_volts = str(payload.pop())
dc_current = str(payload.pop())
kw_out = str(payload.pop())
mwh_total = str(payload.pop())
current_time = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
i_data = InverterHistory(
inverter = i,
if ac_volts_a:
voltage_ac_a = float(ac_volts_a),
if ac_volts_b:
voltage_ac_b = float(ac_volts_b),
if ac_volts_c:
voltage_ac_c = float(ac_volts_c),
if ac_current_a:
current_ac_a = float(ac_current_a),
if ac_current_b:
current_ac_b = float(ac_current_b),
if ac_current_c:
current_ac_c = float(ac_current_c),
if dc_volts:
voltage_dc = float(dc_volts),
if dc_current:
current_dc = float(dc_current),
if kw_out:
kwout = float(kw_out),
if mwh_total:
mwh = float(mwh_total),
recordTime = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
i_data.save()
except Exception, e:
print >> sys.stderr, "Error While Recording Inverter History"
print >> sys.stderr, e
raise Http404
I am fairly new to python and don’t know how to properly code the above. When I try to compile the code I am getting an error where the if statements start. How can i fix the above code so it will compile and work as desired?
When you write
i_data = InverterHistory(...), you are creating an object of typeInverterHistoryand the...are the parameters you pass to the constructor. Constructing an object in Python is like calling a function or a method and you cannot put logic inside the parenthesis. So, you are getting an error because it is incorrect syntax to put anifstatement there.What you need to do is move your logic out of the parenthesis and put all your variables inside a Python
dict. You can then pass thatdictas parameter to your call toInverterHistory.The
**paramsunpacks the dictionary. This means that the interpreter will take all thekey: valuefrom the dictionary and turn them intokey=value. This way, each param for which theifstatement wasTruewill be passed as a named parameter toInverterHistory