def CreateMessage(self, to, sender, messageTextSender, messageTextTo): """ Creates a message from to to sender containing the message """ db = firestore.client() user = db.collection('users').document(to) if user.get().to_dict() is None: return "That user does not exists" db = firestore.client() message = { 'participants': [to, sender], 'messages': [{ "timestamp": datetime.datetime.now(), "sender": sender, "messageContents": { to: messageTextTo, sender: messageTextSender } }] } (_, message) = db.collection('messages').add(message) messageId = message.id db = firestore.client() user = db.collection('users').document(to) user.update({'messages': firestore.ArrayUnion([messageId])}) db = firestore.client() user = db.collection('users').document(sender) user.update({'messages': firestore.ArrayUnion([messageId])}) return ""
def assign(taskset, type_, s, cred_file="firebase-admin.json"): """Assign a taskset to a group consisting of (usertype, set). Make sure to upload the taskset first""" db = get_db(cred_file) # 1. add to taskset task_ref = db.collection("taskset").document(taskset) if not task_ref.get().exists: click.echo( "incorrect taskset : %s does not exist. Use `upload` to put the taskset on firebase first." % taskset) return -1 task_ref.update({"groups.%s" % type_: firestore.ArrayUnion([s])}) task_ids = [ r.id for r in db.collection("tasks").where("taskset", "==", taskset).stream() ] # 2. add to group ref = db.collection("groups").document(type_) # 2. a. create group if necessary if not ref.get().exists: ref.set({}) # Need to deal with the condition that this task has already been assigned ref.update({str(s): firestore.ArrayUnion([taskset])})
def addToCart(db): # Here's the plan: ask for name, ask for product name, ask for quantity. # Get the user's name (this will find the cart) name = input("What is your name? ") query = db.collection("orders").where("customer", "==", name).get() # Get the product product = input("What product do you want to add? ") quantity = input("How many %ss do you want? " % product.lower()) quantity = int(quantity) # Get the product ID productID = db.collection("products").where("name", "==", product.capitalize()).get()[0].id if len(query) > 1: cart = pluralCart(query) elif len(query) == 1: cart = query[0].id else: cart = newCart(db, name, productID, quantity) return # Add the item to the cart db.collection("orders").document(cart).update({"products" : firestore.ArrayUnion([productID])}) # Add the quantity to the cart db.collection("orders").document(cart).update({"count" : firestore.ArrayUnion([quantity])})
async def create_project(email, project_name, date): try: print("creating project") batch = db.batch() print("creating batch") project_ref = db.collection("projects").document(project_name) print("created ref") batch.set( project_ref, { "name": project_name, "createdAt": date, "admins": firestore.ArrayUnion([email]), "users": firestore.ArrayUnion([email]), }) print("set project_ref") # TODO: to be changed to something else user_ref = db.collection("profiles").document(email) batch.update( user_ref, { "projects": firestore.ArrayUnion([project_name]), "project": project_name, "lastActive": "date" }) print("added user") batch.commit() return True except: return False
def upload_new_resources(new_resources_df: pd.DataFrame, firestore_resources: Dict[Resource, str], db, sheet: gspread.models.Worksheet) -> List[int]: length = len(new_resources_df.index) log(f"{length} resources to upload") added = 0 uploaded_rows = list() for index, row in new_resources_df.iterrows(): links = Links(row["card link"], row["website"]) date_created = datetime.now().strftime("%Y/%m/%d %H:%M:%S") resource = Resource(title=row["resource name"], reviewed=True, want_support_with=row["want support with"], this_resource_offers=row["this resource offers"], description=row["description"], img=row["image link"], category=row["category"], tags=row["tags"].split(", "), links=links, date_created=date_created, ranking=row["ranking"]) try: category_document = db.collection(FIREBASE_COLLECTION).document( resource.category.replace("/ ", "_")) if resource not in firestore_resources: category_document.update({ "resource_list": firestore.ArrayUnion([resource.title]) }) # Update resource list category_document.update( {"tag_list": firestore.ArrayUnion(resource.tags)}) # Update tag list category_document.collection("resources").add( resource.to_dict()) # Add new document to collection log(f"\tAdded {row['resource name']} to {FIREBASE_COLLECTION}/{category_document.id}" ) else: resource._date_created = category_document.collection( "resources").document(firestore_resources[resource]).get( ).to_dict()["dateCreated"] category_document.collection("resources").document( firestore_resources[resource]).set(resource.to_dict( )) # Update old document in collection log(f"\tUpdated {row['resource name']} in {FIREBASE_COLLECTION}/{category_document.id}" ) except Exception as e: log(f"Error uploading data to firestore. {added} / {length} resources uploaded successfully" ) print(e) return uploaded_rows added += 1 uploaded_rows.append(index + 1) log(f"\nAdded {added} / {length} entries to Firestore") return uploaded_rows
def level_1_analysis(event, context): start_time = time.time() ticker = base64.b64decode(event['data']).decode('utf-8') raw_data = [doc.to_dict() for doc in get_raw_data(ticker)] datatypes = [ "reddit_comment", "reddit_post", "tweet", "stocktwits_post", "yahoo_finance_comment" ] updated_fields = {} for dt in datatypes: sentiment = calculate_sentiment(raw_data, dt) mentions = calculate_mentions(raw_data, dt) updated_fields[dt + "_sentiment"] = sentiment updated_fields[dt + "_sentiment_timestamp"] = time.time() updated_fields[dt + "_mentions"] = mentions updated_fields[dt + "_mentions_timestamp"] = time.time() # update histories db().collection('tickers').document(ticker).collection( 'history').document(dt + '_mentions').set( { "history": firestore.ArrayUnion([{ "timestamp": time.time(), "data": mentions }]) }, merge=True) db().collection('tickers').document(ticker).collection( 'history').document(dt + '_sentiment').set( { "history": firestore.ArrayUnion([{ "timestamp": time.time(), "data": sentiment }]) }, merge=True) # finally we add the yahoo finance data yahoo_finance_fields = [ "quoteType", "bid", "previousClose", "marketCap", "industry", "sector", "logo_url" ] info = yf.Ticker(ticker).info for field in yahoo_finance_fields: updated_fields[field] = info.get(field, "na") # update the main ticker document db().collection('tickers').document(ticker).set(updated_fields, merge=True) return jsonify({"success": True, "time_taken": time.time() - start_time})
def create_league(): auth_login = check_status()["auth_user"]["login"] if not auth_login: return redirect("/login") form = CreateLeagueForm() if form.validate_on_submit(): to_db = form.data print(form.data) email = check_status()["auth_user"]["profile"]["email"] league_name = form.data["league_name"] # add league data to db to_db[ "draft_time"] = f'{to_db["date"].__str__()}-{to_db["time"].__str__()}' for e in [ "csrf_token", "submit", "date", "time", "add_rostering", "add_scoring" ]: to_db.pop(e) db.collection("leagues").document(league_name).set({ "INFO": to_db, "owned": [], "matchup": {}, "standings": {} }) # add member to league doc username = db.collection("users").document( email).get().to_dict()["username"] email_id = Toolbox().email_alphabetify(email) # add email to member list; set player data in league db.collection("leagues").document(league_name).update( {"members": firestore.ArrayUnion([email])}) db.collection("leagues").document(league_name).update( {email_id: { "email": email, "name": f"{username}'s Team" }}) # add league/ current league to user doc db.collection("users").document(email).update({ "leagues": firestore.ArrayUnion([league_name]), "current_league": league_name }) return redirect("/") return render_template("create_league.html", form=form)
def setUp(self): db = firestore.client() # make user in user collection user_data = {'email': '*****@*****.**', 'workspaces': []} db.collection(u'users').document('testUser').set(user_data) ws1_data = {"emoji": "😀", "title": "workspace 1", "description": "first test file!", "date": datetime.datetime.now(), "quiz": []} ws2_data = {"emoji": "😎", "title": "workspace 2", "description": "second test file!", "date": datetime.datetime.now(), "quiz": []} ws3_data = {"emoji": "🙏", "title": "workspace 3", "description": "third test file!", "date": datetime.datetime.now(), "quiz": []} workspace1 = db.collection(u'workspaces').document(u'testWorkspace1') workspace1.set(ws1_data) workspace2 = db.collection(u'workspaces').document(u'testWorkspace2') workspace2.set(ws2_data) workspace3 = db.collection(u'workspaces').document(u'testWorkspace3') workspace3.set(ws3_data) user_ref = db.collection(u'users').document(u'testUser') user_ref.update({u'workspaces': firestore.ArrayUnion([u'testWorkspace1'])}) user_ref.update({u'workspaces': firestore.ArrayUnion([u'testWorkspace2'])}) user_ref.update({u'workspaces': firestore.ArrayUnion([u'testWorkspace3'])}) liked_colors = ["#AF4035", "#AF4D43", "#FFFF99", "#FFFC99", "#1CD3A2", "#1CAC78", "#1F75FE", "#0066CC","#0066FF","#967BB6","#9678B6"] for color in liked_colors: workspace1.update({u'quiz': firestore.ArrayUnion([color])}) generator = palette_generator() #Retrieves algorithm's output in dictionary form. palettes = generator.generate_palettes(liked_colors, None, 30, False) gallery_data = generator.output_to_gallery_cards(palettes) i=1 for card in gallery_data: card_ref = db.collection(u'workspaces').document(u'testWorkspace1').collection(u'galleryCards').document(u'card' + str(i)) card_ref.set(card) i = i +1 card1 = db.collection(u'workspaces').document(u'testWorkspace1').collection(u'galleryCards').document('card1') card1.update({u'heart': True}) card2 = db.collection(u'workspaces').document(u'testWorkspace1').collection(u'galleryCards').document('card2') card2.update({u'heart': True}) card3 = db.collection(u'workspaces').document(u'testWorkspace1').collection(u'galleryCards').document('card3') card3.update({u'heart': True})
def add_albums_to_db(albums): for album in albums: album_ref = db.collection(u'albums').document(u'{0}'.format(album["id"])) album_ref.set({ "album_group": album["album_group"], "album_type": album["album_type"], "external_urls":album["external_urls"], "href":album["href"], "id":album["id"], "images":album["images"], "name":album["name"], "uri":album["uri"] },merge=True) artists_refs = [] for artist in album["artists"]: artist_ref = db.collection(u'artists').document(u'{0}'.format(artist["id"])) artists_refs.append(artist_ref) artist_ref.set(artist,merge=True) artist_ref.set({ 'albums': firestore.ArrayUnion([album_ref]) },merge=True) album_ref.set({ "artists": artists_refs },merge=True)
def tag_add(self, tags): user_ref = db.collection(u'users').document(self.username) # Atomically add a new tag to the 'tags' array field. you can add multiple. user_ref.update({u'tags': firestore.ArrayUnion(tags)}) user_ref.update({u'timestamp': firestore.SERVER_TIMESTAMP})
def model_update(model_l,model_t,ids,loss): pickled_model =model_l.to_json() weights_list = model_l.get_weights() w_l=pickle.dumps(weights_list) weights_list = model_t.get_weights() w_t=pickle.dumps(weights_list) doc_ref = store.collection(u'test').document(ids) try: doc_ref.update({u'model':pickled_model, u'weightsPeriod':w_l ,u'weightsTotal':w_t}) except: doc_ref.set({u'model':pickled_model, u'weightsPeriod':w_l ,u'weightsTotal':w_t}) if(loss==np.nan): loss=0 doc_ref.update({u'loss': firestore.ArrayUnion([loss])}) doc_ref.update({u'dateUpdated': firestore.ArrayUnion([str(datetime.now())])})
def add_stock_to_user(): print('adding new stock for user') new_stock = { 'userId': request.args.get('userId'), 'stockTicker': request.args.get('ticker'), 'sharesHeld': 0, 'balance': request.args.get('amount'), 'initialBalance': request.args.get('amount'), 'minBalance': request.args.get('minBalance'), 'transactions': [], 'autoTrade': True } # update user table user_ref = db.collection("users").document(new_stock['userId']) user = user_ref.get() if user.exists: user_ref.update( {u'stocks': firestore.ArrayUnion([new_stock['stockTicker']])}) else: print('no user found') return jsonify({'success': False}) # update stock table stocks_ref = db.collection("stocks") stocks_ref.document().set(new_stock) return jsonify({'success': True})
def _init_song(self, artist_id, track_id, track_details): """ Adds a new song to firebase for the first time Parameters ---------- artist_id : str - the id of the song's artist track_id : str - the id of the song track_details : dict - the information to add to firebase about the song Returns ------- None """ song_doc_ref = self.song_collection.document(track_id) song_doc_ref.set({ "artist_id": artist_id, "artist_name": track_details["artist_name"], "duration": track_details["duration"], "first_listen": self._get_time_info(track_details["timestamp"]), "song_name": track_details["song_name"], "track_id": track_id, "listens": [] }) artist_doc_ref = self.artist_collection.document(artist_id) artist_doc_ref.update({ "tracks": firestore.ArrayUnion([{"track_id":track_id, "song_name":track_details["song_name"]}]) })
def update_firestore(user_id, db, food_nutrition): current_date = datetime.today().strftime('%d-%m-%Y') user_doc_ref = db.collection('users').document(user_id) doc = user_doc_ref.get() if doc.exists: user_doc_ref.update({ current_date: { "foods": firestore.ArrayUnion([food_nutrition['food_name']]), "total_nutrition": { "calories": firestore.Increment(food_nutrition['calories']), "fat_g": firestore.Increment(food_nutrition['fat_g']), "sodium_mg": firestore.Increment(food_nutrition['sodium_mg']), "protein_g": firestore.Increment(food_nutrition['protein_g']) } } }) else: user_doc_ref.set({ current_date: { "foods": [food_nutrition['food_name']], "total_nutrition": { "calories": food_nutrition['calories'], "fat_g": food_nutrition['fat_g'], "sodium_mg": food_nutrition['sodium_mg'], "protein_g": food_nutrition['protein_g'] } } })
def teacher_signup(): if request.method == 'GET': if 'user' not in session: return render_template('teacher_signup_page.html') else: return redirect('/logout') elif request.method == 'POST': name = request.form['name'] division = request.form['division'].upper() sub = request.form['sub'] year = request.form['year'] sem = request.form['sem'] email = request.form['email'] password = request.form['password'] password2 = request.form['password2'] # check if passwords match if password != password2: flash('The passwords do not match...', 'error') return redirect('/teacher_signup') # check length of pass if len(password) < 6: flash('The password has to be more than 5 characters long...', 'error') return redirect('/teacher_signup') # auth user try: teacher_user = auth.create_user_with_email_and_password( email, password) except: flash( 'This e-mail has already been registered. Please use another e-mail...', 'error') return redirect('/teacher_signup') # e-mail verification auth.send_email_verification(teacher_user['idToken']) # add teacher to db db.collection('teacher').document(email).set({ 'name': name, 'division': division, 'subject': sub, 'year': year, 'sem': sem, 'password': password # firebase auth }) # check for div db.collection('division').document(division).set( { 'year': year, 'sem': sem }, merge=True) db.collection('division').document(division).update( {'teacher_email': firestore.ArrayUnion([email])}) flash( 'Registration successful! Please check your e-mail for verification and then log in...', 'info') return redirect('/teacher_login')
def _init_artist(self, artist_id, track_id, track_details): """ Adds a new artist to firebase for the first time Parameters ---------- artist_id : str - the id of the song's artist track_id : str - the id of the first song played track_details : dict - the information to add to firebase about the artist and first song Returns ------- None """ doc_ref = self.artist_collection.document(artist_id) doc_ref.set({ "artist_id": artist_id, "artist_name": track_details["artist_name"], "first_listen_time": self._get_time_info(track_details["timestamp"]), "first_listen": {"track_id":track_id, "song_name":track_details["song_name"]}, "listen_count": 0, "listen_time": 0, "tracks": [], }) self.artist_list_doc.update({ "list": firestore.ArrayUnion([{"artist_id":artist_id, "artist_name":track_details["artist_name"]}]) })
def moveFile(username, user_ref, current_folder_id, move_from_folder_id, file_id): file_ref = user_ref.collection('files').document(file_id) move_from_folder_ref = user_ref.collection('folders').document( move_from_folder_id) current_folder_ref = user_ref.collection('folders').document( current_folder_id) file_data = file_ref.get().to_dict() current_file_parent = file_data['parent'] file_name = file_data['name'] if current_file_parent == move_from_folder_id: storage_current_file_name = username + '/' + current_file_parent + '/' + file_name storage_new_file_name = username + '/' + current_folder_id + '/' + file_name if duplicate_file_exists(file_name, current_folder_id, username): return 1 #duplicate file exists in new folder. Cannot move file. else: move_from_folder_ref.update( {'files': firestore.ArrayRemove([file_id])}) current_folder_ref.update( {'files': firestore.ArrayUnion([file_id])}) file_ref.update({'parent': current_folder_id}) storage.rename_file(storage_current_file_name, storage_new_file_name) session.pop('movefrom', None) session.pop('movefile', None) else: return 2 # move from and file parent do not match
def handle(self, *args, **options): stocks_colection = db.collection(u'stocks') docs = stocks_colection.stream() for doc in docs: recommendation = make_recommendation(doc.id) amount = recommendation['likelihood'] action = recommendation['action'] prediction = float(recommendation['predictions'][0][0]) test = db.collection(u'recommendations').add({ 'action': action, 'amount': amount, 'date': firestore.SERVER_TIMESTAMP }) stocks_ref = stocks_colection.document(doc.id) print(stocks_ref) stocks_ref.update( {u'recommendations': firestore.ArrayUnion([test[1]])}) db.collection(u'predictions').document(doc.id).set( {'value': prediction})
def uploadNewFile(file, username, user_ref, current_folder_id, current_folder_ref, fileRequest): fileName = secure_filename(file.filename) duplicate_file_id = check_duplicate_file(fileName, user_ref) if duplicate_file_id: return duplicate_file_id display_fileName = file.filename file_extension = fileName.split('.')[1] fileType = get_file_type(file_extension) if fileType == 'None': return 2 if duplicate_file_exists(fileName, current_folder_id, username): return 1 fileSize = upload_file(fileRequest.get('fileUpload'), current_folder_id, username) if fileSize: file_ref = user_ref.collection('files').document() file_ref.set({ 'name': fileName, 'display_name': display_fileName, 'owner': username, 'size': fileSize, 'type': fileType, 'parent': current_folder_id, 'created_date': datetime.datetime.now(), }) current_folder_ref.update( {'files': firestore.ArrayUnion([file_ref.id])}) user_data = user_ref.get().to_dict() updatedFilesCount = int(user_data['files']) + 1 user_ref.update({'files': updatedFilesCount}) updatedStorageUsed = int(user_data['total_storage_used']) + fileSize user_ref.update({'total_storage_used': updatedStorageUsed}) return 0 return 1
def create_new_workspace(): try: if request.method == "POST": workspace_info = request.json userUID = workspace_info['uid'] # Checks if the title of the workspace already exists if not checkDuplicateName(userUID, workspace_info['title']): return jsonify(success=False, workspaceid="") # Create new instance of workspace to add to database workspace = Workspace(workspace_info['title'], workspace_info['description'], workspace_info['emoji'], datetime.datetime.now(), []) db = firestore.client() # Add workspace to workspaces collection new_workspace = db.collection(u'workspaces').document() new_workspace.set(workspace.to_dict()) new_workspace_id = new_workspace.id # Add workspace ID under the user user_ref = db.collection(u'users').document(userUID) user_ref.update( {u'workspaces': firestore.ArrayUnion([new_workspace_id])}) except Exception as ex: print(str(ex)) return jsonify(success=False, workspaceid="") return jsonify(success=True, workspaceid=new_workspace_id)
async def on_raw_reaction_add(payload): # ignore other channels and self if payload.channel_id != botconfig['reactionChannelID'] or payload.user_id == bot.user.id: return # fetch reactionMsg = await reactionChannel.fetch_message(payload.message_id) # resolve emoji reaction = payload.emoji.name idx = regional_indicators.index(reaction) # resolve role em = reactionMsg.embeds[0] data = urlToDict(em.description.splitlines()[0][4:-1]) roleId, categoryId = data[str(idx)] role = reactionMsg.guild.get_role(roleId) # resolve user member = reactionMsg.guild.get_member(payload.user_id) await member.add_roles(role) # update firestore db.collection('user').document(str(payload.user_id)).set({ 'courses': firestore.ArrayUnion([str(categoryId)]) }, merge=True)
def upload(self, db): """ Uploads recipes to database. Params: db: databse to upload to. """ # write recipes to db recipes_ref = db.collection('recipes') for key, recipe in self.recipes.items(): recipe_ref = recipes_ref.document(f'{key}') recipe_ref.set(recipe) # write ingredients to db ingredients_ref = db.collection('ingredients') for ingredient in self.ingredients: ingredient_doc = ingredients_ref.document(ingredient) ingredient_exists = ingredient_doc.get().exists # merge with existing recipes if doc already exists in db if ingredient_exists: ingredient_doc.update( {'recipes': firestore.ArrayUnion(ingredient['recipes'])}) else: ingredient_doc.set(ingredient)
def add_hotels(): hotelData = request.get_json(force=True) doc_ref = db.collection('users').document(hotelData['uid']) # {u'regions': firestore.ArrayUnion([u'greater_virginia'])} doc_ref.update({u'hotels': firestore.ArrayUnion([hotelData['hotelId']])}) return jsonify({"message": 'User flight successfully', "status": 200})
def addSensorDataRow(self, sensorID, data, newData=False): """Push a row of data to a given sensorID. If newData, will also update the machine's sensor metadata using given sensor datarow""" # sensorData = { # '_timestamp': None, # 'batt': 3.654, # 'peak_x': 5.052, # 'peak_y': 4.982, # 'peak_z': 8.565, # 'rms_x': 2.465, # 'rms_y': 2.548, # 'rms_z': 2.859, # 'temp': 65.56, # 'fft':None # } if isinstance(data, list): print("Data must be a single dict containing one row of data") return False # Step one, push sensor data to sensor doc sensorRef = self.db.document("Sensors/{}".format(sensorID)) sensorRef.update({'data': firestore.ArrayUnion([data])}) # Step two, if data is new, update the metadata on ParentMachineDoc if (newData == True): self.updateSensorMetadata(sensorID, data)
def createTodo(userId, title, dueDate, description="", completed=False, isFocus=False, category="Default"): ''' args: userId: the userId associated with the new todo item title: the title of the new todo dueDate: when this todo is due. must conform to datetime.datetime date description: the optional argument of the todo description completed: defaulted to False unless you want to create a todo that is already completed isFocused: defaulted to False, set to true if this is a focused todo category: what category does this belong to? ''' new_todo = { 'title': title, 'description': description, 'completed': completed, 'isFocus': isFocus, 'category': category, 'dueDate': dueDate } db = firestore.client() # Add the todo (_, todo) = db.collection('todos').add(new_todo) # Add the todo ID to the users table db.collection('users').document(userId).update( {'todos': firestore.ArrayUnion([todo.id])})
def update_grade(file): df = pd.read_csv(file) for data in df.values: sid=data[0] grade=str(data[1]) doc_ref = db.collection(u'students').document(str(sid)) doc_ref.update({u'grades': firestore.ArrayUnion([grade])}) return
def addSensorDataRows(self, sensorID, data): """Pushes a List of Sensor Data rows to a specified Sensor Document. Also refreshes the ParentMachine's metadata to its latest sensor datarow""" parentRef = self.db.document("Sensors/{}".format(sensorID)) parentRef.update({'data': firestore.ArrayUnion(data)}) self.refreshSensorMetadata(sensorID)
async def add_channel(project, dashboard, tile, channel): try: ref = db.collection("projects").document(project).collection( "dashboards").document(dashboard).collection("tiles").document( tile) ref.update({"channels": firestore.ArrayUnion([channel])}) return True except: return False
def add_saved(username): target = request.args.get("username") if not target: raise InvalidUsage("Missing 'username' argument") if not profile_exists(target): raise InvalidUsage(f"Profile with username '{target}' does not exist") saved = profile_collection.document(username) saved.update({'saved': firestore.ArrayUnion([target])}) return success()
def updateCatch(): try: data = request.json print(data) print(data['image']) convert(data['image'], data['imageFileName']) imagePath = BASE_PATH + data['imageFileName'] storage.child('fishes/{}'.format(data['imageFileName'])).put(imagePath) fish_url = storage.child('fishes/{}'.format( data['imageFileName'])).get_url(None) # The url of the image sent from app print(fish_url) request_url = 'http://35.240.219.8:8080/register?key=' + fish_url print(request_url) try: predictedData = requests.get(request_url).json() except Exception as e: print(e) print(predictedData) temp = int(''.join( [str(random.randint(0, 999)).zfill(3) for _ in range(2)])) data2 = { 'date': data['date'], 'description': data['description'], 'image': fish_url, 'hours': float(data['hours']), 'latitude': float(data['latitude']), 'longitude': float(data['longitude']), 'name': data['name'] + " " + str(temp), 'weight': float(data['weight']), 'number': data['number'], 'catchId': temp, 'catches': predictedData['fishData'], 'boundedImageUrl': predictedData['boundedUrl'] } ref = userCatches.document(str(data['number'])) ref.update({u'catches': firestore.ArrayUnion([data2])}) print(data2) data1 = { 'latitude': float(data2['latitude']), 'longitude': float(data2['longitude']), 'totalWeight': float(data2['weight']), 'date': data2['date'], 'catchId': data2['catchId'], 'hours': data2['hours'], 'catches': predictedData['fishData'], 'boundedImageUrl': predictedData['boundedUrl'] } print(data1) fishData.document(str(data1['catchId'])).set(data1) return jsonify({"success": True}) except Exception as e: print(e) return jsonify({"success": False}), 400