Home > OS >  (Python) calling mutiple my own functions, NameError not defined , on passing output between functio
(Python) calling mutiple my own functions, NameError not defined , on passing output between functio

Time:10-21

I know this kind of the beginner mistake, but I'm not sure how to make change_db_data detect mycol

issue on passing value mycol between function

(ps. mycol means collection in MongoDB )

error :

Traceback (most recent call last):
File "C:\Users\chuan\OneDrive\Desktop\10.20_connect_mongoD_(Query, Delete)\main.py", line 16, in
x = change_db_data(myquery_json, newvalues_json, one_or_many_bool)

File "C:\Users\chuan\OneDrive\Desktop\10.20_connect_mongoD_(Query, Delete)\Iser_upd_qur_del_function.py", line 14, in change_db_data
x = mycol.update_many(myquery_json, newvalues_json)
NameError: name 'mycol' is not defined

The function file name Iser_upd_qur_del_function.py

import pymongo
import datetime
import json
def init_db(ip, db, coll):
    myclient = pymongo.MongoClient('mongodb://'   ip   '/')
    mydb = myclient[db]
    mycol = mydb[coll]

    return mydb, mycol


def change_db_data(myquery_json, newvalues_json, one_or_many_bool):
    
    if one_or_many_bool == True:
        x = mycol.update_many(myquery_json, newvalues_json)
    else:
        x = mycol.update_one(myquery_json, newvalues_json)
    return x
  • the main function:
from Iser_upd_qur_del_function import *

ip_input = input("Enter the ip: ")
exist_DB_name = input("Enter exist DB name: ")
exist_coll_name = input("Enter exist collection name: ")
mydb, mycol  = init_db(ip_input, exist_DB_name, exist_coll_name)

myquery_str = input("Enter ur query: ")
update_one_or_many = input("U are update one or many values? (ex:1 for many , 0 for one): ")
newvalues_str = input("Enter new values: ")

one_or_many_bool = bool(int(update_one_or_many))

myquery_json =json.loads(myquery_str)
newvalues_json =json.loads(newvalues_str)
x = change_db_data(myquery_json, newvalues_json, one_or_many_bool)
print(x)
print(x.modified_count, "documents updated.")

CodePudding user response:

You're not passing 'mycol' into your change_db_data() function.

change_db_data(myquery_json, newvalues_json, one_or_many_bool, mycol)

def change_db_data(myquery_json, newvalues_json, one_or_many_bool, mycol):
  • Related