def populate_db(): """Populate db with sample data""" data = [ Task(id=1, name="Study", description="python and flask"), Task(id=2, name="Work", description="add feature"), Task(id=3, name="Buy food", description="pizza"), ] db.session.bulk_save_objects(data) db.session.commit() return Task.query.all()
def post(self): """新增任务 data: { 'user_list': [ { 'id': 1, 'username': '******' } ] 'title': 'xxx', } """ data = request.get_json(force=True) user_list = data.get('user_list') for user in user_list: new_task = Task(title=data.get('title'), ownerId=user.get('id'), from_user_id=g.userId) db.session.add(new_task) db.session.commit() target_task = Task.query.filter_by(title=data.get('title'), ownerId=g.userId).first() return { 'code': 20000, # 返回新增任务的id 'data': target_task.id }
def post(self): """新增任务 data: { 'title': 'xxx', } """ data = request.get_json(force = True) new_task = Task( title = data.get('title'), time = self.tomorrow_time, ownerId = g.userId, from_user_id = g.userId ) db.session.add(new_task) db.session.commit() target_task = Task.query.filter_by( title = data.get('title'), ownerId = g.userId ).first() return { 'code': 20000, # 返回新增任务的id 'data': target_task.id }
def new_task(): if request.method == 'POST': form = request.form # gets the form from the data sent title = form.get("title") content = form.get("content") if not title: # some null checks return "Title is empty!", 400 if not content: return "Content is empty!", 400 # gets all the information from the form data submitted task = Task(title=title, date_posted=form.get("date_posted"), elderly_id=current_user.id, content=content) db.session.add(task) # adds in the task db.session.commit() return "Successfully added task!", 200
def handle_file_stream(): """处理文件流,整合今日和明日的任务 """ # 当天日期 current_time = datetime.datetime.now().strftime('%Y-%m-%d') # 第二天日期 tomorrow_time = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d") # 今日任务 today_tasks = Task.query.filter_by(time=str(current_time), ownerId=g.userId).all() today_task_list = [] for item in today_tasks: node = dict(id=item.id, title=item.title, status=status_trans(item.status), time=datetime.datetime.now(), edit=False) today_task_list.append(node) # 未完成任务添加到明天 if item.status != 1: target = Task.query.filter_by(id=item.id).first() if not Task.query.filter_by(title=item.title, time=tomorrow_time, ownerId=g.userId).first(): tomorrow_task = Task(title=target.title, status=target.status, time=tomorrow_time, ownerId=g.userId, from_user_id=target.from_user_id) db.session.add(tomorrow_task) db.session.commit() # 明日任务 tomorrow_tasks = Task.query.filter_by(time=str(tomorrow_time), ownerId=g.userId).all() tomorrow_task_list = [ dict(id=item.id, title=item.title, status=status_trans(item.status), time=item.time, edit=False) for item in tomorrow_tasks ] # 问题/建议 other = Other.query.filter_by(time=str(current_time), ownerId=g.userId).first() if other: advice = other.advice else: advice = '' filename = '{0}-{1}.xlsx'.format( g.username, datetime.datetime.now().strftime('%Y%m%d')) file_stream = handle_excel(g.username, today_task_list, tomorrow_task_list, advice) return file_stream, filename
def db_get_task(list_id, task_id): ''' Queries the db for a task with the specified id''' query = ''' select * from Tasks where id = ? and list = ? order by id asc ''' with app.app_context(): cur = get_db().cursor() cur.execute(query, [task_id, list_id]) task = Task.fromDict(dict_from_row(cur.fetchone())) return task
def db_get_task(list_id, task_id): ''' Queries the db for a task with the specified id''' query = ''' SELECT * FROM Tasks WHERE (id = ? AND list = ?) ORDER BY ASC ''' with app.app_context(): cur = get_db().cursor() cur.execute(query, [task_id, list_id]) task = Task.fromDict(dict_from_row(cur.fetchone())) return task
def insert(): """灌数据""" for user in ['jack', 'jerry', 'mark']: newUser = User(username=user, password="******") db.session.add(newUser) click.echo('insert User: %s' % user) db.session.commit() for item in range(1, 11): newTask = Task(title="task%s" % (item), ownerId=1, from_user_id=item) db.session.add(newTask) db.session.commit() click.echo('Done.')
def test_delete_workspace(self, user): methodology = Methodology(name='test', workspace=self.workspace) task = Task(methodology=methodology, assigned_to=[user], name="test", workspace=self.workspace) self.session.add(task) self.session.commit() with self.assert_deletes(self.permission): with self.assert_deletes(self.user, should_delete=False): self.session.delete(self.workspace) self.session.commit()
def db_get_task(list_id, task_id): ''' Queries the db for a task with the specified id''' query = ''' SELECT id, title, list, status, description, due, revision FROM tasks WHERE id = ? AND list = ?; ''' with app.app_context(): cur = get_db().cursor() cur.execute(query, [task_id, list_id]) task = Task.fromDict(dict_from_row(cur.fetchone())) return task
def db_get_tasks_for_list(list_id): ''' Returns all tasks from the database for a given list''' query = ''' SELECT * FROM Tasks WHERE list = ? ''' with app.app_context(): cur = get_db().cursor() cur.execute(query, [list_id]) tasks = [] for row in cur: task = Task.fromDict(dict_from_row(row)) if isinstance(task, Task): tasks.append(task) return tasks
def newtask(): title = request.json['title'] describe = request.json['describe'] t = Task(title=title, describe=describe) taskdata = json.loads(request.json['data']) data = taskdata taskdata.update({ 'tid': suuid(), }) # 添加到一个列表中 mongo_store.update({'email': current_user.email}, {'$push': { 'task': taskdata }}) db.session.add(t) key = job_spider(data).key.decode() return redirect(url_for('.job_result', id=key))
def post(self): json_data = request.get_json(force=True) if not json_data: return api_response_no_input() try: fields = task_schema.load(json_data) except ValidationError as err: return validation_error(err.messages) if Task.query.filter_by(name=fields['name']).all(): return api_misc_error("Task with this name already exists.", code=409) task = Task(name=fields['name'], status=fields['status']) apply_optional_fields(task, fields) db.session.add(task) db.session.commit() return api_response(204, data=task_schema.dump(task))
def post(self): if request.headers['Content-Type'] != 'application/json': return jsonify({'error': 'not a json type'}), 400 req = request.get_json() print("\n============\n", req, "\n============\n") user_id = req['user_id'] content = req['content'] limit = req['_limit'] task = Task(user_id, content, limit) sess = Session sess.add(task) sess.commit() result = db.session.query(Task).filter(Task.user_id == user_id).all() result = TaskSchema(many=True).dump(result) result = result[-1] print("POST: " + json.dumps(result)) data = jsonify({'items': result}) return data
def sparktask(): task = t.spark_job_task.apply_async() task_id_str = str(task.id) user = User.query.filter_by(email=session['email']).first() user.tasks += user.tasks + task_id_str + ";" db.session.commit() if not es.indices.exists('spark-jobs'): print("creating '%s' index..." % ('spark-jobs')) res = es.indices.create(index='spark-jobs', body={ "settings": { "number_of_shards": 1, "number_of_replicas": 0 } }) print(res) es.index(index='spark-jobs', doc_type='job', id=task.id, body={ 'current': 0, 'total': 100, 'id_string': task_id_str, 'status': 'Spark job pending..', 'start_time': datetime.utcnow() }) link = task_id_str new_task = Task(user_id=user.id, id_string=link) db.session.add(new_task) db.session.commit() return jsonify({}), 202, { 'Location': url_for('main.taskstatus', task_id=task.id) }
def test_update_tasks(test_client, init_database): s = db.session s.bulk_save_objects(generate_users()) s.commit() # get all user ids user_ids = [id for (id, ) in s.query(User.id).all()] assert (len(user_ids) == 4) task = Task(name="test_task") s.add(task) s.commit() task.update_users(user_ids) assert (len(task.users) == 4) # update invalid ids partly_invalid = [1337, 1] task.update_users(partly_invalid) assert (len(task.users) == 1)
def new_tasks(): print("got post", request) f = Task(request.args.get('name'), request.args.get('text')) print("new task object: ", f.__dict__) tasks.append(f) return jsonify(f.__dict__)
def populate(self, workspace, service, session, user, vulnerability_factory, credential_factory, empty_command_factory): session.commit() self.session = session assert service.workspace_id == workspace.id workspace.set_scope(['*.infobytesec.com', '192.168.1.0/24']) self.user = user self.workspace = workspace self.permission = WorkspacePermission(user=user, workspace=workspace) session.add(self.permission) self.host = service.host self.host.set_hostnames(['a.com', 'b.com']) self.service = service self.host_cred = credential_factory.create( host=self.host, service=None, workspace=workspace, creator=user, ) self.service_cred = credential_factory.create( host=None, service=service, workspace=workspace, creator=user, ) self.host_vuln = vulnerability_factory.create( host=self.host, service=None, workspace=workspace, creator=user, ) self.service_vuln = vulnerability_factory.create( host=None, service=service, workspace=workspace, creator=user, ) session.flush() for vuln in [self.host_vuln, self.service_vuln]: vuln.references = ['CVE-1234', 'CVE-4331'] vuln.policy_violations = ["PCI-DSS"] self.attachment = File( name='test.png', filename='test.png', content='test', object_type='vulnerability', object_id=self.service_vuln.id, creator=user, ) self.session.add(self.attachment) self.host_attachment = File( name='test.png', filename='test.png', content='test', object_type='host', object_id=self.host.id, creator=user, ) self.session.add(self.host_attachment) self.comment = Comment( text="test", object_type='host', object_id=self.host.id, workspace=self.workspace, creator=user, ) self.session.add(self.comment) self.reply_comment = Comment( text="ok", object_type='host', object_id=self.host.id, workspace=self.workspace, reply_to=self.comment, creator=user, ) self.command = empty_command_factory.create(workspace=workspace, creator=user) CommandObject.create(self.host_vuln, self.command) CommandObject.create(self.service_vuln, self.command) self.methodology_template = MethodologyTemplate(name="test", ) session.add(self.methodology_template) self.methodology_template_task = TaskTemplate( name="aaaa", template=self.methodology_template) session.add(self.methodology_template) self.methodology = Methodology(name="test", template=self.methodology_template, workspace=self.workspace) session.add(self.methodology) self.methodology_task = Task(name="aaaa", workspace=self.workspace, template=self.methodology_template_task, methodology=self.methodology) session.add(self.methodology_template_task) self.methodology_task_assigned = TaskAssignedTo( task=self.methodology_task, user=self.user, ) session.add(self.methodology_task_assigned) session.commit()