예제 #1
0
def edituser(userid=None):
    user = mongo.db.users.find_one({'_id': ObjectId(userid)})
    return render_template('edituser.html', title="Please modify the user", user=user)
예제 #2
0
 def findById(self, id):
     return self.user.find_one({'_id': ObjectId(id), 'is_active': True})
예제 #3
0
def viewBlog(id):
    blog = mongo.db.blogs.find_one_or_404({'_id': ObjectId(id)})
    blog.setdefault('user', getMe())
    if not (current_user and current_user.is_authenticated):
        mongo.db.blogs.update({'_id': ObjectId(id)}, {'$inc': {'viewCount': 1}})
    return render_template('blog.html', blog=blog)
예제 #4
0
def load_user(user_id):
    user = mongo.db.users.find_one({"_id": ObjectId(user_id)})
    return User(username=user['username'],
                password=user['password'],
                id=user['_id'])
예제 #5
0
def deleteCite(id):
    db.delete_one({'_id': ObjectId(id)})
    return jsonify({'message': 'Cite Deleted'})
예제 #6
0
def deleteUser(id):
    #Eliminamos al usuario atravez de ese ID unico
    db.delete_one({'_id': ObjectId(id)})
    #Retornamos al cliente un mensaje
    return jsonify({'msg': 'Usuario eliminado correctamente'})
예제 #7
0
def deleteUser(id):
    db.delete_one({'_id': ObjectId(id)})
    return jsonify({'msg': 'User delete'})
예제 #8
0
def deleteUser(id):
    db.delete_one({'_id': ObjectId(id)})
    return jsonify({'msg': f'user {id} deleted'})
예제 #9
0
def deleteUser(id):
    db.delete_one({"_id": ObjectId(id)})
    return jsonify({"msg": "User deleted"})
    def audits():
        if request.method == 'POST':
            auditData = request.json
            auditMetaData = auditData["auditMetadata"]
            filledAuditForms = auditData["auditForms"]

            allFormsAreValid = validateFilledAuditForms(filledAuditForms)
            allMetadataAreValid = validateAuditMetadata(auditMetaData)

            if not allMetadataAreValid[0]:
                errorDescription = allMetadataAreValid[1]
                return serverResponse(None, 400, errorDescription)

            if not allFormsAreValid[0]:
                errorDescription = allFormsAreValid[1]
                return serverResponse(
                    None, 400,
                    f"Item no. {errorDescription[1]} in '{errorDescription[0]}':\n{errorDescription[2]}"
                )

            auditMetaData_ID, filledAuditForms_ID = generateIDs(
                auditMetaData, filledAuditForms)
            filledAuditForms_ID_processed = post_process_filledAuditForms(
                filledAuditForms_ID)
            auditMetaData_ID_processed = post_process_AuditMetadata(
                auditMetaData_ID)
            auditScore = calculateAuditScore(filledAuditForms_ID_processed)
            auditMetaData_ID_processed["score"] = auditScore

            if auditScore < 1:
                allAnswers = []
                for filledAuditForm in filledAuditForms_ID_processed.values():
                    for answerList in filledAuditForm["answers"].values():
                        allAnswers.extend(answerList)
                percentRect = percentageRectification(allAnswers)

                if percentRect < 1:
                    auditMetaData_ID_processed['rectificationProgress'] = 0

            try:
                result1 = mongo.db.audits.insert_one(
                    auditMetaData_ID_processed)

                if not result1.acknowledged:
                    return serverResponse(
                        None, 503,
                        "Problem uploading audit details to Database")

                for filledForm in filledAuditForms_ID_processed.values():
                    result2 = mongo.db.filledAuditForms.insert_one(filledForm)

                    if not result2.acknowledged:
                        return serverResponse(
                            None, 503, "Problem uploading forms to Database")

            except DuplicateKeyError:
                return serverResponse(None, 400,
                                      "Form has already been uploaded")

            tenant = mongo.db.tenant.find_one(
                {"_id": auditMetaData["tenantID"]})
            if tenant:
                if (expoTokens := tenant.get("expoToken")) != None:
                    for token in expoTokens:
                        try:
                            send_push_message(
                                token, "SingHealth Audits",
                                "Recent audit results ready for viewing")
                        except:
                            continue

                date = auditMetaData_ID_processed['date']

                send_email_notif(
                    app, tenant["email"], "Audit Results",
                    f"""Dear {tenant["name"]},
                        Your recent audit results dated {utc2sgt(date).strftime('%d %B %Y, %I:%M %p')} are ready for reviewing. Please check your app for details.
                        This email is auto generated. No signature is required.
                        You do not have to reply to this email.""")

                notif = {
                    "_id": str(ObjectId()),
                    "userID": tenant["_id"],
                    "auditID": auditMetaData_ID_processed["_id"],
                    "stallName": tenant["stallName"],
                    "type": "post",
                    "message":
                    f"New audit on {utc2sgt(date).strftime('%d/%m/%Y')} ready for viewing.",
                    "readReceipt": False,
                    "notiDate": datetime.now(),
                    "auditDate": date
                }

                result = mongo.db.notifications.insert_one(notif)
                if not result.acknowledged:
                    print("Failed to add POST nofitication to DB")
            return serverResponse(None, 200,
                                  "Forms have been submitted successfully!")
