I am getting a litle problem with my code in python 3.7 : I woul like to compare the result i'm getting from my query in the first function (getResult(self, result)) with the query in my 'insertMetersCount()' function. How could i use this?

I know how heritage into differents classes works but not for the functions

from twisted.enterprise import adbapi
from twisted.internet import task
import logging
from datetime import datetime
from twisted.internet import reactor

class MetersCount():

    def getTotalMeters(self):
        log.info("Select operation in Database.")
        getMetersQuery = """ SELECT count(met_id) as totalMeters FROM meters WHERE DATE(met_last_heard) = DATE(NOW()) """

        return dbpool.runQuery(getMetersQuery).addCallback(self.getResult).addErrback(self.errorGetQuery)

    def getResult(self, result):
        print ("Receive Result : ")
        print (result)
        # general purpose method to receive result from defer.
        return result

    def errorGetQuery(self,result):
        print ("error received", result)
        return result

    def insertMetersCount(self):
        log.info("Insert operation in Database.")
        insertMetersQuery = """ INSERT INTO meter_count (mec_datetime, mec_count)  VALUES (NOW(), %s)""" % (self.getResult(result)) 
        return dbpool.runQuery(insertMetersQuery).addCallback(self.getResult)

    def checkDB(self):

a= MetersCount()



Thats what the error I'm getting : "NameError: global name 'result' is not defined.

1 Answers

Jean-Paul Calderone On

Welcome to stackoverflow. In the future, try posting a complete code example. Something someone could run and reproduce the problem you're having. Also, post the complete error you receive and explain what you expected to happen instead.

You need to pass result to insertMetersCount. You can also give it a better name while you're at it and stop using getResult which is basically just the identity function plus some logging. Also, don't interpolate values into SQL. That's how you create SQL injection vulnerabilities. You'll have to find the right param style for the DB library you're using. I've left "%s" but it might be "?" or "\1" or something else.

    def insertMetersCount(self, meters_count):
        log.info("Insert operation in Database.")
        insertMetersQuery = """ INSERT INTO meter_count (mec_datetime, mec_count)  VALUES (NOW(), %s)"""
        return dbpool.runQuery(
            insertMetersQuery, [meters_count]

Then call the method with the necessary argument. You can do this with the regular Deferred API:

    def checkDB(self):
        d = self.getTotalMeters()
        return d

Or with inlineCallbacks:

    from twisted.internet.defer import inlineCallbacks

    def checkDB(self):
        meters_count = yield self.getTotalMeters()
        yield self.insertMetersCount(meters_count)

These both arrange for exactly the same thing to happen. They're just two different APIs for doing so.