def create_task(user_route): body = request.get_json() new_task = Tasks(user_name=user_route, task_text=body["task_text"], task_done=body["task_done"]) new_task.add_task() return jsonify(new_task.serialize())
def create_task(request): data = json.loads(request.data) if "taskname" not in data: return jsonify(error=True, message="Task Name field is required") taskname = cgi.escape(data['taskname']) if not taskname: return jsonify(error=True, message="Task Name field cannot be blank") taskduedate = None if "taskduedate" in data: if data['taskduedate']: date_obj = datetime.strptime(data['taskduedate'], "%Y-%m-%d") current = datetime.now() print(date_obj, current) if date_obj < current: return jsonify(error=True, message="Date cannot be today or in the past") else: taskduedate = date_obj parent_task_id = data[ 'parent_task_id'] if 'parent_task_id' in data else None new_task = Tasks(text = taskname, due_date = taskduedate, owner_id = user_session["you_id"]) \ if taskduedate else Tasks(text = taskname, owner_id = user_session["you_id"]) new_task.parent_task_id = parent_task_id db_session.add(new_task) db_session.commit() return jsonify(message="New Task Created!", new_task=new_task.serialize)
def add_new_task(): body = json.loads(request.data) title = body.get('title', None) description = body.get('description', None) due_date = body.get('due_date', None) if due_date is not None: due_date = datetime.strptime(due_date , '%Y-%m-%d').date() new_task = Tasks(title=title, description=description, due_date=due_date) db.add(new_task) # Add assignee relation assignee_key = body.get('assignee_key',None) assignee = db.query(People).by_key(assignee_key) if assignee_key is not None: db.add(task_graph.relation(new_task, Assignee_Relation(), assignee)) # Add category relation category_key = body.get('category_key', None) category = db.query(Categories).by_key(category_key) if category is not None: db.add(task_graph.relation(relation_from=category, relation=Category_Relation(), relation_to=new_task)) return jsonify({'result': new_task._dump()})
def delete(task_id): ''' Delete a task from the database arg: task_id - the id of the task to delete ''' Tasks.delete(task_id) return '{"status": "success"}'
def complete(task_id): ''' Mark a task completed. arg: task_id - the task to mark as completed ''' Tasks.change_complete(task_id) return '{"status": "success"}'
def uncomplete(task_id): ''' Mark a task as not completed arg: task_id - the task to mark as not completed ''' Tasks.change_complete(task_id, False) return '{"status": "success"}'
def update_task(user_route): body = request.get_json() updated_task = Tasks(user_name=user_route, id=body["id"], task_text=body["task_text"], task_done=body["task_done"]) updated_task.update_task(user_route, body["id"], body["task_text"], body["task_done"]) return jsonify(updated_task.serialize())
def api_create_new_task(): # In post operation we first fetch the json received from client received_json = request.get_json() # Convert that Json into you object tasks_object = Tasks(received_json) tasks_object.tcreatedondate = datetime.now() db_session.add(tasks_object) db_session.commit() return {"id": tasks_object.tid, "msg": "task created"}, 201
def assign(task_id): ''' Assign a user to a task. arg: task_id - the id of the task to assign POST arg: user_id - the id of the user to assign to the task ''' user_id = request.form['user_id'] Tasks.assign(task_id, user_id) return '{"status": "success"}'
def unassign(task_id): ''' Unassign a user from a task. arg: task_id - the task to unassign from POST arg: user_id - the id of the user to unassign from the task ''' user_id = request.form['user_id'] Tasks.unassign(task_id, user_id) return '{"status": "success"}'
def post(self, task_id): task = Tasks.get_by_id(int(task_id)) task.archived = False task.put() time.sleep(0.1) if Tasks.query(Tasks.archived == True).fetch(): return self.redirect_to("archived") else: return self.redirect_to("tasks")
def post(self): entry = self.request.get("entry") if '<script>' not in entry and not entry == '': task = Tasks(task=entry) task.put() time.sleep(0.1) else: pass return self.redirect_to("tasks")
def get(self, task_id): task = Tasks.get_by_id(int(task_id)) task.archived = True task.put() time.sleep(0.1) tasks = Tasks.query(Tasks.archived == False).fetch() tasks.sort(key=lambda r: r.date, reverse=True) params = {"tasks": tasks, "task_id": task_id} return self.render_template("archive_task.html", params=params)
async def delete_task(request, task_id): errors = '' status_code = 202 async with app.engine.acquire() as conn: query = await conn.execute(Tasks.select().where(Tasks.c.id == task_id)) task = await query.fetchone() if task: await conn.execute(Tasks.delete().where(Tasks.c.id == task_id)) await conn.connection.commit() else: status_code = 404 errors = 'Not Found' return response.json({'errors': errors}, status_code)
def post(self, task_id): task = Tasks.get_by_id(int(task_id)) task.archived = False task.put() time.sleep(0.1) return self.redirect_to("tasks")
def post(self, task_id): edited = self.request.get("edit") task = Tasks.get_by_id(int(task_id)) task.task = edited task.put() time.sleep(0.1) return self.redirect_to("tasks")
def get(self): tasks = Tasks.query(Tasks.archived == False).fetch() tasks.sort(key=lambda r: r.date, reverse=True) params = {"tasks": tasks} return self.render_template("tasks.html", params=params)
def create_task(): try: project_name = request.json.get('project_name') title = request.json.get('task_title') status = request.json.get('status') reason = request.json.get('reason') user_name = session['user']['user_name'] user_obj = User.query.filter_by(user_name=user_name).first() project_obj = Project.query.filter_by( project_name=project_name).first() user_obj.projects.append(project_obj) task = Tasks(task_title=title, status=status, reason=reason, project=project_obj, user=user_obj) db.session.add(task) db.session.commit() message = "Successfully saved task" return send_success_response(message) except KeyError as e: print(e) return send_error_response() except Exception as e: print(e) message = "Error in storing task" return send_error_response(message)
def createTask(self, data): """inputs: @string task name @string task members """ team = Teams.query.filter_by(team_code=data['team_code']).first() if not team: return {'status': 401, 'message': 'Team does not exist'} existing = Tasks.query.filter_by(teams_id=team.id).filter_by(name=data['name']).first() if not existing: new_task = Tasks(teams_id=team.id, name=data['name'], items=data['items']) db.session.add(new_task) message = 'New Task created' val = new_task.items else: existing.items = data['items'] message = 'Existing task updated' val = existing.items db.session.commit() return {'status': 201, 'message': message, 'val': val}
def new_task_post(): task_form = TaskForm(request.form) title = request.form types = get_task_types() if task_form.validate(): title = request.form["title"] location = request.form["location"] price = float(request.form["price"]) description = request.form["description"] type = request.form["type"] user = session["id"] try: task = Tasks(title=title, location=location, price=price, description=description, user=user, type=type) db.session.add(task) db.session.commit() link = "/task/{}".format(task.id) return redirect(link) except Exception as e: db.session.rollback() return render_template("new.html", task_form=task_form, task_types=types) else: return render_template("new.html", task_form=task_form, task_types=types)
def add_task_to_db(owner_id, task_id): """ Функция добавления id чата в БД :return: """ t = Tasks(owner_id, task_id) db.session.add(t) db.session.commit()
def create_task(task_name): try: new_task = Tasks(name=task_name) db.session.add(new_task) db.session.flush() db.session.commit() return True except: return False
def new_task(): form = AddTask(request.form, csrf_enabled=False) if form.validate_on_submit(): task = Tasks(form.name.data, form.due_date.data, form.priority.data, '1') db.session.add(task) db.session.commit() flash('Entry was successful') return redirect_url(url_for('tasks'))
def add(): form = forms.AddText() if form.validate_on_submit(): t = Tasks(title=form.title.data, date=datetime.utcnow()) db.session.add(t) db.session.commit() flash("Task successfully added") return redirect(url_for('index')) return render_template('add.html', form=form)
def tearDown(self): """Clear test_db (Delete all row in tasks table)""" app.engine = create_engine( "mysql+pymysql://{user}:{password}@{host}/{db}".format( user=app.config.DB_USER, db=app.config.DB_NAME, host=app.config.DB_HOST, password=app.config.DB_PASSWORD)) with app.engine.connect() as conn: conn.execute(Tasks.delete())
def test_task_constraints(db_handle): task = Tasks(name="taski", start=datetime.date(2020, 1, 1), end=datetime.date(2019, 1, 1), total_hours=-1, total_cost=-1, status="asdasd") db_handle.session.add(task) with pytest.raises(IntegrityError): db_handle.session.commit()
def create_task_intent(context, message, intent): """Handle create task intent Args: context (Context): the Telegram context object message (Message): the Telegram message object intent (IntentResult): the intent result from Dialogflow """ task = Tasks(team_id=message.chat_id, status=consts.TASK_TODO) context.user_data[consts.CURR_TASK] = task ask_task_details(context.bot, message.chat_id, task)
def get(self): tasks = Tasks.query(Tasks.archived == True).fetch() tasks.sort(key=lambda r: r.date, reverse=True) if tasks: params = {"tasks": tasks} else: params = {"message": "There are no completed tasks."} return self.render_template("archived.html", params=params)
def post(self): try: task_dict = request.get_json(force=True) new_task = Tasks(task_dict['item']) db.session.add(new_task) db.session.commit() except SQLAlchemyError as e: db.session.rollback() return {"error_msg": str(e)}, 403 return task_schema.jsonify(new_task)
async def update_task(request, task_id): errors = '' status_code = 200 form = TaskUpdateForm().load(request.json) if not form.errors: async with app.engine.acquire() as conn: query = await conn.execute( Tasks.select().where(Tasks.c.id == task_id)) task = await query.fetchone() if task: await conn.execute(Tasks.update().where(Tasks.c.id == task_id). \ values({k: v for k, v in form.data.items()})) await conn.connection.commit() else: errors = 'Not Found' status_code = 404 else: status_code = 400 errors = form.errors return response.json({'errors': errors}, status=status_code)
def create_item(address: str): if URL_REGEX.match(address): task = Tasks(address=address, timestamp=datetime.utcnow()) session = Session() session.add(task) try: session.commit() except IntegrityError: raise HTTPException(status_code=422, detail='Unprocessable Entity') count.delay(task.id) else: raise HTTPException(status_code=422, detail='Unprocessable Entity')
def task_add(): todo = request.json body = request.get_json() new_task = Tasks(label=todo["label"], done=todo["done"], user=todo["user"]) db.session.add(new_task) db.session.commit() # query all tasks and return updated_tasks = Tasks.query.filter_by(user=body["user"]) response_body = list(map(lambda x: x.serialize(), updated_tasks)) return jsonify(response_body), 200
def store_to_database(self): taskid_json = self.task.taskid # 任务id str格式 task_status_json = self.task.status # 任务状态 str格式 task_result_json = json.dumps(self.task.task_result) # 任务结果 json格式 task_owner_id = session.get('user_id') # 任务创建者 int类型 # 实例化数据对象 task = Tasks(task_id=taskid_json, task_status=task_status_json, task_data=task_result_json, task_owner_id=task_owner_id) db.session.add(task) # 将数据对象添加到数据库 db.session.commit() # 提交事务
def __init__(self, log, course, answers, courses): self.course_name = '' self.users = Users() self.tasks = Tasks() self.modules = Modules() self.content = Content() self._parse(log) for item in (self.users, self.tasks, self.modules, self.content): item.update_data(course, answers) self.course_long_name = courses[self.course_name]
def add_todo(name, text): """ todo listの追加 """ try: task = Tasks(name=name, text=text) session.add(task) session.commit() except SQLAlchemyError as e: print(e) session.rollback() except Exception as e: session.rollback() finally: session.close()
def edit(task_id): ''' Edits a task in the given board arg: task - the id of the task to be edited POST arg: name - the name of the task POST arg: description - a description of the task POST arg: estimate - an estimate of task's man hours to completion ''' name = request.form['name'] description = request.form['description'] estimate = 1.0 try: estimate = float(request.form['estimate']) except ValueError: estimate = 1.0 result = Tasks.edit(task_id, name, description, estimate) if type(result) != dict: return '{"status": "success"}' else: return json.dumps(result)
def create(story_id): ''' Create a new task in the given story. arg: story_id - the id of the story the new task will belong to POST arg: name - the name of the task POST arg: description - a description of the task POST arg: estimate - the estimated hours for the task ''' name = request.form['name'] estimate = 1.0 try: estimate = float(request.form['estimate']) except ValueError: estimate = 1.0 description = '' if 'description' in request.form: description = request.form['description'] result = Tasks.create(story_id, name, description, estimate) if type(result) != dict: return '{"status": "success"}' else: return json.dumps(result)
def setup(request): if request.method == 'POST': if request.POST.get('action') == 'cleardb': job = tasks.cleardb.delay() try: task = Tasks.objects.get(Task='cleardb') except: task = Tasks() task.Task = 'cleardb' task.Task_Id = job.id task.Count = 0 task.save() LogKrakenEvent(request.user, 'Database Cleared', 'info') return HttpResponse() elif request.POST.get('action') == 'removescreenshots': job = tasks.removescreenshots.delay() try: task = Tasks.objects.get(Task='removescreenshots') except: task = Tasks() task.Task = 'removescreenshots' task.Task_Id = job.id task.Count = 0 task.save() LogKrakenEvent(request.user, 'Screenshots Deleted', 'info') return HttpResponse() elif request.POST.get('action') == 'parse': form = ParseForm(request.POST, request.FILES) if form.is_valid: with open('/opt/Kraken/tmp/nmap.xml', 'wb+') as destination: for chunk in request.FILES["parsefile"].chunks(): destination.write(chunk) job = tasks.nmap_parse.delay('/opt/Kraken/tmp/nmap.xml') try: task = Tasks.objects.get(Task='parse') except: task = Tasks() task.Task = 'parse' task.Task_Id = job.id task.Count = 0 task.save() form = ParseForm() addresses = Addresses.objects.all() return render(request, 'Web_Scout/setup.html', {'addresses':addresses, 'form':form, 'uploaded':False, 'failedupload':False}) else: return render(request, 'Web_Scout/setup.html', {'form':form, 'uploaded':False, 'failedupload':True}) elif request.POST.get('action') == 'screenshot': overwrite = request.POST.get('overwrite') ipPattern = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") hostnamePattern = re.compile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$") proxy = "" proxyHost = request.POST.get("proxyhost", "") proxyPort = request.POST.get("proxyport", "") if proxyHost != "" and (ipPattern.match(proxyHost) or hostnamePattern.match(proxyHost)) and int(proxyPort) > 0 and int(proxyPort) < 65536: proxy = request.POST.get('proxyhost') + ":" + request.POST.get('proxyport') elif proxyHost: return HttpResponse(status=500) if overwrite == 'True': job = tasks.startscreenshot.delay(True, proxy) else: job = tasks.startscreenshot.delay(False, proxy) try: task = Tasks.objects.get(Task='screenshot') except: task = Tasks() task.Task = 'screenshot' task.Task_Id = job.id task.Count = 0 task.save() LogKrakenEvent(request.user, 'Screenshot taking task initiated', 'info') return HttpResponse() elif request.POST.get('action') == 'addurl': raw_list = request.POST.get('address-textarea') address_data = AddUrl(raw_list) json_data = json.dumps(address_data) return HttpResponse(json_data, content_type='application/json') elif request.POST.get('action') == 'runmodules': job = tasks.runmodules.delay() try: task = Tasks.objects.get(Task='runmodules') except: task = Tasks() task.Task = 'runmodules' task.Task_Id = job.id task.Count = 0 task.save() LogKrakenEvent(request.user, 'Running default credential checks.', 'info') return HttpResponse() elif request.POST.get('action') == 'scan': address_list = [] error_message = [] for key,value in request.POST.items(): if str(value) == "on": try: address_object = Addresses.objects.get(AddressID=key) if address_object.Hostname: address_list.append(address_object.Hostname) else: address_list.append(address_object.Address + '/' + address_object.Cidr) except: error_message.append(key + ' not found in database.') continue job = tasks.scan.delay(address_list) try: task = Tasks.objects.get(Task='scan') except: task = Tasks() task.Task = 'scan' task.Task_Id = job.id task.Count = 0 task.save() json_data = json.dumps(error_message) return HttpResponse(json_data, content_type='application/json') elif request.POST.get('action') == 'addaddress': raw_list = request.POST.get('address-textarea') print raw_list address_data = AddAddress(raw_list) json_data = json.dumps(address_data) return HttpResponse(json_data, content_type='application/json') elif request.POST.get('action') == 'addhostname': raw_list = request.POST.get('address-textarea') address_data = AddHostname(raw_list) json_data = json.dumps(address_data) return HttpResponse(json_data, content_type='application/json') elif request.POST.get('action') == 'delete': address_list = [] for key,value in request.POST.items(): if str(value) == "on": address_list.append(key) deleted_addresses = DeleteAddress(address_list) json_data = json.dumps(deleted_addresses) return HttpResponse(json_data, content_type='application/json') else: return HttpResponse("Failure.") else: form = ParseForm() addresses = Addresses.objects.all() return render(request, 'Web_Scout/setup.html', {'addresses':addresses, 'form':form, 'uploaded':False, 'failedupload':False})