예제 #11
0
def find_lesson(mongo, _id):
    condition = {'_id': ObjectId(_id)}
    data = mongo.db.lessons.find_one(condition)
    return data
예제 #12
0
 def deletar(self, id):
     return self.tabela.delete_one({'_id': ObjectId(id)})
예제 #13
0
 def busca_por_id(self, id):
     return self.tabela.find_one({'_id': ObjectId(id)})
예제 #14
0
def removeuser():
    mongo.db.users.delete_one({'_id': ObjectId(request.form['radio-delete'])})
    return index()
예제 #15
0
def getPerfilPhoto(id):
    data = str(id)
    gen = db.find_one({'_id': ObjectId(data)}, {"_id": 0, "foto": 1})
    return jsonify(gen)
예제 #16
0
def find_block_type(mongo, _id):
    condition = {'using': True, '_id': ObjectId(_id)}
    data = mongo.db.block_type.find_one(condition)
    return data
예제 #17
0
def recuperar(codigo):
    livro = mongo.db.livros.find_one({'_id': ObjectId(codigo)})
    livro['id'] = str(livro['_id'])
    del livro['_id']
    return jsonify(livro)
예제 #18
0
def leave_lfg(lfg_id):
    lfg = LFG(**mongo.db.lfgs.find_one({"_id": ObjectId(lfg_id)}))
    lfg.remove_member(str(current_user.id))
    lfg.update_collection(mongo.db.lfgs)
    return redirect(url_for("lfgs.index"))
예제 #19
0
def user_home(logged_user):

    if 'mail' in session and session['USER'] == True:

        searchmovieform = SearchMovieForm()
        buyticketform = BuyTicketForm()

        if request.form.get(
                "submit", ""
        ) == 'Search_movie' and searchmovieform.validate_on_submit and request.method == 'POST':

            if movies.find_one({"title": searchmovieform.s_movie.data}):

                movie = movies.find({"title": searchmovieform.s_movie.data})
                flash(movie, "movie_info")

            else:

                flash("No movie with this title.", "not_found")

        elif request.form.get(
                "submit", ""
        ) == 'choose_movie' and buyticketform.validate_on_submit and request.method == 'POST':

            ticket_num = buyticketform.t_ticket_num.data
            title = buyticketform.t_title.data
            screening_date = buyticketform.t_screening_date.data
            movie_id = buyticketform.t_movie_id.data
            sits_left = buyticketform.t_sits_left.data

            if int(sits_left) < int(ticket_num):
                flash("Invalid amount of tickets.", "invalid")

            else:
                session['movie_id'] = movie_id
                session['ticket_num'] = ticket_num
                session['title'] = title
                session['screening_date'] = screening_date

                flash(title, 'title')
                flash(screening_date, 'screening_date')
                flash(ticket_num, 'ticket_num')

        elif request.form.get(
                "submit", "") == 'submit_order' and request.method == 'POST':
            movie = movies.find_one({"_id": ObjectId(session['movie_id'])})
            dates = movie['screening_dates']

            for date in dates:

                if date['screening_date'] == session['screening_date']:

                    sits_left = int(date['sits_left']) - int(
                        session['ticket_num'])
                    db.movies.update_one(
                        {
                            "title":
                            session['title'],
                            "screening_dates.screening_date":
                            session['screening_date']
                        },
                        {'$set': {
                            'screening_dates.$.sits_left': sits_left
                        }})

                    db.users.update_one({"mail": session['mail']}, {
                        '$push': {
                            'movies_seen':
                            [session['movie_id'], session['ticket_num']]
                        }
                    })

                    flash("Book successful.", 'book')

        elif request.form.get("submit",
                              "") == 'history' and request.method == 'POST':

            return redirect(url_for("user_history", logged_user=logged_user))

        elif request.form.get("submit",
                              "") == 'log_out' and request.method == 'POST':

            session.clear()
            return redirect(url_for("sign_up_page"))

        return render_template("user_home.html",
                               logged_user=logged_user,
                               searchmovieform=searchmovieform,
                               buyticketform=buyticketform)

    else:
        return render_template("error.html")
