Increment all fields of all objects in a collection pymongo - python

Hello i would like to increment the field current_week of all objects in the collection tournaments but i get an error. I have the code:
class DataBase:
def __init__(self):
self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
self.mydb = self.myclient["MMA_TOURNAMENT"]
self.tournaments = self.mydb["tournaments"]
def insert_new_tournament(self, tournament):
print(tournament.__dict__)
self.tournaments.insert_one(tournament.__dict__)
def increment_day(self):
self.tournaments.update({'$inc': {'current_week' : 1}})
and i get the error:
TypeError: update() missing 1 required positional argument: 'document'
when calling the function. I am a beginner in pymongo I really don't know what query I should put there. Thank you!

You need to pass a filter as the first parameter to update_many(); to update every document your filter is simply {}.
def increment_day(self):
self.tournaments.update_many({}, {'$inc': {'current_week' : 1}})

Related

Python - Problem returning True/False to class properties from class method

I have a class as below which within the __init__ method I am trying to assign a True/False value to a class property using a class method.
class Sensor:
def __init__(self, json_data):
self.sensor_eui = json_data['end_device_ids']['dev_eui']
self.reading1 = json_data['uplink_message']['decoded_payload']['temperature']
self.reading2 = json_data['uplink_message']['decoded_payload']['humidity']
self.tolerance_exceeded = self.tolerance_check
def tolerance_check(self):
sql = f"SELECT DefaultLowerLimit, DefaultUpperLimit FROM [dbo].[IoT_Sensors] WHERE
DeviceID = '{self.sensor_eui}'"
results = exec_sql(sql)
if (self.reading1 > int(results[0])) and (self.reading1 < int(results[1])):
return False
return True
The issue is, when trying to troubleshoot this and logging the objects to the console, instead of returning True or False as the assigned value of 'tolerance_exceeded' it returns the method and object:
logging.info(f'Tolerance Exceeded: {sensor.tolerance_exceeded}')
logs in the console as below:
[2022-10-26T12:08:08.025Z] Tolerance Exceeded: <bound method Sensor.tolerance_check of <__app__.IoT_Data-Handler.classes.Sensor object at 0x000001C834D45BE0>>
So what is going on here? I have not been coding long, but when I have done something similar in the past (assigning a string value from an API), it worked fine. This is for an Azure Function, but I cannot see how that would impact what I am trying to achieve.
Any help would be appreciated.
The issue in your code is that instead of calling the function you assign it. In order to call the function you have to add the parenthesis.
class Sensor:
def __init__(self, json_data):
self.sensor_eui = json_data['end_device_ids']['dev_eui']
self.reading1 = json_data['uplink_message']['decoded_payload']['temperature']
self.reading2 = json_data['uplink_message']['decoded_payload']['humidity']
# Calling tolerance_check and assigning return value to tolerance_exceeded
self.tolerance_exceeded = self.tolerance_check()

pydantic initialize new object with an existing object (fastapi)

I have a Base class, to get the values from the frontend. The user_id should comes from the Depends(deps.get_current_user) function.
How can i initialize the new class CommentCreate now, with the values from CommentBase?
And is this the common use?
I got it worked with the workaround extra=Extra.allow and setattr(message,...)
I think it should be something like: commentCreate = schemas.CommentCreate(**comment, user_id=current_user.id)
class CommentBase(BaseModel, extra=Extra.allow):
blog_id: int
message: str
class CommentCreate(CommentBase):
user_id: int
#router.post("/post/comment")
def post_comment_reply(
message: schemas.CommentBase,
current_user: models.User = Depends(deps.get_current_active_user),
db: Session = Depends(deps.get_db),
):
setattr(message, "user_id", current_user.id)
print(message)
You can use the dict method to achieve this.
something like :
CommentCreate(user_id=current_user , **message.dict())

return value using into another function

