i have query like this
query = Notification.query(db.func.count(Notification.id))
query = query.filter(Notification.read == False)
query = query.filter(Notification.id == recv_id)
return query.all()
and i got error like this
query = Notification.query(db.func.count(Notification.id))
TypeError: 'BaseQuery' object is not callable
please help, thanks
Your first line raises the error. query is an instance of BaseQuery and its not callable.
What you are trying to do is similar to:
class A(object):
pass
a_obj = A()
print a_obj()
You can't call an instance.
You should call some method on the instance.
Not sure why you require the first line in your code.
You can do something like:
Notification.query.filter(Notification.read == False)
Related
I am writing Unit test for Python app that connects to Mysql using MySQLdb .
There is a function that connects to Mysql db and returns the connection object.
def connect_to_database():
conn = MySQLdb.connect(host=db_pb2['mysql_host'],
user=db_pb2['mysql_user'],
passwd=db_pb2['mysql_password'],
db=db_pb2['mysql_db'])
return conn
There is one more function that executes the query using the above connection
def execute_query():
cur = connect_to_database().cursor()
a = cur.execute("query")
if a > 0:
result = cur.fetchall()
return result
I have written #patch to mock the return value from the cur.fetchall() and cur.execute() methods
#patch('application.module1.data_adapters.connect_to_database')
def test_daily_test_failures(self, db_connection):
db_connection.cursor().execute.return_value = 1
db_connection.cursor().fetchall. \
return_value = ((1,5,6),)
self.assertEqual((execute_query(),
((1,5,6),))
I get the following error:
if a > 0:
TypeError: '<=' not supported between instances of 'MagicMock' and 'int'
Seems like the return value in patch function is not working as expected
Your patching requires a bit more effort.
#patch('application.module1.data_adapters.connect_to_database')
def test_daily_test_failures(self, connect_to_database):
db_connection = MagicMock()
connect_to_database.return_value = db_connection # 1.
mock_cursor = MagicMock()
db_connection.cursor.return_value = mock_cursor # 2.
mock_cursor.fetchall.return_value = ((1,5,6),)
self.assertEqual((execute_query(),
((1,5,6),))
You're patching the symbol connect_to_database - that does not mock the call to the function. You need to specify that "when that symbol is called, do this"
When mocking function calls, you can't do it like this: db_connection.cursor(). - you need to make db_connection.cursor return a mock, & then specify the .return_value for that mock object
If I'm getting multiple records from a database with peewee, I can convert them to dicts like this:
users = User.select().where(User.attribute == some_value).dicts()
However, often I only want one record (or know that only one record will be returned), so I can do:
one_user = User.get(User.name == some_value)
But I can't call .dicts() on the object which is returned by that.
Is there a way to get the result of that get query in dict form?
At the moment the only thing I can think of is the unpythonic
one_user = User.select().where(User.name == some_value).dicts()[0]
peewee has an extension function model_to_dict, defined in playhouse.shortcuts. From the example:
>>> from playhouse.shortcuts import model_to_dict
>>> user = User.create(username='charlie')
>>> model_to_dict(user)
{'id': 1, 'username': 'charlie'}
You can use ".get()":
one_user = User.select().where(User.name == some_value).dicts().get()
Though you can also add a helper method:
class User(Model):
#classmethod
def get_as_dict(cls, expr):
query = cls.select().where(expr).dicts()
return query.get()
It's python. You can extend it.
in reference to Peewee model to JSON
i think you should implement a str method as defined in the link, and then when you do.
user = User.get(User.name == some_value)
userDict = json.dumps(str(user))
you will get the dictioanry of the user
I followed the short guide in the peewee docs on how to add user defined operators, but when I try to do it, it gives me a KeyError.
from peewee import *
from peewee import OP
from peewee import Expression
db = MySQLDatabase(app.config['MYSQL_DATABASE_DB'], host=app.config['MYSQL_DATABASE_HOST'], user=app.config['MYSQL_DATABASE_USER'], passwd=app.config['MYSQL_DATABASE_PASSWORD'])
OP['MOD'] = 'mod'
def mod(lhs, rhs):
return Expression(lhs, OP.MOD, rhs)
MySQLDatabase.register_ops({OP.MOD: '%'})
class Base(Model):
class Meta:
database = db
class User(Base):
user_id = PrimaryKeyField()
first_name = CharField(max_length = 150)
last_name = CharField(max_length = 150)
#app.route('/')
def test():
query = User.select().where(mod(User.user_id, 2) == 0)
return "Query: %r" % query
When I try to run it, it gives me this error:
KeyError: 'mod'
Any ideas what I might be doing wrong?
The problem is that you are defining your database before you are calling register_ops(). To fix the immediate bug you can move your db = MySQL... below the call to register_ops().
This does seem a little like a bug in peewee, though, so I've opened a github issue: https://github.com/coleifer/peewee/issues/599
Edit: I decided to after all not change the behavior. The solution I proposed should work, though -- register ops first, instantiate second. You can also specify custom ops when instantiating the database:
http://docs.peewee-orm.com/en/latest/peewee/api.html#Database
Example
OP['MOD'] = 'mod'
def mod(lhs, rhs):
return Expression(lhs, OP.MOD, rhs)
db = MySQLDatabase(
app.config['MYSQL_DATABASE_DB'],
host=app.config['MYSQL_DATABASE_HOST'],
user=app.config['MYSQL_DATABASE_USER'],
passwd=app.config['MYSQL_DATABASE_PASSWORD'],
ops={OP.MOD: '%'})
Before this
def mod(lhs, rhs):
return Expression(lhs, OP.MOD, rhs)
You need to define this
OP['MOD'] = 'mod'
OP['MOD'] = 'mod'
def mod(lhs, rhs):
return Expression(lhs, OP.MOD, rhs)
db = MySQLDatabase(
app.config['MYSQL_DATABASE_DB'],
host=app.config['MYSQL_DATABASE_HOST'],
user=app.config['MYSQL_DATABASE_USER'],
passwd=app.config['MYSQL_DATABASE_PASSWORD'])
Specifying the ops argument will lead to error, in fact, you don't have to do that.
The only thing you have to be careful is to import the function mod you defined to the module that you want to use it in.
I need to call a method from another method of the same class in python .
I can't use self due to some limitation .
When I am trying to do following .
def get_report_by_region(self, report_type, ids, business_unit, region):
if report_type == "courses":
request_name = "_get_reports_course_region"
elif report_type == "certifications":
request_name = "_get_reports_certificate_region"
elif report_type == "learning_path":
request_name = "_get_reports_learning_path_region"
data = {
'ids': ids,
'businessunit': business_unit,
'regioncode': region}
result = self.get_individual_report_by_region(data,request_name)
return result
#staticmethod
#cached_by_signature(time=memcached.MINUTE)
def get_individual_report_by_region(data,request_name):
result = MoodleClient.get(request_name, params=data)
return result
I am getting the error
result = MoodleClient.get(request_name, params=data)
TypeError: unbound method get() must be called with MoodleClient instance as first argument (got str instance instead)
all the above method are defined inside the class
MoodleClient
The error indicates that get() method is an instance method.
It either needs to be static in the same fashion as get_individual_report_by_region() or you need to provide an instance of MoodleClient.
You have to think whether it can be static method at all - if you need an instance state, then you cannot make it static.
I have an ORM mapped object, that I want to update. I have all attributes validated and secured in a dictionary (keyword arguments). Now I would like to update all object attributes as in the dictionary.
for k,v in kw.items():
setattr(myobject, k, v)
doesnt work (AttributeError Exception), thrown from SQLAlchemy.
myobject.attr1 = kw['attr1']
myobject.attr2 = kw['attr2']
myobject.attr3 = kw['attr3']
etc is horrible copy paste code, I want to avoid that.#
How can i achieve this? SQLAlchemy already does something similar to what I want to do in their constructors ( myobject = MyClass(**kw) ), but I cant find that in all the meta programming obfuscated crap in there.
error from SA:
<< if self.trackparent:
if value is not None:
self.sethasparent(instance_state(value), True)
if previous is not value and previous is not None:
self.sethasparent(instance_state(previous), False)
>> self.sethasparent(instance_state(value), True)
AttributeError: 'unicode' object has no attribute '_sa_instance_state'
myobject.__dict__.update(**kw)
You are trying to assign a unicode string to a relation attribute. Say you have:
class ClassA(Base):
...
b_id = Column(None, ForeignKey('b.id'))
b = relation(ClassB)
And you are trying to do:
my_object = ClassA()
my_object.b = "foo"
When you should be doing either:
my_object.b_id = "foo"
# or
my_object.b = session.query(ClassB).get("foo")