예제 #20
0
def find_form_meta(mongo, _id):
    condition = {'using': True, '_id': ObjectId(_id)}
    data = mongo.db.form_meta.find_one(condition)
    return data
예제 #21
0
def deleteUser(id):
    db.find_one_and_delete({'_id': ObjectId(id)})
    return jsonify({'msg': 'User deleted'})
예제 #22
0
def delete(id):
    db.delete_one({'_id': ObjectId(id)})
    respose = jsonify({"message": "user" + id + "borrado"})
    return respose
예제 #23
0
def deleteUser(id):
    db.delete_one({'_id': ObjectId(id)})
    return jsonify({'message': 'Usuario eliminado'})
예제 #24
0
def create(pid):
    exp_form = CreateExperiment_form()
    db = get_db()

    #
    col_gans = (db["gantypes"].find({},{"_id":0}))
    col_exp = db["experiments"] # experiments table
    col_exp.create_index([("name", pymongo.ASCENDING), ("pid", pymongo.ASCENDING)], unique=True) # name unique index

    all_exps = col_exp.find({"pid":pid})

    gan_types = []

    for g in col_gans:
        print("gggg=", g)
        gan_types.append((g["name"], g["name"]))
        
    print(gan_types)
    exp_form.ganType.choices = gan_types
    error = None
    #all_projects = col.find({})

    # load default hyper params
    all_hyperparams = list(get_default_hyperparams(db, pid))

    
    default_para_list = list(get_default_hyperparams(db, pid))

    #print(all_projects)

    #all_projects = list(all_projects)

    # test_project = {"p1":"test1", "p2":"test2"}

    # if this for loop print outputs -
    # web page will not print outputs
    #for p in all_projects:
     #   print(p)

     
    if exp_form.validate_on_submit():

        try:
            if error is None:
                exp_name = exp_form.expName.data
                exp_gan = exp_form.ganType.data
                exp_pro_path = db.projects.find_one({"_id":ObjectId(pid)})["path"]
                print(exp_pro_path)
                print("exp gan=", exp_gan)

                #paths
                exp_path = os.path.join(exp_pro_path, exp_name)
                exp_models_path = os.path.join(exp_pro_path, exp_name + "/models")
                exp_output_path = os.path.join(exp_pro_path, exp_name + "/output")

                os.mkdir(exp_path)
                os.mkdir(exp_models_path)
                os.mkdir(exp_output_path)


                # initialize exp inforamtion
                exp_dict = {"name":exp_name, "type":exp_gan, "pid": pid, "status": "TRAIN", 
                            "path":exp_path, "models_path":exp_models_path, "output_path": exp_output_path , "iters": 0,
                            "current_epoch": 0, "dataloader_size": 0}

                # modify exp_dict with default parameters
                exp_para_list = get_default_exp_para(db, pid)
                print("exp para list=", exp_para_list)

                for exp_para in exp_para_list:
                    print("exp para000=====", exp_para) 
                    exp_dict.update({exp_para["para_key"]: exp_para["para_value"]})

                # insert exp dict
                x = col_exp.insert_one(exp_dict)

                # add additional data to experiments collection

                #addInfoToExp

                # initialize train settings
                dict_settings = {"num_epochs": 0, "checkpoint_interval": 0, "checkpoint_type":"EPOCH"}
                set_train_settings(db, str(x.inserted_id), dict_settings)

                print(x.inserted_id) #out.inserted_id
                # flash(x.inserted_id) # remove this one, if redirect the page
                #return redirect(url_for('experiments.create'))



        except Exception as e:
            flash(e)

    return render_template('experiments/create.html', form=exp_form, pid=pid, exps=all_exps)
예제 #25
0
def find_user(mongo, _id):
    condition = {'using': True, '_id': ObjectId(_id)}
    datas = mongo.db.user.find_one(condition)
    return datas
