def seed_journals(): user = User.query.first() demo = Journal(name='My First Journal', color='#ff9800', user_id=user.id) db.session.add(demo) for num in range(2, 18): demo2 = Journal(name=f'Journal {num}', color='#{:02x}{:02x}{:02x}'.format(r(), r(), r()), user_id=user.id) db.session.add(demo2) db.session.commit()
def rent_car(car_id): car = Car.query.get(car_id) journal = Journal.query.all() if request.method == 'POST': car.availability = False if car.availability else True if car.availability == False: car.created = datetime.now() time_begin = datetime.now() time_end = None car.num_book += 1 db.session.add(Journal(car_id=car_id, time_begin=time_begin, time_end=time_end)) db.session.commit() db.session.commit() age_seconds = (datetime.now() - car.created).seconds car.total_time += age_seconds car.total_rent = car.total_time * car.rent_price / 60 db.session.commit() if car.availability == True: journal[-1].time_end = datetime.now() journal[-1].total_cost = (journal[-1].time_end - car.created).seconds * car.rent_price/60 db.session.commit() return render_template('auto_detail.html', car=car)
def add_journal(): patient_name = "JohnDoe" patient = Patient.query.filter_by(username=patient_name).first() req_data = request.get_json() date = req_data.get('date') entry = req_data.get('entry') client = language.LanguageServiceClient() document = types.Document(content=entry, type=enums.Document.Type.PLAIN_TEXT) annotations = client.analyze_sentiment(document=document) score = annotations.document_sentiment.score magnitude = annotations.document_sentiment.magnitude # return('Overall Sentiment: score of {} with magnitude of {}'.format( # score, magnitude)) temp_journal_entry = Journal(date=date, entry=entry, sentiment_scre=score, sentiment_mag=mag, patient_id=patient.id) db.session.add(temp_journal_entry) db.session.commit() return ("{}".format(score))
def test_update_title(self): old_title = "first" new_title = "new" journal = Journal(title=old_title, body="hello") self.assertEqual(old_title, journal.title) journal.update_title(new_title) self.assertEqual(new_title, journal.title)
def test_journal_repr(self): user_id = 1 date = datetime.utcnow journal = Journal(user_id=user_id, date_created=date) journal_repr = "<Journal's user_id={0}, created on {1}>".format( user_id, date) self.assertEqual(journal_repr, repr(journal))
def test_update_body(self): old_body = "first" new_body = "second" journal = Journal(title="test", body=old_body) self.assertEqual(old_body, journal.body) journal.update_body(new_body) self.assertEqual(new_body, journal.body)
def create_journal(): form = JournalForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): new_journal = Journal(name=form.data['name'], color=form.data['color'], user=current_user) db.session.add(new_journal) db.session.commit() return new_journal.to_dict() return {'errors': validation_errors_to_error_messages(form.errors)}
def create_journal(): form = JournalForm() form['csrf_token'].data = request.cookies['csrf_token'] print('----------') if form.validate_on_submit(): data = Journal() print(data, '----------') form.populate_obj(data) data.userId = current_user.id db.session.add(data) db.session.commit() return data.to_dict() return 'invalid info'
def test_get_journal_json(self): id = 1 title = "test title" body = "journal body" date = datetime.utcnow json_expected = { "id": id, "title": title, "body": body, "date_created": date } journal = Journal(id=id, title=title, body=body, date_created=date) self.assertEqual(json_expected, journal.get_journal_json())
def journal_create(c_id): char = Character.query.filter_by(id=c_id).first_or_404() if current_user.id != char.user_id: flash_no_permission() return redirect(url_for(no_perm)) heading = "Create Journal Entry for " + char.name form = JournalForm() form.session.choices = gen_session_choices(char) form.submit.label.text = "Create Journal Entry" if form.validate_on_submit(): journal_entry = Journal(title=form.title.data, content=form.content.data, is_visible=form.is_visible.data, character_id=c_id) if (form.session.data != 0): journal_entry.session_id = form.session.data db.session.add(journal_entry) db.session.commit() flash("Journal entry was created.", "success") return redirect( url_for("character.journal_view", c_id=c_id, j_id=journal_entry.id)) else: # pre-select session if get-param was passed session_id = request.args.get("session") # will do nothing if session_id not an int or not in choices if session_id: try: form.session.data = int(session_id) except: pass return render_template("character/journal_form.html", heading=heading, form=form, title=page_title("Add Journal Entry for '%s'" % char.name))
def save_journal(form, article): option = form.select.data if option == "alt": article.journal = form.alt_journal.data journal = Journal.query.filter_by(journal=article.journal).first() if not journal: abort(500) alt = AltJournal( altjournal=form.value.data.lower().replace(".", ""), journal=journal ) db_add_commit(alt) elif option == "new": article.journal = form.new_journal_full.data new = Journal( journal=form.new_journal_full.data, abbrev=form.new_journal_abbrev.data ) db_add_commit(new) else: abort(500)
def journal_land(): # constructing the tree user_id = session['user_id'] tree = user_tree(user_id) # number of journals journal_no = len(tree) - 1 # form for new inputs of journals form = NewJournal() if form.validate_on_submit(): journal = Journal(name=form.new_journal.data, user_id=user_id) db.session.add(journal) db.session.commit() section = Section(name="my section", journal_id=journal.id) db.session.add(section) db.session.commit() entry = Entry(name="my entry", section_id=section.id, content="this is some content") db.session.add(entry) db.session.commit() user_id = session['user_id'] tree = user_tree(user_id) journal_no = len(tree) - 1 form.new_journal.data = '' return render_template('journal-land.html', tree=tree, journal_no=journal_no, form=form, name=tree[0][1]) return render_template('journal-land.html', tree=tree, journal_no=journal_no, form=form, name=tree[0][1])
def auto_rental(id_auto): # Получаем из таблицы Auto запись по автомобилю (по конкретному ID) auto = Auto.query.get(id_auto) # Получаем неизменяемую часть имени файла данного автомобиля (например, auto2_) img_url = auto.img_url[:6] # Получаем изменяемую часть имени файла данного автомобиля в виде целого числа k = int(auto.img_url[6]) # В dt помещаем текущую дату и время dt = datetime.now() if request.method == 'POST': # Пришел запрос с методом POST (на странице auto_detail.html пользователь нажал на кнопку 'Арендовать / Освободить') # Получаем все записи из таблицы Journal по данному автомобилю (по конкретному ID) journal = Journal.query.filter_by(auto_info=id_auto).all() # Устанавливаем доступность автомобиля в соответствие с тем, на какую кнопку (Арендовать / Свободен) нажал пользователь if auto.dostup == 'Свободен': auto.dostup = 'Занят' button_name = 'Освободить' if not journal: # Если записей в журнале по данному автомобилю не было, то добавляем строку в таблицу Journal db.session.add( Journal(auto_info=id_auto, time_begin=dt, time_end=None, cost=0, quantity=1, time_total=0, cost_total=0)) else: # Добавляем строку в таблицу Journal с учётом данных последней записи по данному автомобилю db.session.add( Journal(auto_info=id_auto, time_begin=dt, time_end=None, cost=0, quantity=journal[-1].quantity + 1, time_total=journal[-1].time_total, cost_total=journal[-1].cost_total)) else: # Меняем доступность автомобиля на "Свободен" и название кнопки на "Арендовать" auto.dostup = 'Свободен' button_name = 'Арендовать' # В последнюю запись по данному автомобилю в таблице Journal вносим данные: время окончания аренды, общее время аренды, стоимость последней аренды и общая стоимость аренды journal[-1].time_end = dt journal[-1].time_total += (dt - journal[-1].time_begin).seconds // 60 journal[-1].cost = ( (dt - journal[-1].time_begin).seconds // 60) * auto.price if journal[-1].cost == 0: journal[-1].cost = auto.price journal[-1].cost_total += journal[-1].cost # сохраняем изменения в базе db.session.commit() # Получаем все записи из таблицы Journal по данному автомобилю (по конкретному ID) journal = Journal.query.filter_by(auto_info=id_auto).all() # Заполняем словарь контекста для отображения на странице auto_detail.html context = { 'id_auto': auto.id, 'name_auto': auto.name, 'price': auto.price, 'in_rent_or_free': auto.dostup, 'yes_or_not': auto.transmission, 'auto_description': auto.description, 'img_url_1': auto.img_url, 'img_url_2': img_url + str((k + 1) // 5 + (k + 1) % 5) + '.jpg', 'img_url_3': img_url + str((k + 2) // 5 + (k + 2) % 5) + '.jpg', 'img_url_4': img_url + str((k + 3) // 5 + (k + 3) % 5) + '.jpg', 'button_name': button_name, 'journal_list': journal } return render_template('auto_detail.html', **context)
def signupValidation(SignupForm): form = SignupForm username = form.username.data firstname = form.firstName.data surname = form.surname.data email = form.email.data password1 = form.password1.data password2 = form.password2.data # Username Validation # username can only contain . _ and alphanumeric regexusername = re.compile( '^(?=.{5,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$') # follow an email format ie. have an @, only allows alphanumerical and certain other characters regexemail = re.compile( '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)') # password minimum 8 character, at least 1 number 1 letter regexpassword = re.compile('^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$') if not regexusername.match(username): return "username must be between 5-20 characters, contain letters, numbers or ._", None elif (User.query.filter_by(username=username).scalar()) is not None: return "username is taken", None # First name Validation elif (len(firstname) < 2 or len(firstname) > 14): # !!!!!!!!!!!!!!!!!!!! fix lower case thingy, lower case usernames still match # func.lower(User.username) == func.lower("GaNyE") return "firstname must be 2 - 20 characters", None elif not firstname.isalpha(): return "firstname can only contain letters", None # Surname Validation elif (len(surname) < 2 or len(surname) > 14): return "surname must be 2 - 20 characters", None elif not surname.isalpha(): return "surname can only contain letters", None # Email Validation elif not regexemail.match(email): return "invalid email", None elif (User.query.filter_by(email=email).scalar()) is not None: return "email is taken", None # Password validation elif password1 != password2: return "passwords do not match", None elif not regexpassword.match(password1): return "passwords must be a minimum of 8 characters, with at least 1 number and letter", None else: password = password1.encode('utf-8') salt = uuid.uuid4().hex.encode('utf-8') password_hash = hashlib.sha512(password + salt).hexdigest() user = User(username=username, firstname=firstname, surname=surname, email=email, salt=salt, password_hash=password_hash) db.session.add(user) db.session.commit() journal = Journal(name="my journal", user_id=user.id) db.session.add(journal) db.session.commit() section = Section(name="my section", journal_id=journal.id) db.session.add(section) db.session.commit() entry = Entry(name="my entry", section_id=section.id, content="this is some content") db.session.add(entry) db.session.commit() # i.e. error = False, so no errors return False, user.id