def load_fixtures(): users = [ {"username": "******", "password": "******"}, {"username": "******", "password": "******"}, {"username": "******", "password": "******"} ] with db.atomic(): User.insert_many(users).execute() u1 = User.get( User.username == "user1") u2 = User.get( User.username == "user2") todos = [(u1, 'Vivamus tempus'), (u1, 'lorem ac odio'), (u1, 'Ut congue odio'), (u1, 'Sodales finibus'), (u1, 'Accumsan nunc vitae'), (u2, 'Lorem ipsum'), (u2, 'In lacinia est'), (u2, 'Odio varius gravida'), (u2, 'Extra entry to trigger pagination 1'), (u2, 'Extra entry to trigger pagination 2'), (u2, 'Extra entry to trigger pagination 3'), (u2, 'Extra entry to trigger pagination 4'), (u2, 'Extra entry to trigger pagination 5')] with db.atomic(): for u, d in todos: Todo.insert(user=u, description=d, completed=False).execute()
def todos_POST(): if not session.get('logged_in'): return redirect('/login') if len(request.form.get('description')) < 1: flash('The Description field cannot be blank') return redirect('/todo') u = User.get(User.id == session['user']['id']) Todo.create(user=u, description=request.form.get('description', ''), completed=False) flash("Todo added") return redirect('/todo')
def todos(): if not session.get('logged_in'): return redirect('/login') requested_page = int(request.args.get('page', 1)) todos_count = Todo.select().join(User).where(User.id == session['user']['id']).count() pages = [] i=0 for index in list(range(0, todos_count, 5)): i+=1 pages.append(i) todos_page = Todo.select().join(User).where(User.id == session['user']['id']).paginate(requested_page, 5) return render_template('todos.html', todos=todos_page, pages=pages, requested_page = requested_page)
def todo_delete(id): if not session.get('logged_in'): return redirect('/login') todo = Todo.select().join(User).where(Todo.id == id, User.id == session['user']['id']).get() todo.delete_instance() flash("Todo deleted") return redirect('/todo')
def create(): user_data = json.loads(request.data) db_user_data = None # If an X-HTTP-Method-Override flag is in the header # the request is a PUT if "X-HTTP-Method-Override" in request.headers and request.headers["X-HTTP-Method-Override"] == "PUT": method = request.headers[OVERRIDE_KEY] db_user_data = session.query(Todo).filter_by(id=user_data["id"]) if db_user_data: db_user_data = db_user_data[0] db_user_data.todo_done() else: db_user_data = Todo(user_data["text"], user_data["tag"], user_data["done"]) session.add(db_user_data) session.commit() return json.dumps(db_user_data.to_obj())
def todo_complete(id): if not session.get('logged_in'): return redirect('/login') todo = Todo.select().join(User).where(Todo.id == id, User.id == session['user']['id']).get() todo.completed = True todo.save() return redirect('/todo')
def todo(id): if not session.get('logged_in'): return redirect('/login') try: todo = Todo.select().join(User).where(Todo.id == id, User.id == session['user']['id']).get() return render_template('todo.html', todo=todo) except DoesNotExist: flash("Todo not found") return redirect('/todo')
def list_movie(id): """ This feature lists the metadata for a movie""" if not session.get('logged_in'): return redirect('/login') try: todo = Todo.select().join(User).where(Todo.id == id, User.id == session['user']['id']).get() return render_template('todo.html', todo=todo) except DoesNotExist: flash("Todo not found") return redirect('/todo')
def add_todo(): todo_name = request.form.get("todo_name") todo_description = request.form.get("todo_description") todo_start = request.form.get("todo_start") todo_end = request.form.get("todo_end") todo_visible = request.form.get("todo_visible") is not None todo_erasable = request.form.get("todo_erasable") is None res = ajax_response() with session_cm() as db: td = Todo(user_id=current_user.user_id, todo_name=todo_name, todo_description=todo_description, todo_start=todo_start, todo_end=todo_end, todo_visible=todo_visible, todo_erasable=todo_erasable) db.add(td) db.commit() res.update(data=td.to_dict()) return jsonify(res)
def create(): # Controller de création d'un todo avec un PUT form = TodoForm(request.form) if request.method == 'PUT' and form.validate(): db_session = connect(True) newTodo = Todo() newTodo.title = form.title.data newTodo.done = False db_session.add(newTodo) db_session.commit() todo_data = { "id": newTodo.id, "title": newTodo.title, "done": newTodo.done } data = { "form": form, "todo_html": render_template( "todo.html", **todo_data ).replace("\n", "") } js_response = make_response( render_template("list.js", **data).replace("\n", "") ) js_response.headers["Content-Type"] = "text/javascript; charset=utf-8" return js_response return "", 400
def delete(todo_id): """ <int:todo_id> 的方式可以匹配一个 int 类型 int 指定了它的类型,省略的话参数中的 todo_id 就是 str 类型 这个概念叫做 动态路由 意思是这个路由函数可以匹配一系列不同的路由 动态路由是现在流行的路由设计方案 """ # 通过 id 删除 routes t = Todo.delete(todo_id) # 引用蓝图内部的路由函数的时候,可以省略名字只用 . # 因为我们就在 routes 这个蓝图里面, 所以可以省略 routes # return redirect(url_for('todo.index')) return redirect(url_for('.index'))
def todo_json(id): if session.get('logged_in'): try: todo = Todo.select().join(User).where(Todo.id == id, User.id == session['user']['id']).get() output = api_body_object('todo', todo._data) status_code = 200 except DoesNotExist: output = api_body_error(2, 'Object not found') status_code = 404 else: output = api_body_error(1, 'Authentication required') status_code = 401 resp = app.make_response(json.dumps(output)) resp.mimetype = "application/json" resp.status_code = status_code return resp
def add(): # 得到浏览器发送的表单, 浏览器用 ajax 发送 json 格式的数据过来 # 所以这里用新增加的 json 函数来获取格式化后的 json 数据 form = request.get_json() # 创建一个 todo u = current_user() t = Todo(form) t.user_id = u.id t.save() # 把创建好的 todo 返回给浏览器 return jsonify(t.json())
def add(request): # 得到浏览器发送的表单, 浏览器用 ajax 发送 json 格式的数据过来 # 所以这里我们用新增加的 json 函数来获取格式化后的 json 数据 form = request.json() # 创建一个 todo u = current_user(request) t = Todo(form) t.user_id = u.id t.save() # 把创建好的 todo 返回给浏览器 return json_response(t.json())
def update(request): ''' 处理POST后 /todo/edit 的路由函数 ''' uname = current_user(request) u = User.find_by(username=uname) if request.method == "POST": ''' Body: 'title=aaa&id=1' ''' form = request.form() todo_id = int(form.get('id', '-1')) t = Todo.find_by(id=todo_id) t.title = form.get('title', t.title) t.save() # 任务完成 return redirect('/todo')
def index(req: Request, res: Response): """ todo 首页的路由函数 """ try: user_id = int(req.query['userId']) except: return res.json({ 'code': 400, 'msg': '参数错误', }) todos = Todo.find_all(user_id=user_id) res.json({ 'code': 0, 'msg': '', 'data': [t.json() for t in todos], })
def add(req: Request, res: Response): """ 用于增加新 todo 的路由函数 """ u = current_user(req) if u is None: return res.json({ 'code': 401, 'msg': 'Unauthorized', }) form = req.body t = Todo.add(form, u.id) res.json({ 'code': 0, 'msg': '添加 todo 成功', 'data': t.json(), })
def add(request): """ 接受浏览器发过来的添加 todo请求 添加数据并返回给浏览器 :param request: :return: json格式数据 """ # 得到浏览器发送的json格式数据 # 浏览器用 ajax 发送 json 格式的数据过来 # 所以这里我们用Request对象中新增加的json函数 来获取 格式化后的 json 数据(字典) form = request.json() # 创建一个 todo项 t = Todo.new(form) # 把创建好的 todo返回给 浏览器 # 下面的json方法是todo对象的json方法 是把对象变成字典 # 然后json_response将字典转化成字符串 return json_response(t.json())
def findDeletedTodos(self): idx = self.old_version_line_start deleted_todo_dict = {} for line in self.old_version: if line[0] == "-" and self.containsTodo(line): index = Patch.findTodo(line) todo_text = line[index:] deleted_todo = Todo(headline=todo_text, committed_by=self.committed_by, account=self.account, line_number=idx, filepath=self.file_path, text=todo_text, repo=self.repo) deleted_todo_dict[idx] = deleted_todo idx += 1 return deleted_todo_dict
def test(): connection = pymysql.connect( host='localhost', user='******', password=database_password, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: cursor.execute('DROP DATABASE `web`') cursor.execute('CREATE DATABASE `web` CHARACTER SET utf8mb4') cursor.execute('USE `web`') cursor.execute(User.sql_create) cursor.execute(Session.sql_create) cursor.execute(Todo.sql_create) cursor.execute(Comment.sql_create) cursor.execute(Weibo.sql_create) connection.commit() connection.close() form = dict( username='******', password='******', ) User.register_user(form) u, result = User.login_user(form) assert u is not None, result session_id = random_string() form = dict( session_id=session_id, user_id=u.id, ) Session.new(form) s: Session = Session.one(session_id=session_id) assert s.session_id == session_id form = dict( title='test todo', user_id=u.id, ) t = Todo.add(form, u.id) assert t.title == 'test todo'
def add(request): """ 接受浏览器发过来的添加 todo 请求 添加数据并返回给浏览器 """ currentuserid = current_user(request) user = User.find(currentuserid) log('add微博的用户以及id ', user, currentuserid) # 得到浏览器发送的 json 格式数据 # 浏览器用 ajax 发送 json 格式的数据过来 # 所以这里我们用新增加的 json 函数来获取格式化后的 json 数据 form = request.json_loads() form['user_id'] = int(currentuserid) log('add微博的form表单 ', form) # 创建一个 todo t = Todo.new(form) # 把创建好的 todo 返回给浏览器 return json_response(t.json())
def todos(): data = request.form if request.method == "POST": todo = Todo(data["task"]) db.session.add(todo) print("create new record") db.session.commit() return redirect("/") elif request.method == "PUT": id = data["todo_id"] t = db.session.query(Todo).filter_by(id == id).first() t.task = "fooo" db.session.add(t) db.session.commit() elif request.method == "DELETE": return "hello" return "a"
def edit(request): """ todo 首页的路由函数 """ # 课5作业2:由于权限判断都放在了装饰器,所以这里直接写edit逻辑 # 替换模板文件中的标记字符串 todo_id = int(request.query['id']) t = Todo.find_by(id=todo_id) body = template('todo_edit.html') body = body.replace('{{todo_id}}', str(todo_id)) body = body.replace('{{todo_title}}', str(t.title)) # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中 headers = { 'Content-Type': 'text/html', } header = response_with_headers(headers) r = header + '\r\n' + body return r.encode()
def edit(request): """ todo edit 的路由函数 """ # 得到当前编辑的 todo的 id todo_id = int(request.query.get('id', -1)) t = Todo.find_by(id=todo_id) uid = current_user(request) u = User.find_by(id=uid) # 验证用户id是否相同 if t.user_id != u.id: return redirect('/login') # 替换模板文件中的标记字符串 body = template('todo_edit.html') body = body.replace('{{ todo_id }}', str(t.id)) body = body.replace('{{ todo_task }}', str(t.task)) return http_response(body)
def delete_todo(request): """ todo delete 的路由函数 """ # 得到当前编辑的 todo的 id todo_id = int(request.query.get('id', -1)) t = Todo.find_by(id=todo_id) uid = current_user(request) u = User.find_by(id=uid) # 验证用户id是否相同 if t.user_id != u.id: return redirect('/login') if t is not None: # 删除 todo t.remove() return redirect('/todo')
def findDeletedTodos(self): deleted_todos = {} for i, line in enumerate(self.new_version): if line[0]=="-" and containsTodo(line): index = findTodo(line) todo_text = line[index:] line_num = self.old_version_start_line + i new_todo = Todo(headline = todo_text, committed_by = self.committed_by, account = self.account, line_number = line_num, filepath = self.file_path, text = todo_text, repo = self.repo) new_todos[line_num] = new_todo return deleted_todos
def index(request): """ todo 首页的路由函数 """ u = current_user(request) # todos = Todo.all() todos = Todo.find_all(user_id=u.id) # 下面这行生成一个 html 字符串 # 课5作业4,添加了时间的显示 todo_html = """ <h3> 添加时间: {}, 更新时间:{} <br> {} : {} <a href="/todo/edit?id={}">编辑</a> <a href="/todo/delete?id={}">删除</a> </h3> """ # 课5作业4,添加了时间的显示 import datetime def dt(t): return datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S') todo_html = ''.join([ todo_html.format( dt(t.created_time), dt(t.updated_time), t.id, t.title, t.id, t.id ) for t in todos ]) # 替换模板文件中的标记字符串 body = template('todo_index.html') body = body.replace('{{todos}}', todo_html) # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中 headers = { 'Content-Type': 'text/html', } header = response_with_headers(headers) r = header + '\r\n' + body return r.encode()
def update(request): """ 用于增加新 todo 的路由函数 """ uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') if request.method == 'POST': # 修改并且保存 todo form = request.form() print('debug update', form) todo_id = int(form.get('id', -1)) t = Todo.find_by(id=todo_id) t.title = form.get('title', t.title) t.save() # 浏览器发送数据过来被处理后, 重定向到首页 # 浏览器在请求新首页的时候, 就能看到新增的数据了 return redirect('/todo')
def updateTodos(self): new_todos = self.findNewTodos() deleted_todos = self.findDeletedTodos() coupled_todos = self.findCoupledTodos() print new_todos print deleted_todos print coupled_todos for key in deleted_todos: ln = deleted_todos[key].line_number fp = deleted_todos[key].filepath try: todo = Todo.get(line_number=ln, filepath=fp, repo=self.repo, account=self.account, committed_by=self.committed_by) todo.remove() except KeyError, e: print e.message print "This todo was already deleted"
def delete(todo_id): """ <int:todo_id> 的方式可以匹配一个 int 类型 int 指定了它的类型,省略的话参数中的 todo_id 就是 str 类型 这个概念叫做 动态路由 意思是这个路由函数可以匹配一系列不同的路由 /todo/delete/1 /todo/delete/2 /todo/delete/3 都可以执行 动态路由是现在流行的路由设计方案 """ # 通过 id 删除 todo t = Todo.delete(todo_id) # 引用蓝图内部的路由函数的时候,可以省略名字只用 . # 因为我们就在 todo 这个蓝图里面, 所以可以省略 todo # return redirect(url_for('todo.index')) return redirect(url_for('.index'))
def update(request): """ 用于增加新 todo 的路由函数 """ # 课5作业2:由于权限判断都放在了装饰器,所以这里直接写update逻辑 form = request.form() log('todo update', form, form['id'], type(form['id'])) todo_id = int(form['id']) t = Todo.find_by(id=todo_id) t.title = form['title'] # 课5作业3:update保存之前更新updated_time import time t.updated_time = int(time.time()) t.save() # 浏览器发送数据过来被处理后, 重定向到首页 # 浏览器在请求新首页的时候, 就能看到新增的数据了 return redirect('/todo')
def edit(request): """ todo edit 的路由函数 """ uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') # 得到当前编辑的 todo 的 id todo_id = int(request.query.get('id', -1)) t = Todo.find_by(id=todo_id) # 权限 if t.user_id != u.id: return redirect('/login') # if todo_id < 1: # return error(404) # 替换模板文件中的标记字符串 body = template('todo_edit.html', todo=t) return http_response(body)
def post(self): data = request.get_json(force=True) title = data["title"] description = data["description"] created_at = datetime.date.fromtimestamp(time.time()) try: session = get_session() to_add = Todo(title=title, description=description, created_at=created_at) session.add(to_add) session.commit() return {"message": "Successfully inserted a value"}, 200 except: return {"message": "Failed to insert a value"}, 500
def add(request): """ 接受客户端发送的 json 数据, 添加数据并 将新创建的 todo 数据返回给前端 """ # 得到 body 里面的数据 user_id = current_user_id(request) form = request.json_parse() t = Todo(form) # 设置 user_id t.user_id = user_id Todo.add(t) # 返回新添加的数据 return json_response(t.json_parse())
def add(request): ''' 处理POST后 todo 的路由函数 ''' headers = { "Content": "text/html", } uname = current_user(request) u = User.find_by(username=uname) if request.method == "POST": ''' Body: 'title=aaa' -> {'title': 'aaa'} ''' form = request.form() t = Todo.new(form) t.user_id = u.id t.save() # 任务完成 return redirect('/todo')
def add(request): """ 用于增加新 todo 的路由函数 """ headers = { 'Content-Type': 'text/html', } uname = current_user(request) u = User.find_by(username=uname) if request.method == 'POST': # 'title=aaa' # {'title': 'aaa'} form = request.form() t = Todo.new(form) t.user_id = u.id t.save() # 浏览器发送数据过来被处理后, 重定向到首页 # 浏览器在请求新首页的时候, 就能看到新增的数据了 return redirect( '/todo') # 如果不重定向 直接返回发index(request)刷新 结果一样 但是网址是/todo/add 不应该这样
def add(): if request.method == 'POST' or request.method == 'post': form = request.json if form is None: form = request.form print(form) t = Todo.new_without_save(form) if t.title == ' ' or len(t.title) == 0: # flash("人生在世总是要干点什么的") return jsonify({'flash': "人生在世总是要干点什么的"}) else: t.save() # return redirect(url_for('todo.index')) return jsonify({ "id": t.id, "ct": strftime(t.ct), "title": t.title, "status": 200, })
def index(request): """ todo 首页 的路由函数 """ # 找到当前登录的用户, 如果没登录, 就 redirect 到 /login uid = current_user(request) todo_list = Todo.find_all(user_id=uid) todo_html = '' if todo_list is not None: # 下面生成一个 html 字符串 todos = [] for t in todo_list: edit_link = '<a href="/todo/edit?id={}">编辑</a>'.format(t.id) delete_link = '<a href="/todo/delete?id={}">删除</a>'.format(t.id) s = '<h3>{} : {} {} {}</h3>'.format(t.id, t.task, edit_link, delete_link) todos.append(s) todo_html = ''.join(todos) # 替换模板文件中的标记字符串 body = template('todo_index.html') body = body.replace('{{ todos }}', todo_html) return http_response(body)
def fake_data(): SQLModel.init_db() Test.new({}) form = dict( username='******', password='******', role=UserRole.normal, ) u, result = User.register(form) Session.add(u.id) form = dict(title='test todo ajax', ) todo = Todo.add(form, u.id) t = TodoAjax.add(form, u.id) form = dict(content='test weibo', ) weibo = Weibo.add(form, u.id) comment = Comment.add(form, u.id)
def create_item(): username = session["username"] dt_created = datetime.datetime.utcnow() text = request.form.get("text") title = request.form.get("title") item_id = int(str(uuid.uuid4().int)[:10]) item_json = { "item_id": item_id, "username": username, "dt_created": dt_created, "text": text, "title": title, } record = Todo.put({ "item_id": item_id, "username": username, "dt_created": dt_created, "text": text, "title": title, }) return jsonify({"message": "Item created.", "Item": item_json}), 200
def index(request): """ todo 首页的路由函数 """ u = current_user(request) log('todo index', u) todo_list = Todo.find_all(user_id=u.id) # 生成一个 todo 项的 html 字符串 todo_html = """ <h3> {} : {} <a href="/todo/edit?id={}">编辑</a> <a href="/todo/delete?id={}">删除</a> 创建 {} 最近修改 {} </h3> """ todo_html = ''.join([ todo_html.format( t.id, t.title, t.id, t.id, formatted_time(t.created_time), formatted_time(t.updated_time), ) for t in todo_list ]) # 替换模板文件中的标记字符串 body = template('todo_index.html') body = body.replace('{{todos}}', todo_html) headers = { 'Content-Type': 'text/html', } header = response_with_headers(headers) r = header + '\r\n' + body return r.encode()
def create_tables(): User.create_table() Todo.create_table()
#! coding: utf-8 import sqlite3 as sq import sys from models.manager import Manager from models.todo import Todo # set up manager. manager = Manager() # bind cur,con to manager todo = Todo(manager) todo.drop_table() todo.create_table() todo.find(2).remove() todo.find(1).update("wash the car") todo.create({"task": "bar"}) todo.create({"task": "hoge"}) print todo.show_todos()
def add(): form = request.form t = Todo(form) t.save() return redirect(url_for('.index'))