예제 #26
0
def move_food(id, receive_id):
    if request.method == "GET":
        donate = mongo.db.donate
        identity = ObjectId(str(id))
        # print(identity)
        donateview = list(donate.find({"_id": identity}))
        # print(donateview)
        quantity = donateview[0]["quantity"]
        food = donateview[0]["description"]
        kind = donateview[0]["type"]
        name = donateview[0]["name"]
        email = donateview[0]["email"]
        # print(quantity)
        return render_template('message.html',
                               time=datetime.now(),
                               quantity=quantity,
                               food=food,
                               kind=kind,
                               name=name,
                               email=email,
                               id=identity,
                               receive_id=receive_id)
    else:
        # get the user quantity from form
        user_quantity = request.form['quantity']
        # connect with database and query the database and store variables "89-98"
        donate = mongo.db.donate
        identity = ObjectId(str(id))
        receive_identity = ObjectId(str(receive_id))
        donateview = list(donate.find({"_id": identity}))
        quantity = donateview[0]["quantity"]
        kind = donateview[0]["type"]
        # subtraction = subtract user_quantity from quantity
        remaining = int(quantity) - int(user_quantity)
        # print(remaining)
        # compare it with the quantity that's already in the database
        if remaining > 0:
            # insert new data
            receive = mongo.db.receive
            # receive.insert({'quantity': quantity})
            receive.update({'_id': receive_identity},
                           {"$set": {
                               'quantity': user_quantity
                           }})
            searchreceive = list(receive.find({"_id": receive_identity}))
            receive_name = searchreceive[0]["name"]
            receive_city = searchreceive[0]["city"]
            receive_type = searchreceive[0]["type"]
            receive_email = searchreceive[0]["email"]
            receive_quantity = searchreceive[0]["quantity"]
            for item in searchreceive:
                print(item)
            donate.update({'_id': identity},
                          {"$set": {
                              'quantity': str(remaining)
                          }})
            # donate = mongo.db.donate
            donateview = list(donate.find({"_id": identity}))
            quantity = donateview[0]["quantity"]
            food = donateview[0]["description"]
            kind = donateview[0]["type"]
            name = donateview[0]["name"]
            email = donateview[0]["email"]
            message = "Here's a summary of your receive request: "
            return render_template('receive-confirmation.html',
                                   time=datetime.now(),
                                   quantity=quantity,
                                   food=food,
                                   kind=kind,
                                   name=name,
                                   email=email,
                                   identity=identity,
                                   receive_name=receive_name,
                                   receive_city=receive_city,
                                   receive_type=receive_type,
                                   receive_email=receive_email,
                                   receive_quantity=receive_quantity,
                                   message=message)
        elif remaining == 0:
            # insert new data
            receive = mongo.db.receive
            receive.update({'_id': receive_identity},
                           {"$set": {
                               'quantity': user_quantity
                           }})
            searchreceive = list(receive.find({"_id": receive_identity}))
            receive_name = searchreceive[0]["name"]
            receive_city = searchreceive[0]["city"]
            receive_type = searchreceive[0]["type"]
            receive_email = searchreceive[0]["email"]
            receive_quantity = searchreceive[0]["quantity"]
            donate = mongo.db.donate
            donateview = list(donate.find({"_id": identity}))
            food = donateview[0]["description"]
            donate.remove({"_id": identity})
            message = "Here's a summary of your receive request: "
            return render_template('receive-confirmation.html',
                                   time=datetime.now(),
                                   food=food,
                                   receive_name=receive_name,
                                   receive_city=receive_city,
                                   receive_type=receive_type,
                                   receive_email=receive_email,
                                   receive_quantity=receive_quantity,
                                   message=message)
        else:
            # Show donate quantity
            donate = mongo.db.donate
            donateview = list(donate.find({"_id": identity}))
            donate_quantity = donateview[0]["quantity"]
            return render_template('receive-fail.html',
                                   time=datetime.now(),
                                   donate_quantity=donate_quantity)
예제 #27
0
def bloglist():
    user = getMe()
    condition = {'userId': ObjectId(user.get_id())}
    db_blogs = mongo.db.blogs.find(condition).sort("postTime", DESCENDING)
    blogs = list(db_blogs)
    return render_template('bloglist.html', blogs=blogs)
예제 #28
0
파일: mongo.py 프로젝트: regcam/choosytable
def findone_company(c):
    querykey = client.get(c)
    if querykey == None:
        querykey = ct.find_one({'_id': ObjectId(c)})
        client.set(c, querykey)
    return querykey
예제 #29
0
def deleteBlog(id):
    mongo.db.blogs.remove({'_id': ObjectId(id)})
    flash(u'删除成功')
    return redirect(request.args.get('next') or url_for('index'))
예제 #30
0
def updateUser(id):
    db.update_one({"_id": ObjectId(id)}, {"$set": request.json})
    return {"message": "User updated."}