Ejemplo n.º 1
0
Archivo: routes.py Proyecto: jjkv/pp
def index():
    addform = AddForm(smins='00', emins='00')
    if addform.validate_on_submit() and addform.submit.data:
        sd = str(addform.sday.data)
        st = TP.form_data_to_timestr(addform.shours.data, addform.smins.data)
        et = TP.form_data_to_timestr(addform.ehours.data, addform.emins.data)

        try:
            ed = TP.end_day_validate(sd, st, et)
        except Exception as inst:
            flash(inst.args)
            return redirect(url_for('index'))
        sd, st, ed, et = TP.sanitize_timestr(sd, st, ed, et)

        fi = FreeInterval(author=current_user,
                          start_day=sd,
                          start_time=st,
                          end_day=ed,
                          end_time=et)
        db.session.add(fi)
        db.session.commit()
        flash('time block added, thanks')
        if sd != ed:
            flash('note: time block extends to next day, from '+sd+' to '+ed)
        return redirect(url_for('index'))

    schedule = FreeInterval.query.filter_by(author=current_user)
    if list(schedule):
        return render_template('index.html', title='Home', form=addform, schedule=schedule)
    else:
        return render_template('index.html', title='Home', form=addform)
Ejemplo n.º 2
0
def index():
    addform, delform = AddForm(), DelForm()
    # creating/adding intervals using submitted add form data
    if addform.validate_on_submit() and addform.submit.data:
        fi = FreeInterval(author=current_user,
                          start_day=addform.sd.data,
                          start_time=addform.st.data,
                          end_day=addform.ed.data,
                          end_time=addform.et.data)
        db.session.add(fi)
        db.session.commit()
        flash('Interval added, thanks')
        return redirect(url_for('index'))
    # deleting interval using submitted delete form data
    elif delform.validate_on_submit() and delform.submit.data:
        intervals = FreeInterval.query.all()
        target = filter(lambda x: x.id == delform.interval_id.data, intervals)
        for i in target:
            if i.author == current_user:
                db.session.delete(i)
                flash('Deleting interval')
            else:
                flash("You can't delete someone else's interval.")
        db.session.commit()
        return redirect(url_for('index'))

    schedule = FreeInterval.query.filter_by(author=current_user)
    return render_template('index.html',
                           title='Home',
                           addform=addform,
                           delform=delform,
                           schedule=schedule)
Ejemplo n.º 3
0
def add_product():
    """
    Receive product name and description from form
    Add to database
    Redirect to product listings page
    :return: add products page for GET requests
    """
    form = AddForm()
    if request.method == "POST" and form.validate_on_submit():
        product = models.Product(name=form.name.data,
                                 description=form.description.data)
        # Handle cases when a product's name already exists
        try:
            models.db.session.add(product)
            models.db.session.commit()
            flash("Product added successfully", "success")
            return redirect(url_for("products"))
        except sa.exc.IntegrityError:
            flash("Product name exists", "danger")
    page_title = "DuFarms - Add Product"
    form_type = "Product"
    return render_template("add.html",
                           page_title=page_title,
                           form=form,
                           form_type=form_type)
Ejemplo n.º 4
0
def update_lead(lead_id):
    lead = Lead.query.get_or_404(lead_id)
    if lead.author != current_user:
        abort(403)
    form = AddForm()
    form.tovar.choices = [(x.tovar_name, x.tovar_name) for x in current_user.tovars]
    form.tovar.default = lead.tovar
    if form.validate_on_submit():
        lead.fio = form.fio.data
        # lead.tovar = request.form.get('tovar')
        lead.price = form.price.data
        lead.contact = form.contact.data
        lead.address = form.address.data
        lead.delivery_price = form.delivery_price.data
        lead.cost_price = form.cost_price.data
        lead.profit = form.price.data-form.cost_price.data
        lead.track = form.track.data
        lead.status = form.status.data
        db.session.commit()
        flash('Клиент отредактирован!', 'success')
        return redirect(url_for('add_client'))
    elif request.method == 'GET':
        form.fio.data = lead.fio
        # form.tovar.default = lead.tovar
        form.price.data = lead.price
        form.contact.data = lead.contact
        form.address.data = lead.address
        form.delivery_price.data = lead.delivery_price
        form.cost_price.data = lead.cost_price
        form.track.data = lead.track
        form.status.data = lead.status
    return render_template('client_edit.html', title='Изменить данные клиента',
                           form=form)
