def create_note(): data= request.json note = Note(**data) note.updated_at = datetime.datetime.now() db.session.add(note) db.session.commit() return note.to_dict(), 200
def add(): if request.args.get('notebook'): notebook = Notebook.query.filter_by( id=int(request.args.get('notebook'))).first() form = NoteForm(notebook=notebook.id) else: form = NoteForm() form.notebook.choices = [(n.id, n.title) for n in Notebook.query.filter_by( author_id=current_user.id, is_deleted=False).all()] if form.validate_on_submit(): note = Note(title=form.title.data, body=form.body.data, notebook_id=form.notebook.data, author=current_user._get_current_object()) db.session.add(note) db.session.commit() tags = [] if not len(form.tags.data) == 0: for tag in form.tags.data.split(','): tags.append(tag.replace(" ", "")) note.str_tags = (tags) db.session.commit() return redirect(url_for('main.notebook', id=note.notebook_id)) return render_template('app/add.html', form=form)
def save_day(): req = request.get_json() title = req.get('title') data = req.get('data', '') if not title: abort(400) username = get_jwt_identity() if not username: abort(401) user = User.query.filter_by(username=username.lower()).first() if not user: abort(400) enc_date = aes_encrypt(title) note = user.notes.filter_by(title=enc_date).first() if not Note: # Check old encryption enc_date = aes_encrypt_old(title) note = user.notes.filter_by(title=enc_date).first() if not note: note = Note(user_id=user.uuid, name=title, text=data, is_date=True) else: note.text = data db.session.add(note) db.session.flush() db.session.commit() return jsonify(note=note.serialize), 200
def add(): if request.args.get('notebook'): notebook = Notebook.query.filter_by( id=int(request.args.get('notebook'))).first() form = NoteForm(notebook=notebook.id) else: form = NoteForm() form.notebook.choices = [ (n.id, n.title) for n in Notebook.query.filter_by( author_id=current_user.id, is_deleted=False).all()] if form.validate_on_submit(): note = Note( title=form.title.data, body=form.body.data, notebook_id=form.notebook.data, author=current_user._get_current_object()) db.session.add(note) db.session.commit() tags = [] if not len(form.tags.data) == 0: for tag in form.tags.data.split(','): tags.append(tag.replace(" ", "")) note.str_tags = (tags) db.session.commit() return redirect(url_for('main.notebook', id=note.notebook_id)) return render_template('app/add.html', form=form)
def note_add(): user = g.user form = request.form r = {'data': []} if form['note'] is not Note: wordbook = Wordbook.query.filter_by(book_name=user.learning_wordbook, user_id=user.id).first() word = Word.query.filter_by(wordbook_id=wordbook.id, learned=False, word=form['word']).first() note_form = { 'note': form['note'], 'word': word.word, 'word_id': word.id, 'learner': g.user.username } note = Note(note_form) note.save() r['success'] = True r['data'] = note.json() else: r['success'] = False message = '输入为空' r['message'] = message return json.dumps(r, ensure_ascii=False)
def test_can_read_note(self): note = Note(note_name="Hey!", pub_date=timezone.now()) self.assertEqual(note.id, None) note.save() self.assertNotEqual(note.id, None) retrieved = Note.objects.get(note_name="Hey!") self.assertEqual("Hey!", retrieved.note_name)
def audio_message(update, context): from app import create_app app = create_app(config_class=Config) app.app_context().push() audio = update.message.voice.get_file() audio = audio.download_as_bytearray() rand = str(random.randint(100000,1000000)) filename = rand+"note.ogg" with open(os.path.join(Config.UPLOAD_FOLDER, filename), 'wb') as f: f.write(audio) subprocess.run(['ffmpeg', '-i', os.path.join(Config.UPLOAD_FOLDER, filename), os.path.join(Config.UPLOAD_FOLDER, filename.replace('ogg', 'wav'))]) with sr.AudioFile(os.path.join(Config.UPLOAD_FOLDER, filename.replace('ogg', 'wav'))) as s: r = sr.Recognizer() txt = r.listen(s) text = r.recognize_google(txt, language = 'ru-RU') note = Note() note.text = text note.sound_file = filename note.creator = User.query.filter_by(tg_id=update.message.chat_id).first().id db.session.add(note) db.session.commit() bot.send_message( chat_id=update.message.chat_id, text=f"Заметка сохранена" )
def create_note(userid, notebookid): new_note = Note(title="Untitled", user_id=userid, notebook_id=notebookid, content="") db.session.add(new_note) db.session.commit() return new_note.to_dict()
def add_note(userDataObject): note_data = json.loads(request.data.decode("utf-8")) note = Note(title = note_data["Title"], text = note_data["Text"], notebook_id = note_data["notebook_id"]) db.session.add(note) db.session.commit() return jsonify(note.to_dict())
def new_note(): data = request.json note_content = requests.get('https://api.quotable.io/random').json() note = Note(content=note_content["content"], title=f"{note_content['author']} said...", userId=data['userId'], notebookId=data['notebookId']) db.session.add(note) db.session.commit() return note.to_dict()
def test_sea(): from app.models import Note Note.create_table() pwx = _app.extensions.pwx servicerclass = _app.servicers.HelloServicer[1] stub = Stub(servicerclass()) assert stub.return_normal(None) assert pwx.database.is_closed() Note.drop_table()
def addnote(request, pk): form = dict() form['form'] = AddNote() form['icons'] = Icon.objects.all() form['directory'] = Genre.objects.get(id=pk) note_name = Note.objects.all() form['notes'] = note_name form['username'] = auth.get_user(request).username form['parent'] = Genre.objects.get(id=pk) form['tree'] = Genre.objects.filter(parent_id=pk, user_id=auth.get_user(request).id) form['tree_files'] = Note.objects.filter(parent_id=pk, user_id=auth.get_user(request).id) if request.POST: new_add_note = Note() new_add_note.note_name = request.POST['note_name'] new_add_note.note_text = request.POST['note_text'] new_add_note.user = User.objects.get(username=auth.get_user(request).username) new_add_note.parent = Genre.objects.get(id=pk) if new_add_note.valid(): new_add_note.save() for icon in request.POST.getlist('checkbox'): new_add_note.icon_name.add(Icon.objects.get(id=icon)) form['saved'] = 'Сохранено в базе данных' else: form['saved'] = 'Название заметки обязательное поле' return render(request, 'app/boot_index.html', form) return render(request, 'app/add.html', form)
def new_entry(): """ Returns the "main" log view page when used as a GET request or creates and stores a new log entry when called as a POST """ if request.method == "GET": return render_template("api.html") new_log = Note() new_log = new_log_entry(new_log) new_log.user = User.query.filter_by(username=session['username']).first() db.session.add(new_log) db.session.commit() flash('Congratulations on creating a new entry!') return redirect(url_for('index'))
def game(game_id): """ Render the game template on the /game route """ return render_template( 'game.html', game=Game.from_id(game_id), owned_games=id_query_to_set(current_user.get_owned_games(True)), wished_games=id_query_to_set(current_user.get_wished_games(True)), noted_games=id_query_to_set(current_user.get_noted_games(True)), freq_games=id_query_to_set(current_user.get_freq_games(True)), ratings=Note.from_both_ids(current_user.id, game_id), freqs=Prefer.from_both_ids(current_user.id, game_id), average_grade=Note.average_grade(game_id), messages=Note.get_messages(game_id, 5))
def fake_notes(): """Add some fake notes""" year, month = 2018, 1 u1 = User.query.all()[0] u2 = User.query.all()[1] fake = Faker() for i in range(20): fake_date = datetime(year, month, randint(1, 31), randint(0, 23), randint(0, 59)) note = Note(content=fake.text().replace('\n', '\n\n'), timestamp=fake_date) note.author = u1 if randint(0, 1) else u2 db.session.add(note) db.session.commit()
def create_note(id): """ Handle request to /inquiries/<id>/create-note route \n Create a new note and store in the DB """ form = NoteForm() inquiry = Inquiry.query.get_or_404(id) if form.validate_on_submit(): note = Note(title=form.title.data, description=form.description.data, inquiry=inquiry, user=current_user) try: db.session.add(note) db.session.commit() flash('You have successfully added a new note.', 'info') # redirect to the client's page return redirect(url_for('inquiry.read_inquiry', id=id)) except: flash('Error creating the note', 'error') # load note form template return render_template('inquiries/note-form.html.j2', form=form, title='Add Note')
def archive_note(pk): try: Note.query.filter_by(id=pk).filter_by(author=current_user).update( {'archived': True}) #Note.get(Note.id == pk) except Note.DoesNotExist: return render_template('404.html') db.session.commit() flash('Your note has been deleted!!') form = PostForm() if form.validate_on_submit(): note = Note(body=form.note.data, author=current_user) db.session.add(note) db.session.commit() flash('Your note has been received!') return redirect(url_for('index')) page = request.args.get('page', 1, type=int) notes = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('index', page=notes.next_num) \ if notes.has_next else None prev_url = url_for('index', page=notes.prev_num) \ if notes.has_prev else None return render_template('index.html', title='Home', form=form, notes=notes.items, next_url=next_url, prev_url=prev_url)
def new_notes(id): form = NoteForm(request.form) form.author.choices = [(volunteer.id, volunteer.name) for volunteer in Volunteer.query.all()] form.author.choices.insert(0, (-1, 'Select your name')) openhour = Openhour.query.get(id) if request.method == 'POST' and form.validate(): new_note = Note(openhour_id=id, author=form.author.data, customers=form.customers.data, body=form.body.data, shopping=form.shopping.data) shopping_list = new_note.shopping db.session.add(new_note) db.session.commit() flash( 'Notes created for %s. Thank you for volunteering tonight!' % openhour.date.strftime('%B %d'), 'success') return redirect(url_for('index')) return render_template('notes_form.html', form=form)
def writenote(): form = PostForm() if len(Note.query.all()) == 0: newnote_id = 1 else: newnote_id = Note.query.order_by(Note.id.desc()).first().id + 1 tags = Tag.query.all() if form.validate_on_submit(): tags_id = form.tags.data.split(',') content_md = form.content_md.data content_html = md2html(content_md) note = Note(id=newnote_id, title=form.title.data, content_html=content_html, content_md=content_md, category_id=form.category.data, date=datetime.now()) if tags_id != ['']: for tag_id in tags_id: tag = Tag.query.filter_by(id=tag_id).first() note.tags.append(tag) db.session.add(note) db.session.commit() flash('发布成功') return redirect(url_for('auth.index')) return render_template('admin/writenote.html', form=form, tags=tags, newnote_id=newnote_id)
def add_note(year=None, month=None, day=None): create_at = datetime.now(app.config['TIMEZONE']) timestamp = create_at if year and month and day: if date(year, month, day) > create_at.date(): return jsonify(status_code=1) # 补签 if date(year, month, day) < create_at.date(): timestamp = datetime(year, month, day, 23, 59, 59) content = request.form.get('content', None) if not content: return jsonify(status_code=1) author = User.query.get(session.get('user_id')) note = Note(content=content, author=author, timestamp=timestamp, create_at=create_at) db.session.add(note) db.session.commit() other = User.query.filter(User.id != session.get('user_id')).first() if other.email: notification(other.email, note, '添加了一条动态', '{}于{}添加了动态:<p>{}') return jsonify(status_code=0)
def post(self): body = request.json db.session.add(Note(body['title'], body['content'])) db.session.commit() return Response(json.dumps({ 'result': 'success' }), mimetype='application/json')
def mynotes(): form = NoteForm() noteID = request.args.get('noteID') #if creating a new note if form.validate_on_submit() and noteID is None: if 'submit' in request.form: note = Note(body=form.note.data, due_date=form.due_date.data, author=current_user, priority=form.priorityLevel.data, title=form.title.data) #changed db.session.add(note) db.session.commit() return redirect(url_for('mynotes')) notes = current_user.get_notes().all() #will run when click submit after editing an existing note noteData = Note.query.filter_by(id=noteID).first() if form.validate_on_submit() and noteID is not None: if 'submit' in request.form: noteData.body = form.note.data noteData.due_date = form.due_date.data noteData.priority = form.priorityLevel.data noteData.author = current_user noteData.title = form.title.data #changed db.session.commit() return redirect(url_for('mynotes')) #This puts the existing notes data into the note field for editing if noteID is not None: form.note.data = noteData.body form.due_date.data = noteData.due_date form.priorityLevel.data = noteData.priority form.title.data = noteData.title #display note to edit return render_template('mynotes.html', form=form, notes=notes)
def edit_note(id, data): note = Note.find_by_id(id) not_exists(note) not_authorized(note.folder.author.name) if data.get('title'): if Note.find_by_title(data['title']): abort(409, 'Title exists') note.title = data['title'] if data.get('body'): note.body = data['body'] db.session.commit() return {'message': 'Operation Success'}, 200
def create_note(): if not request.json: abort(400) user = User.query.filter(User.username == 'ruturaj').first() note = Note(body=request.json['body'], author=user) db.session.add(note) db.session.commit() return make_response({}, 204)
def submit_note(): form = NoteForm() if form.validate_on_submit(): flash('Message {} received! Redirecting ...'.format(form.message.data)) note = Note(name=form.name.data, message=form.message.data) db.session.add(note) db.session.commit() return redirect(url_for('index')) return render_template('note.html', title='Leave a note', form=form)
def add_note(): form = NoteForm() if form.validate_on_submit(): count = len(set(form.body.data.split())) note = Note(body=form.body.data, counter_unique_words=count) db.session.add(note) db.session.commit() return redirect(url_for('add_note')) return render_template('add_note.html', title='Add Note', form=form)
def add_note(self, notebook, user): n = Note(title="5/14/3", body="test", notebook_id=notebook.id, author=user) db.session.add(n) db.session.commit() return n
def delete_note(id): note = Note.find_by_id(id) not_exists(note) not_authorized(note.folder.author.name) db.session.delete(note) db.session.commit() return {'message': 'Operation success'}, 201
def add_game_note(game_id): note = request.form.get("note", False) message = request.form.get("message-text", False) db.session.add( Note(user_id=current_user.id, game_id=game_id, note=note, message=message)) db.session.commit() return redirect(request.referrer)
def clone_commentary(doc_id, user_id, type_id): com_to_be_cloned = Commentary.query.filter( Commentary.user_id == user_id, Commentary.doc_id == doc_id, Commentary.type_id == type_id).first() if not com_to_be_cloned: return make_404() is_not_allowed = forbid_if_not_in_whitelist( current_app, Document.query.filter(Document.id == doc_id).first()) if is_not_allowed: return is_not_allowed teacher = current_app.get_current_user() teacher_com = Commentary.query.filter(Commentary.user_id == teacher.id, Commentary.type_id == type_id, Commentary.doc_id == doc_id).first() if teacher_com is None: teacher_com = Commentary(doc_id=doc_id, user_id=teacher.id, content=com_to_be_cloned.content) else: # replace the teacher's com content teacher_com.content = com_to_be_cloned.content # remove the old teacher's notes # for note in teacher_com.notes: # # MUST delete commentary_has_note and not the note itself # # (since the latest might be used somewhere else)! for chn in CommentaryHasNote.query.filter( CommentaryHasNote.commentary_id == teacher_com.id).all(): db.session.delete(chn) # clone notes for chn_to_be_cloned in com_to_be_cloned.commentary_has_note: note = Note(type_id=chn_to_be_cloned.note.type_id, user_id=teacher.id, content=chn_to_be_cloned.note.content) db.session.add(note) db.session.flush() teacher_com.transcription_has_note.append( CommentaryHasNote(ptr_start=chn_to_be_cloned.ptr_start, ptr_end=chn_to_be_cloned.ptr_end, note_id=note.id, commentary_id=teacher_com.id), ) db.session.add(teacher_com) try: db.session.commit() except Exception as e: db.session.rollback() print(str(e)) return make_400(str(e)) return make_200()
def new_note(): global KAFENUT_NOTES if request.method=='GET': return render_template('new_note.html',kafenut_notes=KAFENUT_NOTES) #if receiving a json data=json.loads(request.get_data()) resp=dict(success=False) if data['title']!='new_note': resp['text']='错误:无效的访问方法!' return json.dumps(resp) #if making a new folder if data['new_folder']==True: if len(g.user.folders) >= 5: resp['text']='错误:文件夹数目过多!' return json.dumps(resp) if '.' in data['note_path']: resp['text']='错误:文件夹名中存在非法字符!' return json.dumps(resp) if len(data['note_path'])>20: resp['text']='错误:文件夹名过长!' return json.dumps(resp) if not data['note_path'] in g.user.folders: g.user.folder=g.user.folder+'.'+data['note_path'] db.session.add(g.user) #save the note note=Note(title=data['note_title'],upload_time=datetime.utcnow(),author=g.user,logic_folder=data['note_path']) path=save_note(data['note_title'],data['note_body'],g.user.nickname) if path=='文件已存在!' or path=='文件过大!': resp['text']=path else: note.path=path db.session.add(note) db.session.commit() #reload KAFENUT_NOTES if note.author.nickname=='菜姬李': KAFENUT_NOTES=Note.query.filter_by(author_id=ADMIN.id) resp['success']=True resp['text']='Upload successfully!' resp['url']=url_for('note',note_id=note.id,nickname=note.author.nickname) flash('Nice upload!') return json.dumps(resp)
def create_note(): data = request.get_json() note = Note.query.filter(Note.title == data['title'], Note.player_id == data["playerId"]).first() try: if note: note.title = data['title'] note.text = data['note'] note.player_id = data["playerId"] db.session.commit() return jsonify({'note': note.to_dict()}) else: new_note = Note(title=data['title'], text=data['note'], player_id=data["playerId"]) db.session.add(new_note) db.session.commit() return jsonify({'note': new_note.to_dict()}) except: return jsonify({'hit': False})
def ticket_detail(ticket_id): ticket = Ticket.query.filter_by(id=ticket_id).first_or_404() if g.user.admin or g.user.id == ticket.user.id: form = forms.TicketUpdateForm() if form.validate_on_submit(): ticket.status = form.status.data ticket.priority = int(form.priority.data) if form.text.data != '': note = Note() note.text = form.text.data ticket.conversation.append(note) flash('New Content posted to ticket %s' % ticket.id, 'success') db.session.merge(ticket) db.session.commit() flash('Ticket Status Updated', 'success') else: form.status.data = ticket.status form.priority.data = str(ticket.priority) for error in form.errors: flash('%s: %s' % (error, form.errors[error]), 'danger') return render_template('ticket_detail.html', ticket=ticket, form=form, title='Ticket: %s' % ticket.id)
def addnote(request): form = dict() form['form'] = AddNote() note_name = Note.objects.all() form['notes'] = note_name if request.POST: new_add_note = Note() new_add_note.note_name = request.POST['name'] new_add_note.note_text = request.POST['text'] new_add_note.user = User.objects.get(username=auth.get_user(request).username) new_add_note.save() form['saved'] = 'Сохранено в базе данных' return render(request, 'app/index.html', form) return render(request, 'app/add.html', form)