I am using return value of function into another function, I want to do first I check if function return value ? if yes then only use return value
I am able to do this but in my case function call two times reason also i know but how can I achieve it with function call for only one time
Actually I am new in programming please can anyone help me
Thank you in advance
from loginAuth import *
class DisplayInfo:
def displayInfo(self):
# create object of loginAuth class
obj = LoginAuth()
if obj.check_password_and_userid():
userid, userrole = obj.check_password_and_userid()
print(userid,userrole)
obj = DisplayInfo()
obj.displayInfo()
here method: check_password_and_userid() is a function of class LoginAuth
which return userid and userrole
output : 01 Admin
obj.check_password and userid() returns a tuple like (userid, user role) if it's true then you can just set data to a variable then play with the data.
from loginAuth import *
class DisplayInfo:
def displayInfo(self):
# create object of loginAuth class
obj = LoginAuth()
data = obj.check_password_and_userid()
if data:
userid, userrole = data
print(userid,userrole)
obj = DisplayInfo()
obj.displayInfo()

builtins.TypeError TypeError

i have tried 100 times i do not know what is wrong with this code. somebody please help me to sort out this issue or tell me what i am doing wrong to below code.
Every time i receive:
builtins.TypeError TypeError: getCategoryItems() missing 1 required
positional argument: 'cat_id'
Code:
#app.route('/')
def getAllItems():
return redirect(url_for('getCategoryItems', category_name='ab', cat_id=1))
#app.route('/<string:category_name>/items/')
def getCategoryItems(category_name, cat_id):
id = cat_id;
items = session.query(Item).filter_by(category_id=id).all()
output = ''
for item in items:
output += item.title + '</br>'
return output
You don't need to pass category_name, you only need the category id. The category name should be contained in each of the item fetched from the database.
You're getting an error because cat_id is not defined when the function def getCategoryItems(category_name, cat_id) is called.
I would suggest, however, if you want to really get all items to just use:
#app.route('/')
def getAllItems():
items = session.query(Item).all()
...
For more info, have a look at the flask-sqlalchemy docs.

Accessing elements of lists, and calling their fuctions

Here is Customer class:
class Customer:
def __init__(self, timestamp, cid, item_count):
self.time_stamp = timestamp
self.customer_name = cid
self.item_count = item_count
def checkout(self, new_timestamp):
self.time_stamp = new_timestamp
def get_cus_name(self):
return self.customer_name
If I create an empty list of Customer objects like:
customers = [Customer]
And then somewhere else I try to call Customer methods in a loop like:
def checkout_customer(self, cid):
for cus in self.customers:
if cus.get_cus_name == cid:
cus.checkout(self.cur_num_customers + 7)
why do I get an error when I try to call cus.checkout? My ide tells me that it expects a Customer but got an int. Why doesn't it pass itself into the 'self' arg here?
However if I just create a Customer object and directly call its methods, it works fine:
def foo(self):
cus = Customer(1,'pop',2)
cus.checkout(23)
This is my first time learning python, and ive been stuck trying to figure out lists, and accessing its members. Perhaps my initialization of self.custormers = [Customer] is incorrect?
EDIT:
In my constructor of tester class I create an empty list like this:
self.customer = [Customer]
I am able to add customers no problem:
def add_custormer(self, customer):
self.customers.append(customer)
My problem is not adding customers, but accessing their methods once they are in a list. Doing something like this self.customers[0].checkout(1,'pop',2) gives me an error "Expected type 'Customer' got int".
I am not sure of the class where checkout_customer lives but I am assuming you declare the list self.customers somewhere in it.
self.costumers = []
If you intend to add an element Customer to the list you should use something like: self.customers.append(Customer(x,y,z)) since you want to add a new customer to the list and when doing so you are required to initialize the Customer class.
I didn't try the code but I believe something like this should work:
def foo(self):
self.customers.append(Customer(1,'pop',2))
self.checkout_customers(23)

Categories