Ejemplo n.º 5
0
def add():
    form = AddForm(request.form)
    if form.validate_on_submit():
        p = Examrequest(student_id=form.student_id.data,
                        student_netid=form.student_netid.data,
                        student_name=form.student_name.data,
                        course_id=form.course_id.data,
                        course_name=form.course_name.data,
                        exam_type=form.exam_type.data,
                        exam_format=form.exam_format.data,
                        date=form.date.data,
                        exam_time=form.exam_time.data,
                        exam_csd_time=form.exam_csd_time.data,
                        csd_campus=form.csd_campus.data,
                        csd_building=form.csd_building.data,
                        csd_room=form.csd_room.data,
                        csd_seat=form.csd_seat.data,
                        instructor_netid=form.instructor_netid.data,
                        instructor_name=form.instructor_name.data,
                        instructor_phone=form.instructor_phone.data,
                        instructor_email=form.instructor_email.data,
                        material=form.material.data,
                        accommodations=form.accommodations.data,
                        instructor_notes=form.instructor_notes.data)
        db.session.add(p)
        db.session.commit()
        return render_template('requestAdd.html',
                               form=form,
                               msg="Exam request added!")
    return render_template('requestAdd.html', form=form)
Ejemplo n.º 6
0
def add_location():
    """
    Receive location name and description from form
    Add to database
    Redirect to location listings page
    :return: add locations page for GET requests
    """
    form = AddForm()
    if request.method == "POST" and form.validate_on_submit():
        location = models.Location(name=form.name.data,
                                   description=form.description.data)
        # Handle cases when a location's name already exists
        try:
            models.db.session.add(location)
            models.db.session.commit()
            flash("Location added successfully", "success")
            return redirect(url_for("locations"))
        except sa.exc.IntegrityError:
            flash("Location name exists", "danger")
    page_title = "DuFarms - Add Location"
    form_type = "Location"
    return render_template("add.html",
                           page_title=page_title,
                           form=form,
                           form_type=form_type)
Ejemplo n.º 7
0
def edit_location(name):
    """
    Edit information on the requested location
    :param name:
    :return: location info page
    """
    # Query the database for a location that matches the inputted value
    # sa.func.lower helps with finding the right matches regardless of the case used
    location = models.Location.query.filter(
        sa.func.lower(models.Location.name) == sa.func.lower(name)).first()
    if location:
        form = AddForm(obj=location)
        if request.method == "POST" and form.validate_on_submit():
            location.name = form.name.data
            location.description = form.description.data
            # Handle cases when a location's name already exists
            try:
                models.db.session.commit()
                flash("Location edited successfully", "success")
                return redirect(url_for("locations"))
            except sa.exc.IntegrityError:
                flash("Location name exists", "danger")
        page_title = "DuFarms - Edit Location"
        form_type = "Location"
        return render_template("edit.html",
                               page_title=page_title,
                               form=form,
                               form_type=form_type)
    else:
        abort(404)
Ejemplo n.º 8
0
def additems():
    form = AddForm()
    if request.method == 'POST' and form.validate():
        #save item:
        item = Item()
        save_changes(item, form, new=True)
        flash('Item added successfully')
        return redirect('/index')
    return render_template('additems.html', form=form)
