def save(self): collection.insert_one({ "Usurario": self.nombre, "Username": self.username, "Correo": self.correo, "date": datetime.now(), })
def add_route_to_db(request): global client try: source_city = request.form.get('source_city') dest_city = request.form.get("dest_city") distance = request.form.get("distance") add_rev = request.form.get("checkbox_rev") db = client['route'] collection = db['routeCollection'] item = { 'source_city': source_city, 'dest_city': dest_city, 'distance': distance } collection.insert_one(item) if add_rev == "add_rev": db = client['route'] collection = db['routeCollection'] item_rev = { 'source_city': dest_city, 'dest_city': source_city, 'distance': distance } collection.insert_one(item_rev) except Exception as e: print("Error in add route to db: " + str(e))
def db_from_backup(filename='mongodb_backup.json'): with open(filename) as fp: backup = json.load(fp) for collection_name in backup: collection: pymongo.collection.Collection = db[collection_name] collection.drop() for document in backup[collection_name]: collection.insert_one(document)
def insertDataInMongoDB(self, beanObject=BeanObject()): try: conn = MongoClient() print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database db = conn.database # Created or Switched to collection names: my_gfg_collection collections = db.my_gfg_collection employee = {"id": getattr(beanObject, beanObject.id), "name": getattr(beanObject, beanObject.name), "street": getattr(beanObject, beanObject.street), "city": getattr(beanObject, beanObject.city), "zip": getattr(beanObject, beanObject.zip), "state": getattr(beanObject, beanObject.state)} # Insert Data result = collection.insert_one(employee) print("Data inserted with record ids", result) # Printing the data inserted cursor = collections.find() for record in cursor: print(record)
def insert_one(self, table, dic): ''' :param table: str 数据库中的集合 :param dic: dict 要插入的字典 :return: 返回一个包含ObjectId类型的对象 ''' collection = self.db[table] rep = collection.insert_one(dic) return rep
def signup(): #get credentials set_name = request.form.get("name") set_email = request.form.get("email") set_password = request.form.get("password") #generate keypair alice = generate_keypair() public_key = alice.public_key private_key = alice.private_key #compile keypair and credentials into a list named "user" user_to_mongo = { "name": set_name, "email": set_email, "password": set_password, "public_key": public_key } #write user cred to a file. user_to_file = { "name": set_name, "email": set_email, "password": set_password, "public_key": public_key, "private_key": private_key } file_name = public_key + ".txt" with open(file_name, 'w') as file: file.write(json.dumps(user_to_file)) file.close() #verify if the email already exist on the db if collection.find_one({"email": user_to_mongo['email']}): return jsonify({"error": "Email address already in use"}), 400 #send "user" list to database collection.insert_one(user_to_mongo) flash("Account successfully created. Return to Login Page.") return send_file(file_name, as_attachment=True)
def add_user_to_mongo(email: str): global client try: db = client['users'] collection = db['usersCollection'] item = {'email': email, 'bookings': []} result = collection.insert_one(item) msg_db = client['msg'] msg_collection = msg_db['msgCollection'] msg_item = {'user_id': str(result.inserted_id), 'messages_array': []} msg_collection.insert_one(msg_item) except Exception as e: print('Exception in add user: ' + str(e))
def add_gsm_run(collection, material, directory, other_info={}, other_files = [], force=False): (db, fs, client) = load_db() collection = db[collection] images = [] energies = [] image_dir = [x for x in os.listdir('scratch') if fnmatch.fnmatch(x, 'IMAGE.*')] image_dir.sort() for dir in image_dir: image = add_dir(collection, material, dir, other_info={}, other_files=[], force=True) print('{ "_id" : "' + str(image) + '" }') images.append(image) energies.append(collection.find_one({'_id' : image})) ts_i = energies.index(max(energies)) return collection.insert_one()
def request_cancel(flight_id: str, date: datetime, email: str): global client try: user_db = client['users'] user_collection = user_db['usersCollection'] usr = user_collection.find_one({'email': email}) cancel_db = client['cancels'] collection = cancel_db['cancelsCollection'] for each in usr['bookings']: if (each['flight_id'] == flight_id and each['date'] == date): item = { 'user_id': usr['_id'], 'flight_id': flight_id, 'e_count': each['e_count'], 'b_count': each['b_count'], 'date': date } d = datetime.date.today() x = int(date[len(date) - 2:]) month = int(date[len(date) - 5:len(date) - 3]) if (x - d.day < 2 and month == d.month): return -2 if (d.month != month and x >= 30 and d.day <= 2): return -2 if (collection.find(item).count() != 0): return -1 result = collection.insert_one(item) print('inserted into db', collection.find_one({'flight_id': flight_id})) return 1 except Exception as e: print('Exception in requesting cancel: ' + str(e))
def add_unique(collection: pymongo.collection.Collection, entity: database.entity.Entity) -> bson.ObjectId: """ Add an object to a collection, if that object does not already exist. Treats the entire serialized object as the key, if only one entry is different, they're different objects. This ONLY works for very simple entities, more complex objects like image collections or image entities have their own save methods that check uniqueness. :param collection: The mongodb collection to insert into :param entity: The object to insert :return: The id of the entity, whether newly added or existing """ if isinstance(entity, dict): s_object = entity else: s_object = entity.serialize() query = query_to_dot_notation(copy.deepcopy(s_object)) existing = collection.find_one(query, {'_id': True}) if existing is not None: return existing['_id'] else: return collection.insert_one(s_object).inserted_id
def add_vasp_run(collection, material, incar, kpoints, potcar, contcar, vasprun, other_info={}, other_files=[], force=False, check_convergence=True, ignore_unconverged=False): """ Adds a VASP run to the database. All input/output files must be provided in the arguments. :param collection: str Name of Collection for Database :param material: str name of Material that will be added to database :param incar: str Location of INCAR file on disk :param kpoints: str Location of KPOINTS file on disk :param potcar: str Location of POTCAR file on disk :param contcar: str Location of CONTCAR (or POSCAR) file on disk :param outcar: str Location of OUTCAR file on disk :param vasprun: str Location of vasprun.xml file on disk :param other_info: dict Other identifying info that will be included in database documet :param other_files: list Other files that should be stored :param force: bool Add run even if duplicate enetry exists :param check_convergence: bool Check for convergence (Default True). If convergence is not found and this is True, do not add run to DB :return: pymongo.results.InsertOneResult """ # Convert input strings to pymatgen file types (where applicable) sets up other files to be stored poscar = Poscar.from_file(contcar) potcar = Potcar.from_file(potcar) incar = Incar.from_file(incar) kpoints = Kpoints.from_file(kpoints) files = [('vasprun', vasprun)] + other_files # Creating document information info = { 'material' : material, 'elements' : poscar.site_symbols, 'potcar' : potcar.symbols, 'potcar_functional' : potcar.functional } info['incar'] = incar # Incar is already a dict info['poscar'] = poscar.as_dict() info['kpoints'] = kpoints.as_dict() vasprun_info = get_vasprun_info(vasprun) if 'energy' in other_info: try: del vasprun_info['energy'] except: print('Energy not found in vasprun.xml, likely unconverged') info.update(vasprun_info) info.update(other_info) # Check for convergence if not info['converged'] and check_convergence: if ignore_unconverged: print('Not Adding Unconverged Run') return continueP = input('Run is not Converged. Add Anyway? (y/n)\n --> ') if continueP == 'y' or continueP == 'yes': pass else: print('Did not Select y/yes to add') return # Open up DB connection and check if entry exists, close if entry does exist (db, fs, client) = load_db() collection = db[collection] if entry_exists(collection, info) and not force: print('Identical Entry Exists') client.close() return False # Prepare Files to be added to DB info['files'] = [] # print(files) for (filename, filepath) in files: if os.path.exists(filepath) and os.path.getsize(filepath) > 0: fileID = add_file(fs, filepath, filename) info[filename] = fileID info['files'].append(filename) else: info[filename] = 'none' result = collection.insert_one(info) print('Added') client.close() return result
def add_interpolation(collection, material, directory, incar, kpoints, potcar, other_info={}, other_files=[], force=False, check_convergence=True, ignore_unconverged=False): potcar = Potcar.from_file(potcar) incar = Incar.from_file(incar) kpoints = Kpoints.from_file(kpoints) files = other_files dirs = [x for x in os.listdir(directory) if os.path.isdir(x) and isint(x)] dirs.sort() poscars = [Poscar.from_file(os.path.join(directory, dir, 'POSCAR')).as_dict() for dir in dirs] energies = [] for dir in dirs: with open(os.path.join(dir, 'energy.txt')) as f: energies.append(float(f.read().split()[0])) info = { 'material': material, 'potcar': potcar.symbols, 'potcar_functional': potcar.functional, 'dirs' : dirs, 'poscars' : poscars, 'energies' : energies } info.update(other_info) info['incar'] = incar # Incar is already a dict info['kpoints'] = kpoints.as_dict() # Check for convergence delta = 0.01 max_e = max(energies) max_i = energies.index(max_e) convergedP = (max_e - energies[max_i-1] <= delta if max_i > 0 else True) and (max_e - energies[max_i+1] <= delta if max_i < len(energies)-1 else True) if not convergedP and check_convergence: if ignore_unconverged: print('Not Adding Unconverged Run') return continueP = input('Run is not Converged. Add Anyway? (y/n)\n --> ') if continueP == 'y' or continueP == 'yes': pass else: print('Did not Select y/yes to add') return # Open up DB connection and check if entry exists, close if entry does exist (db, fs, client) = load_db() collection = db[collection] if entry_exists(collection, info) and not force: print('Identical Entry Exists') client.close() return False # Prepare Files to be added to DB info['files'] = [] # print(files) for (filename, filepath) in files: if os.path.exists(filepath) and os.path.getsize(filepath) > 0: fileID = add_file(fs, filepath, filename) info[filename] = fileID info['files'].append(filename) else: info[filename] = 'none' result = collection.insert_one(info) print('Added') client.close() return result
def save_guide_to_database(guide, collection: collection.Collection): try: collection.insert_one(guide) return True except pymongo.errors.DuplicateKeyError: return False
# vandal def split_generate(vandal_count, non_vandal_count): vandal = 0 while vandal < vandal_count: raw = next(vandal_items) if "revs" in raw and len(raw["revs"]) > 1: yield raw vandal += 1 non_vandal = 0 while non_vandal < non_vandal_count: raw = next(non_vandal_items) if "revs" in raw and len(raw["revs"]) > 1: yield raw non_vandal += 1 print("Splitting items") counter = Counter(100, total_count) for collection_name in TASK: collection = client.wiki[collection_name] for item in split_generate(TASK[collection_name]['vandal'], TASK[collection_name]['good']): item["r"] = random() del item["_id"] collection.insert_one(item) counter.tick()