def clear_database_except_admin(): basepath = path.dirname(__file__) filepath = path.abspath( path.join(basepath, "..", "..", "config/admin.json")) with open(filepath) as f: admin_json = json.load(f) for usr in userList: if usr.email != admin_json.get('email'): usr.delete() for glr in galleriesList: if glr.owner != admin_json.get('_id'): glr.delete() for rct in reactionList: rct.delete() for exh in exhibitList: exh.delete() tempId = generate() Galleries(_id=tempId, owner=adminData.get('_id'), createdAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764), updatedAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764)).save()
def test_generate(mocker): mocker.patch("time.time", return_value=1429506585.786924) object_id = generate() assert object_id.startswith("55348a19") assert re.match("^[0-9a-f]{24}$", object_id)
def post(self): nombre = "Sin nombre" height = "2.0 m" weight = "10.0 kg" if 'name' in request.form: nombre = request.form['name'] if 'height' in request.form: height = request.form['height'] if 'weight' in request.form: weight = request.form['weight'] id = generate() iden = obtenerSiguiente() myquery = { "_id": ObjectId(id), "id": iden, "name": nombre, "height": height, "weight": weight } db[base].insert_one(myquery) return jsonify({ "_id": id, "name": nombre, "height": height, "weight": weight })
def receive(): received = port_plc.read(14).decode(errors='ignore') print(received) isPlcNone = re.search(r'01FF(.{8})', received) if (isPlcNone == None): plc_serial_reset() return 0 val = {} val[0] = (isPlcNone.group(0)) val[1] = (isPlcNone.group(1)) hexa = str(f(val[1])) toint = (int(hexa, 16)) print(toint) output3 = "n0.val=" + str(toint) port_lcd.write(output3.encode()) port_lcd.write(ary_end) bson_id = generate() tfa20_time = time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] record = { "_id": bson_id, "Time": tfa20_time, "name": "Calvin", "Output": toint } collection.insert_one(record) return toint
def receive(): received = port_plc.read(14).decode(errors='ignore') print(received) isPlcNone = re.search(r'01FF(.{8})', received) if (isPlcNone == None): plc_serial_reset() return 0 val = {} val[0] = (isPlcNone.group(0)) val[1] = (isPlcNone.group(1)) hexa = str(f(val[1])) toint = (int(hexa, 16)) print(toint) # --------------------------------------- # Show output in TJC LCD # --------------------------------------- output3 = "n0.val=" + str(toint) port_lcd.write(output3.encode()) port_lcd.write(ary_end) # --------------------------------------- # Save output in mongoDB # --------------------------------------- bson_id = generate() tfa20_time = time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] record = { "_id": bson_id, "Time": tfa20_time, "name": "Calvin", "Output": toint } #logging.info('mongodb insert begin.') #mongo_return = collection.insert_one(record) #print(mongo_return) #logging.info('mongodb insert complete.{}'.format(mongo_return)) cmd1 = "ping 10.0.105.158 -c 1" server_ack = str(os.system(cmd1)) print("Ping server ack : " + server_ack) if (server_ack == "0"): collection.insert_one(record) print('mongodb insert complete.') logging.info('mongodb insert complete.') else: print( 'mongodb insert fail.~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!' ) logging.info( 'mongodb insert fail.~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!~~~~~~~~!!!!!!!!' ) return toint
def save_user_mongo(map_user, collection): for user in map_user.values(): user_exist = collection.find_one({"$and":[{"user": user}, {"app_id": app_id}]}) user_id = generate() if user_exist == None: data = { "user_id": user_id, "user": user, "app_id": app_id } collection.insert_one(data)
def create_random_candidate(): """ Function that creates a random candidate based on a name list and a last name list :return: Returns a JSON candidate object """ # Declaring random indexes based on length of the arrays (number from 0 to length - 1). first_name = names.get_first_name() last_name = names.get_last_name() # Creating full name string based on first and last names. full_name = f'{first_name.title()} {last_name.title()}' # Creating email string based on first and last names. email = f'{first_name.lower()}.{last_name.lower()}@email.com' # Generating JWT token from function using email as key. token = generate_jwt_token(email) # Generating object id. id = generate() # Generating random address from library. address = get_random_address() # Writing json candidate object candidate = { '_id': id, 'first_name': first_name, 'last_name': last_name, 'email': email, 'role': get_random_role(), 'branch': get_random_location(), 'personal_token': token, 'college': get_random_college(), 'street_address': address['street'], 'city': address['city'], 'country': address['country'], 'postcode': address['postcode'], 'status': get_random_status(), 'hasInterviewVideo': get_random_boolean(), 'hasUpdatedCv': get_random_boolean(), 'password': f'{first_name.lower()}123' } return candidate
def post(self): _id = generate() id = "" name = "" img = "" # _type = "" height = "" weight = "" # candy = "" # candy_count = "" # egg = "" # spawn_chance = "" # avg_spawns = "" # spawn_time = "" # multipliers = "" # weaknesses = "" # next_evolution = "" if (request.get_json() is not None): if 'id' in request.get_json(): id = request.get_json()['id'] if 'name' in request.get_json(): name = request.get_json()['name'] if 'height' in request.get_json(): height = request.get_json()['height'] if 'weight' in request.get_json(): weight = request.get_json()['weight'] pokemon = { "_id": ObjectId(_id), "id": id, "name": name, "height": height, "weight": weight } db.samples_pokemon.insert_one(pokemon) pokemonjson = { "_id": (_id), "id": id, "name": name, "height": height, "weight": weight } return jsonify(pokemonjson)
def put_file(self, file: bytes) -> ObjectId: id = ObjectId(random_object_id.generate()) self.files[id] = file return id
def add_ml_model(self, ml_model: MlModel) -> ObjectId: id = ObjectId(random_object_id.generate()) ml_model._id = id self.models[id] = ml_model return id
def create_users_and_galleries(number_of_users): does_admin_exist = 0 if len(userList) > 0: for usr in userList: if usr.email == adminData.get('email'): does_admin_exist = 1 if does_admin_exist == 0: Users( _id=adminData.get('_id'), administrator=True, name=adminData.get('name'), email=adminData.get('email'), password=adminData.get('password'), ).save() tempId = generate() Galleries(_id=tempId, owner=adminData.get('_id'), createdAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764), updatedAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764)).save() for usr in range(number_of_users): rnd = random.randint(0, 3) img_path = 'g' if rnd == 0: img_path = 'b' elif rnd == 1: img_path = 'r' path1 = os.path.abspath( os.path.join(os.path.dirname(__file__), '../..', 'public//img//user_' + img_path + '.png')) img = Image.open(path1) img_b64 = im_2_b64(img) tempId = generate() Users(_id=tempId, city="Krakow", country="Russia", administrator=False, date_of_birth=datetime.datetime(2020, 2, 2, 6, 35, 6, 764), name="user00" + str(usr), email="user00" + str(usr) + "@gmail.com", password= "******", avatar=base64.decodebytes(img_b64), createdAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764), updatedAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764)).save() userList_local = Users.objects() for usr in range(number_of_users): tempId = generate() Galleries(_id=tempId, owner=userList_local[usr + 1]._id, createdAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764), updatedAt=datetime.datetime(2020, 2, 2, 6, 35, 6, 764)).save() galleriesList_local = Galleries.objects() return [userList_local, galleriesList_local]
import random_object_id post_request_body = { "user_id": random_object_id.generate(), "date": "2021-09-09", "items": [{ "name": "lifting", "details": [{ "intensity": "very_light", "exercise": "test", "weight": 100, "reps": 1, "sets": 1 }], "comments": "unit tests❗❗" }] } get_request_params = { "returnDetails": True, "returnIdsOnly": False, "returnSummary": False, "returnComments": False, }
def api_1(): if request.method == 'GET': lista = [] array_pokemon = db.samples_pokemon.find().sort('id') for pokemon in array_pokemon: lista.append({ '_id': str(pokemon.get('_id')), # pasa a string el ObjectId 'id': pokemon.get('id'), 'name': pokemon.get('name'), 'img': pokemon.get('img'), 'type': pokemon.get('type'), 'height': pokemon.get('height'), 'weight': pokemon.get('weight'), 'candy': pokemon.get('candy'), 'candy_count': pokemon.get('candy_count'), 'egg': pokemon.get('egg'), 'spawn_chance': pokemon.get('spawn_chance'), 'avg_spawns': pokemon.get('avg_spawns'), 'spawn_time': pokemon.get('spawn_time'), 'multipliers': pokemon.get('multipliers'), 'weaknesses': pokemon.get('weaknesses'), 'next_evolution': pokemon.get('next_evolution'), }) return jsonify(lista) elif request.method == 'POST': _id = generate() id = "" name = "" img = "" # _type = "" height = "" weight = "" # candy = "" # candy_count = "" # egg = "" # spawn_chance = "" # avg_spawns = "" # spawn_time = "" # multipliers = "" # weaknesses = "" # next_evolution = "" if (request.get_json() is not None): if 'id' in request.get_json(): id = request.get_json()['id'] if 'name' in request.get_json(): name = request.get_json()['name'] if 'height' in request.get_json(): height = request.get_json()['height'] if 'weight' in request.get_json(): weight = request.get_json()['weight'] pokemon = { "_id": ObjectId(_id), "id": id, "name": name, "height": height, "weight": weight } db.samples_pokemon.insert_one(pokemon) pokemonjson = { "_id": (_id), "id": id, "name": name, "height": height, "weight": weight } return jsonify(pokemonjson)
def api_1(): if request.method == 'GET': if len(request.args) != 0: myquery = {} if request.args.get('name') != None: nombre = request.args.get('name') myquery['name'] = nombre if request.args.get('height') != None: height = request.args.get('height') myquery['height'] = height if request.args.get('weight') != None: weight = request.args.get('weight') myquery['weight'] = weight try: lista = [] pok = db[base].find(myquery) for p in pok: lista.append({ 'id': str(p.get('_id')), 'name': p.get('name'), 'height': p.get('height'), 'weight': p.get('weight') }) return jsonify(lista) except: return jsonify({'error': 'Not Found'}), 404 else: lista = [] pok = db[base].find().sort('name') for p in pok: lista.append({ 'id': str(p.get('_id')), 'name': p.get('name'), 'height': p.get('height'), 'weight': p.get('weight') }) return jsonify(lista) elif request.method == 'POST': nombre = "Sin nombre" height = "2.0 m" weight = "10.0 kg" if 'name' in request.form: nombre = request.form['name'] if 'height' in request.form: height = request.form['height'] if 'weight' in request.form: weight = request.form['weight'] id = generate() iden = obtenerSiguiente() myquery = { "_id": ObjectId(id), "id": iden, "name": nombre, "height": height, "weight": weight } db[base].insert_one(myquery) return jsonify({ "_id": id, "name": nombre, "height": height, "weight": weight })