Ejemplo n.º 9
0
def add_client():
    form = AddForm()
    form.tovar.choices = [(x.tovar_name, x.tovar_name) for x in current_user.tovars]
    if form.validate_on_submit():
        ld = Lead(fio = form.fio.data, tovar = request.form.get('tovar'), price = Tovar.query.filter_by(tovar_name=request.form.get('tovar'), user_id=current_user.id).first().tovar_price, contact = form.contact.data, address = form.address.data, delivery_price=form.delivery_price.data, cost_price = Tovar.query.filter_by(tovar_name=request.form.get('tovar'), user_id=current_user.id).first().tovar_cost_price, profit = Tovar.query.filter_by(tovar_name=request.form.get('tovar'), user_id=current_user.id).first().tovar_price - Tovar.query.filter_by(tovar_name=request.form.get('tovar'), user_id=current_user.id).first().tovar_cost_price - form.delivery_price.data*int(request.form.get('who_paid')), track = form.track.data, status = form.status.data, user_id = current_user.id)
        db.session.add(ld)
        db.session.commit()
        flash('Клиент успешно добавлен!')
        return redirect(url_for('add_client'))
    return render_template('clients_manager.html', title='Учёт кленитов', form=form)
Ejemplo n.º 10
0
def addplus(place_id, business, address, lat, long):
    form = AddForm()
    place = {
        'place_id': parse.unquote(place_id),
        'business': parse.unquote(business),
        'address': parse.unquote(address),
        'lat': parse.unquote(lat),
        'long': parse.unquote(long)
    }
    if form.validate_on_submit():
        entry = {
            'item': form.item.data.title(),
            'quantity': form.quantity.data,
            'timestamp': time.time(),
            'place_id': form.place_id.data,
            'business': form.name.data,
            'address': form.address.data,
            'lat': form.lat.data,
            'long': form.long.data
        }
        mycol = mongo.db.entries
        entry_id = mycol.insert_one(entry)
        itemcol = mongo.db.items
        existing_item = list(itemcol.find({'item': form.item.data.title()}))
        if not existing_item:
            new_item = itemcol.insert_one({
                'item': form.item.data.title(),
                'priority': 1,
                'category': None,
                'altnames': [],
                'timestamp': time.time()
            })

            items.append({
                'item_id': form.item.data.title(),
                'item_label': form.item.data.title()
            })
        else:
            itemcol.update_one({'item': form.item.data.title()},
                               {'$inc': {
                                   'priority': 1
                               }})
        flash('New entry added')
        return redirect(
            url_for('addsplash',
                    place_id=parse.quote(form.place_id.data),
                    business=parse.quote(form.name.data),
                    address=parse.quote(form.address.data),
                    lat=parse.quote(form.lat.data),
                    long=parse.quote(form.long.data)))
    return render_template('add.html',
                           form=form,
                           items=items,
                           place=place,
                           title="Add an Update")
Ejemplo n.º 11
0
def add(request):
    if request.method == "GET":
        return render(request, "add.html")
    elif request.method == "POST":
        form = AddForm(request.POST)
        if form.is_valid():
            x = form.cleaned_data["x"]
            y = form.cleaned_data["y"]
            answer = x + y
            return render(request, "add.html", {"x": x, "y": y, "answer": answer})
        else:
            return render(request, "add.html", {"error": form.errors})
Ejemplo n.º 12
0
def add():
    form = AddForm()
    if form.validate_on_submit():
        user1 = User(username=form.username1.data)
        user1.set_password(form.password1.data)
        db.session.add(user1)
        user2 = User(username=form.username2.data)
        user2.set_password(form.password2.data)
        db.session.add(user2)
        db.session.commit()
        flash('Congratulations,Users Registered!')
    return render_template('add.html', title='add', form=form)
Ejemplo n.º 13
0
def add_course():
    form = AddForm()
    user = current_user
    if form.validate_on_submit():
        course = Courses(name=form.name.data,
                         instructor=user.lastname,
                         available="open")
        db.session.add(course)
        db.session.commit()
        return redirect(url_for('course'))
    return render_template("add_course.html",
                           title='add_courses_page',
                           form=form)
