def post(self): resp = dict(RESPONSE) args = self.parser.parse_args() user_identity = get_jwt_identity() current_user = User.query.get(user_identity) if not current_user: resp['error'] = True resp['msg'] = f'User {user_identity} does\'t exists' resp['data'] = None return resp, 404 exists_name = db.session.query(User.id).filter_by(name_lower=args['name'].lower()).scalar() is not None if exists_name: resp['error'] = True resp['msg'] = f'Notebook with {args["name"]} name exists' resp['data'] = None return resp, 401 notebook = Notebook(name=args['name']) notebook.user = current_user notebook.user_id = current_user.id db.session.add(notebook) db.session.commit() resp['data'] = marshal(notebook, notebook_fields) return resp, 200
def seed_users(): demo = User(username='******', email='*****@*****.**', password='******') demo_notebook = Notebook(title='Default', user_id=1) db.session.add(demo) db.session.commit() db.session.add(demo_notebook) db.session.commit() demo = User(username='******', email='*****@*****.**', password='******') demo_notebook = Notebook(title='JavaScript', user_id=1) db.session.add(demo) db.session.commit() db.session.add(demo_notebook) db.session.commit() demo = User(username='******', email='*****@*****.**', password='******') demo_notebook = Notebook(title='App Academy', user_id=1) db.session.add(demo) db.session.commit() db.session.add(demo_notebook) db.session.commit() demo_notebook = Notebook(title='Recipes', user_id=1) db.session.add(demo_notebook) db.session.commit() demo_notebook = Notebook(title='Fitness', user_id=1) db.session.add(demo_notebook) db.session.commit()
def add_notes(): user = User.query.filter_by(username='******').first() notedir = os.path.abspath(os.path.dirname(__file__)) + '/notes' os.chdir(notedir) for each in os.listdir('.'): nowdir = notedir + '/' + each if os.path.isdir(nowdir): book = Notebook.query.filter_by(name=each).first() if book == None: book = Notebook(name=each) db.session.add(book) db.session.commit() os.chdir(nowdir) for file in os.listdir('.'): div = file.split('.') if len(div) > 1 and (div[1] == 'md'): with open(nowdir + '/' + file, "r")as fin: body = fin.read() note = Post(title=div[0], body=body, author_id=user.id, notebook_id=book.id) db.session.add(note) if file == 'README': with open(nowdir + '/' + file, "r")as fin: text = fin.read() book.descripton = text db.session.add(book) db.session.commit()
def new_notebook(): data = request.json notebook = Notebook(title=data['title'], userId=data['userId'], isDefault=data['isDefault']) db.session.add(notebook) db.session.commit() return notebook.to_dict()
def add_notebook(user_id): notebook_data = json.loads(request.data.decode("utf-8")) notebook = Notebook(name=notebook_data, user_id=current_user.id) db.session.add(notebook) db.session.commit() return jsonify(notebook.to_dict())
def create_notebook(userid): data_title = json.loads(request.data) title = data_title["title"] user_id = userid new_notebook = Notebook(title=title, user_id=user_id) db.session.add(new_notebook) db.session.commit() return new_notebook.to_dict()
def seed_notebooks(): Notebook1 = Notebook(title=' Daily gratitude', user_id=1) Notebook2 = Notebook(title='I love myself because...', user_id=1) db.session.add(Notebook1) db.session.add(Notebook2) db.session.commit()
def seed_notebooks(): notebook_names = [ "Notes", "Shopping List", "To Do", "Homework", "Things to Study", "Things to do", "Don't Forget", "By Tomorrow", "By Monday", "By Tuesday", "By Wednesday", "By Thursday", "By Friday", "Necessities", "IMPORTANT", ] users = User.query.all() x = 10 just_demo = True if not just_demo: while x >= 0: n = Notebook(user_id=users[random.randint(0, len(users) - 1)].id, name=notebook_names[random.randint( 0, len(notebook_names) - 1)]) db.session.add(n) db.session.commit() x -= 1 else: while x >= 0: if x == 10: n = Notebook( user_id=User.query.filter_by(firstName="Demo").first().id, name=notebook_names[random.randint(0, len(notebook_names) - 1)], default_notebook=True) else: n = Notebook( user_id=User.query.filter_by(firstName="Demo").first().id, name=notebook_names[random.randint(0, len(notebook_names) - 1)]) db.session.add(n) db.session.commit() x -= 1
def new_notebook(): data=request.json notebook= Notebook(**data) notebook.updated_at=datetime.datetime.now() db.session.add(notebook) db.session.commit() first_note = Note(owner_id = notebook.user_id, notebook_id= notebook.id, title="", content= "", shortcut = False, updated_at = datetime.datetime.now()) db.session.add(first_note) db.session.commit() return notebook.to_dict(), 200
def register(): form = RegistrationForm() if form.validate_on_submit(): user_email = form.email.data.lower().strip() user_password = form.password.data # Check if user is already registered user = User.query.filter_by(email=user_email).first() if user: # Attempt to log the user in if user.verify_password(user_password): login_user(user) return redirect( request.args.get('next') or url_for('main.index')) flash('Invalid username or password') return redirect(url_for('main.index')) # Register the user user = User(email=form.email.data.lower().strip(), password=form.password.data) db.session.add(user) db.session.commit() default_notebook = Notebook(title='Default', author_id=user.id) db.session.add(default_notebook) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, 'Confirm Your Account', 'auth/email/confirm', user=user, token=token) flash('A confirmation email has been sent.') return redirect(url_for('main.index')) return redirect(url_for('main.index'))
def init_app(cls, app): Config.init_app(app) with app.app_context(): from app.models import db from app.models import User, Notebook db.init_app(app) db.create_all() # Check if User Already Created u = User.query.filter_by(email='*****@*****.**').first() if u: pass else: # Create Admin User u = User(email='*****@*****.**', password='******', confirmed=True) db.session.add(u) db.session.commit() # Create Default Notebook for Admin User nb = Notebook(title='Default Notebook', author_id=u.id) db.session.add(nb) db.session.commit()
def new(): data = MultiDict(mapping=request.json) form = SignUpForm(data) if form.validate(): if User.query.filter(User.email == data["email"]).first() is None: newUser = User(username=data["username"], email=data["email"], password=data["password"]) db.session.add(newUser) db.session.commit() newNotebook = Notebook(title='My Notebook', isDefault=True, userId=newUser.to_dict()["id"]) db.session.add(newNotebook) db.session.commit() user_dict = newUser.to_dict() return {user_dict["id"]: user_dict} else: res = make_response( {"errors": ["A user with that email already exists"]}, 401) return res else: errorset = set() for error in form.errors: errorset.add(form.errors[error][0]) errorlist = list(errorset) res = make_response({"errors": errorlist}, 401) return res
def fill(db): user = User(name='user', email='*****@*****.**') user.set_password('pass') notebook = Notebook(name='First notebook') notebook.user = user notebook.user_id = user.id note = Note(name='First note', description='Note\'s description') note.notebook = notebook note.notebook_id = notebook.id note.user = user note.user_id = user.id db.session.add(user) db.session.add(note) db.session.add(notebook) db.session.commit()
def standardize(): user = User.query.filter_by(username='******').first() notedir = os.path.abspath(os.path.dirname(__file__)) + '/notes' appdir = os.path.abspath(os.path.dirname(__file__)) + '/app/templates/notes' os.chdir(notedir) for each in os.listdir('.'): nowdir = notedir + '/' + each if os.path.isdir(nowdir): os.chdir(nowdir) if os.path.isdir(appdir + '/' + each) == False: os.mkdir(appdir + '/' + each) book = Notebook.query.filter_by(name=each).first() if book == None: book = Notebook(name=each) db.session.add(book) db.session.commit() for file in os.listdir('.'): div = file.split('.') if len(div) > 1 and (div[1] == 'html'): with open(nowdir + '/' + file, "r", encoding="utf-8")as fin: text = fin.readlines() text[0] = """{% extends "base.html" %}\n""" text[1] = """{% block title %}羽儿之家 - {{ title }}{% endblock %}\n""" text[2] = """{% block head %} {{ super() }}\n""" for i in range(len(text)): if text[i].split('\n')[0] == "</head>": text[i] = """{% endblock %}{% block content %}\n""" # text[-7] = """{% endblock %}{% block content %}\n""" text[-1] = """{% endblock %}\n""" with open(appdir + '/' + each + '/' + file, "w", encoding="utf-8") as fout: fout.writelines(text) note = Post.query.filter_by(title=div[0]).first() if note == None: body = "<a href=\"" + str( url_for('notebook.note_html', bookname=each, notename=div[0])) + "\">" + div[0] + "</a>" note = Post(title=div[0], body=body, author_id=user.id, notebook_id=book.id) db.session.add(note) if file == 'README': with open(nowdir + '/' + file, "r", encoding="utf-8")as fin: text = fin.read() book.descripton = text db.session.add(book) db.session.commit()
def post(self): """Create new notebook. Args: (Via Request Parameters) title (string, required): The title of the new Notebook Returns: JSON representation of the newly created notebook """ self.parser.add_argument( 'title', required=True, type=str, help='Missing Title of the Notebook') args = self.parser.parse_args() notebook = NewNotebook( title=args['title'], author_id=g.user.id, ) db.session.add(notebook) db.session.commit() return {'notebook': notebook.to_json()}, 201
def test_get_single_notebook_not_owned(self): someone_else = self.add_other_user() other_nb = Notebook(title='Other Title', author_id=someone_else.id) db.session.add(other_nb) db.session.commit() response = self.client.get(url_for('api.notebook', notebook_id=other_nb.id), headers=self.headers) self.assertTrue(response.status_code == 404)
def new_notebook(): # 1. Get user from session user = current_user # 2. Prepare form data for validation form = NotebookForm() form['csrf_token'].data = request.cookies['csrf_token'] # 3. Validate form data; if invalid return 400 bad request to user if not form.validate_on_submit(): return {"message": "validation_errors", "data": form.errors}, 400 # 4. If valid then extract useful data from form title = form.data['title'] # 5. Create the notebook notebook = Notebook(user_id=user.id, title=title) # 6. Add and commit the notebook db.session.add(notebook) db.session.commit() # 7. Send 201 response to the user return {"message": "success", "data": notebook.to_dict()}, 201
def notebooks(): form = NotebookForm() if form.validate_on_submit(): if Notebook.query.filter_by(title=form.title.data, author_id=current_user.id).first() is None: notebook = Notebook(title=form.title.data, author_id=current_user.id) db.session.add(notebook) db.session.commit() else: flash('A notebook with name {0} already exists.'.format( form.title.data)) return redirect(url_for('.notebooks')) notebooks = Notebook.query.filter_by(author_id=current_user.id, is_deleted=False).all() return render_template('app/notebooks.html', notebooks=notebooks, form=form)
def sign_up(): """ Creates a new user and logs them in """ form = SignUpForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): user = User(username=form.data['username'], email=form.data['email'], password=form.data['password']) db.session.add(user) db.session.commit() notebook = Notebook(title='First Notebook', user_id=user.id) db.session.add(notebook) db.session.commit() login_user(user) data = get_user_data(user.to_dict()) return data return {'errors': validation_errors_to_error_messages(form.errors)}
def test_special_character(self): u = self.add_user() nb = Notebook(title="default", author=u) db.session.add(nb) db.session.commit() n = Note(title="5/14/3", body="test", notebook_id=nb.id, author=u) db.session.add(n) db.session.commit() e = Exporter(u) e.export() note_files = os.listdir("/tmp/{0}".format(u.id)) expected_note_file = "5-14-3.md" self.assertTrue(expected_note_file in note_files)
def test_export_dir_created_when_not_exist(self): u = self.add_user() nb = Notebook(title="default", author=u) db.session.add(nb) db.session.commit() n = Note(title="5/14/3", body="test", notebook_id=nb.id, author=u) db.session.add(n) db.session.commit() # Create Two Exporter Instances e = Exporter(u) e2 = Exporter(u) e.export() e2.export() notebook_dir = os.listdir("/tmp/braindump-export") self.assertEqual(1, len(notebook_dir))
def add_notebook(self, user): nb = Notebook(title="default", author=user) db.session.add(nb) db.session.commit() return nb
from dotenv import load_dotenv load_dotenv() from app import app, db from app.models import User, Notebook, Note with app.app_context(): db.drop_all() db.create_all() demo = User(username='******', email='*****@*****.**', password='******') demo_user_default_notebook = Notebook(title='My Notebook', isDefault=True, userId=1) demo_user_new_notebook = Notebook(title='Novels', isDefault=False, userId=1) demo_user_note = Note( title='The Two Towers', content= "'There is some good in this world, and it's worth fighting for.' - Samwise Gamgee", userId=1, notebookId=2) demo_user_note_2 = Note( title='A Tale of Two Cities', content= '"It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair." — Charles Dickens', userId=1, notebookId=2) demo_user_new_notebook2 = Notebook(title='TV Shows',