Ejemplo n.º 14
0
def add_user():
    form = AddForm()
    
    if form.validate_on_submit():
        
        surname = form.surname.data
        first_name = form.first_name.data
        last_name = form.last_name.data
        file = form.file.data
        
        file_errors, file_data = validation_image(file)
        
        if True in file_errors.values():
            if file_errors["file_size_error"]:
                flash(f'Ошибка. Размер файла превышает 10МБ !')            
            if file_errors["file_extension_error"]:
                flash(f'Ошибка. Расширение файла не соответствует: .jpg, .jpeg, .png')
            return render_template('add.html', title='Добавление пользователя', form=form)

        user = {
            "surname": surname,
            "first_name": first_name,
            "last_name": last_name,
            "photo": file_data
        }
        
        try:
            user_id = db.insert({
                    "surname": surname,
                    "first_name": first_name,
                    "last_name": last_name,
                    "photo": {
                        'filename': file_data['filename'],
                        'file_extension': file_data['file_extension'],
                        'path': file_data['path'],
                        'path_resized': file_data['path_resized'],
                    }
                } 
            )
        except:
            flash(f'Пользователь не создан. Произошла ошибка в базе данных.')
            return render_template('add.html', title='Добавление пользователя', form=form)
        
        save_file(user_id, user['photo'])

        flash(f'Добавлен пользователь: "{surname} {first_name} {last_name}"')
        return redirect(url_for('index'))

    return render_template('add.html', title='Добавление пользователя', form=form)
Ejemplo n.º 15
0
def add(folder):
    path = Config.CONTENT_PATH
    folders = Config.CONTENT_FOLDERS
    form = AddForm()
    if form.validate_on_submit():
        name = form.name.data
        content = form.content.data
        with open(os.path.join(path, folder, name), 'x') as f:
            f.write(content)
        return redirect(url_for('show', folder=folder, name=name))
    elif request.method == 'GET':
        return render_template('form.html',
                               title='Add list',
                               folders=folders,
                               form=form)
Ejemplo n.º 16
0
def add():
    form = AddForm()
    if form.validate_on_submit():
        pay = form.hourly_pay.data * form.hours_worked.data + form.allowance.data - form.deduction.data
        employee = Employee(name=form.name.data,
                            hourly_pay=form.hourly_pay.data,
                            hours_worked=form.hours_worked.data,
                            allowance=form.allowance.data,
                            deduction=form.deduction.data,
                            payroll=pay,
                            user_id=current_user.id)
        db.session.add(employee)
        db.session.commit()
        flash('Congratulations, you added an employee!')
        return redirect(url_for('index'))
    return render_template('add.html', title='Add', form=form)
Ejemplo n.º 17
0
def add_trans():
    form = AddForm()
    user = User.query.filter_by(id=current_user.id).first()
    
    if form.validate_on_submit():
        # handle floating point errors
        amt = form.amount.data
        amt = round(amt*100)/100
        t = Transaction(amount=amt, description=form.description.data, author=user)

        db.session.add(t)
        db.session.commit()

        return redirect(url_for('transaction_history'))

    return render_template('AddTrans.html', form=form)
Ejemplo n.º 18
0
def add():

    form = AddForm()
    if form.validate_on_submit():
        random_number = random.randint(1,
                                       1000)  # creating a randon key or beacon
        user_1 = User(username=form.name.data,
                      infected=False,
                      beacon_key=form.name.data + str(random_number))
        db.session.add(user_1)
        db.session.commit()
        return redirect(url_for("home"))

    return render_template(
        "add.html",
        form=form)  # provinding the user with a form to input his to do list
Ejemplo n.º 19
0
def newTask():
    form = AddForm()
    if form.validate_on_submit():
        task = Tasks(task=form.taskName.data,
                     rating=form.taskImportance.data,
                     dueDate=form.taskDueDate.data,
                     taskTime=form.taskTime.data,
                     id=current_user.id)
        task.set_priority()
        priorities.put((0 - task.get_priority(), (form.taskName.data,
                                                  form.taskDueDate.data)))
        db.session.add(task)
        db.session.commit()
        flash('Task Added')
        return redirect(url_for('index'))
    return render_template('newTask.html', form=form)
Ejemplo n.º 20
0
def add():
    form = AddForm()
    context = dict()
    context['pagename'] = 'Создание новой ссылки'
    context['form'] = form
    if form.validate_on_submit():
        alias = form.alias.data.strip()
        if alias == '':
            cur = g.db.execute('select seq from sqlite_sequence')
            id = cur.fetchone()[0]
            while True:
                id += 1
                hashid = Hashids(form.full.data)
                alias = hashid.encode(id)
                check = check_alias(alias)
                if not check and check is not None:
                    break
        else:
            if len(alias) > 2048 - len(domen):
                flash(
                    'Использовано слишком много символов, введите другой псевдоним',
                    'warning')
                return render_template('add.html', context=context)
            if check_alias_sym(alias):
                flash(
                    'Использованны запрещенные символы, введите другой псевдоним',
                    'warning')
                return render_template('add.html', context=context)
            exp = check_alias(alias)
            if isinstance(exp, int) and not isinstance(exp, bool):
                flash(
                    'Такой псевдоним уже существует, срок действия закончится через {}ч., '
                    'введите другой'.format(
                        int((exp - int(time())) / 3600) + 1), 'warning')
                return render_template('add.html', context=context)
            if exp is None:
                flash(
                    'Такой псевдоним уже существует, срок действия неограничен, введите другой',
                    'warning')
                return render_template('add.html', context=context)
        g.db.execute(
            'insert into entries (full, alias, password, expiration) values (?, ?, ?, ?)',
            (form.full.data, alias, form.password.data, int(time()) + 86400))
        g.db.commit()
        flash('Успешно создано, короткая ссылка - ' + domen + alias, 'success')
    return render_template('add.html', context=context)
Ejemplo n.º 21
0
def add_record():
    form = AddForm()
    if form.validate_on_submit():
        # Extract values from form
        city_name = form.city.data
        population = form.population.data

        # Create a city record to store in the DB
        c = City(city=city_name, population=population)

        # add record to table and commit changes
        db.session.add(c)
        db.session.commit()

        form.city.data = ''
        form.population.data = ''
        return redirect(url_for('add_record'))
    return render_template('add.html', form=form)
Ejemplo n.º 22
0
def add_student():
    form = AddForm()
    if form.validate_on_submit():
        if Student_Profile().student_exist(form.id_number.data):
            flash('Student with id number {} already exist.'.format(
                form.id_number.data))
            redirect(url_for('add_student'))
        else:
            lastname = form.lastname.data.title()
            firstname = form.firstname.data.title()
            gender = form.gender.data
            id_number = form.id_number.data
            course = form.course.data
            Student_Profile().add_students(lastname, firstname, gender,
                                           id_number, course)
            flash('Student added Successfully!')
            redirect(url_for('add_student'))
    return render_template('add_student.html', form=form, title='Add')
Ejemplo n.º 23
0
def add_name():
    form = AddForm()
    data = pd.read_csv('./app/outputs/patient_list.csv')
    
    if form.validate_on_submit():
        new_row = [{'Last_Name':form.surname.data,
                    'First_Name':form.forename.data,
                    'DOB':form.DOB.data,
                    'Address1':form.Address1.data,
                    'Address2':form.Address2.data,
                    'Town':form.Town.data,
                    'County':form.County.data,
                    'Post_Code':form.Post_code.data,
                    'Location':'0',
                    'Date_filed':numpy.nan}]
        data = data.append(new_row)
        data.to_csv('./app/outputs/patient_list.csv', index=False)
        return redirect('/file')
    return render_template('add_name.html', form=form)
Ejemplo n.º 24
0
def addbook():
    form = AddForm()

    if form.validate_on_submit():
        title = form.title.data
        author_name = form.author.data
        price = form.price.data

        if author_name.lower() not in [aut.name.lower() for aut in Author.query.all()]:
            author = Author(name=author_name)
            db.session.add(author)
        else:
            author = Author.query.filter_by(name=author_name).first()

        newbook = Book(title=title, author=author, price=price)
        db.session.add(newbook)
        db.session.commit()
        return redirect('/')
    return render_template('add_book.html', form=form)
Ejemplo n.º 25
0
def add_files():
    form = AddForm()
    if form.validate_on_submit():
        new_file = fileTable(Station_Code=form.Station_Code.data,
                             Station_Name=form.Station_Name.data,
                             Location=form.Location.data,
                             Month=form.Month.data,
                             Day=form.Day.data,
                             Year=form.Year.data,
                             Weather=form.Weather.data,
                             PC=form.PC.data,
                             Client=form.Client.data,
                             Type=form.Type.data,
                             Longitude=form.Longitude.data,
                             Latitude=form.Latitude.data)
        db.session.add(new_file)
        db.session.commit()
        flash('New File Created!', 'success')
        return redirect(url_for('index'))
    return render_template('add_files.html', form=form)
Ejemplo n.º 26
0
def add():
    user = current_user.uname
    form = AddForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            title = form.title.data
            author = current_user.uname
            head = form.head.data
            body = form.body.data
            user = User.query.filter(User.uname == author).first()
            author_id = user.uid
            post = Post(title=title,
                        author_id=author_id,
                        head=head,
                        body=body,
                        user=user)
            db.session.add(post)
            db.session.commit()
            return redirect('/admin/')
        return '提交失败'

    return render_template('admin/add.html', form=form, user=user)
Ejemplo n.º 27
0
def edit_files(ID):
    articles = fileTable.query.filter_by(ID=ID).one()

    #Get form
    form = AddForm(obj=articles)

    if form.validate_on_submit():
        form.populate_obj(articles)
        articles.Station_Code = form.Station_Code.data
        articles.Station_Name = form.Station_Name.data
        articles.Location = form.Location.data
        articles.Month = form.Month.data
        articles.Day = form.Day.data
        articles.Year = form.Year.data
        articles.Weather = form.Weather.data
        articles.PC = form.PC.data
        articles.Client = form.Client.data
        articles.Type = form.Type.data
        articles.Longitude = form.Longitude.data
        articles.Latitude = form.Latitude.data
        db.session.commit()
        flash('File Updated!', 'success')
        return redirect(url_for('index'))
    return render_template('edit_files.html', form=form, articles=articles)
Ejemplo n.º 28
0
def view():
    add_form = AddForm()
    delete_form = DeleteForm()

    if add_form.validate_on_submit(): # Valid AddForm request
        book_records = session['book_records']
        book_record = {}
        book_record['brn'] = add_form.brn.data
        book_record['title'] = add_form.title.data
        book_record['author'] = add_form.author.data
        book_record['classification'] = add_form.classification.data
        book_records.append(book_record)
        book_records = sorted(book_records, key=itemgetter('classification', 'title'))
        session['book_records'] = book_records
        db_update_book_records(book_records, session['identifier'])
        return redirect('/view')

    if delete_form.validate_on_submit(): #Valid DeleteForm request
        if not 1 <= delete_form.number.data <= len(session['book_records']):
            return redirect('/view')
        book_records = session['book_records']
        book_records.pop(delete_form.number.data - 1)
        session['book_records'] = book_records
        db_update_book_records(book_records, session['identifier'])
        return redirect('/view')

    book_records = session['book_records'] or \
                   sorted(db_retrieve_book_records(session['identifier']),
                          key=itemgetter('classification', 'title'))
    session['book_records'] = book_records
    split_book_records = book_records_by_classification(book_records)

    return render_template('view.html',
                           add_form=add_form,
                           delete_form=delete_form,
                           split_book_records=split_book_records)