def add_employee_xrequest(): if not current_user.is_authenticated: return redirect(url_for('login')) # add employee request to database # declare the Request Form form = RequestForm(request.form) form.stock_item.choices = [(x.id, x) for x in Stock.query.all()] msg = None # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables stock_item = request.form.get('stock_item', '', type=int) quantity = request.form.get('quantity', '', type=int) # see if request already exists # TODO: filter by datecreated as well # request = Request.query.filter_by(user_id=current_user.id, product_id=stock_item, quantity = quantity).first() xrequest = Request(current_user.id, stock_item, 1, quantity, 1) # check if request is in bounds stock = Stock.query.filter_by(id=stock_item).first() if quantity <= stock.stocklevel: xrequest.save() flash('Request successfully created!') else: flash( f'I am sorry but we have only {stock.quantity} {stock} available' ) else: flash('I am sorry but the details you entered cannot be saved :(') return redirect('/psalm2vs8/employee-requests')
def render_task_execution(task_id): task = db.session.query(Task).get_or_404(task_id) if (task.status != 'в работе' and not current_user.is_boss) \ or current_user.id not in [user.id for user in task.users]: return abort(403) form = TaskExecutionForm() if form.validate_on_submit(): date_of_execution = form.executed_date.data if date_of_execution: new_request = Request(user=current_user, task=task, executed_comment=form.comment.data, executed_number=form.executed_number.data, date_of_execution=date_of_execution) else: new_request = Request(user=current_user, task=task, executed_comment=form.comment.data, executed_number=form.executed_number.data) db.session.add(new_request) task.status = 'на рассмотрении' db.session.commit() flash( 'Ваша заявка выполнения задачи успешно передана руководству на рассмотрение!' ) return redirect(url_for('main.render_tasks')) return render_template('execute_task.html', title="Отправить исполнение задачи", form=form, task=task)
def test_create_request_with_details(self): author = User(username='******') author.save() title = "hello world" description = "hello world" request = Request(title=title, description=description, requested_by=author) request.save()
def add_requests(): try: user_id = int(request.json['userId']) except ValueError: return make_response(jsonify({'error': 'Invalid userId'}), 403) user = User.query.filter_by(id=user_id).first() if user.id != current_user.id: return make_response(jsonify({'error': 'User not authenticated'}), 403) request_for_help = Request() request_for_help.user = user if 'amount' in request.json: request_for_help.amount = request.json['amount'] if 'city' in request.json: request_for_help.city = request.json['city'] if 'date' in request.json: request_for_help.date = datetime.strptime(request.json['date'], '%Y-%m-%d') if 'details' in request.json: request_for_help.details = request.json['details'] if 'street' in request.json: request_for_help.street = request.json['street'] if 'title' in request.json: request_for_help.title = request.json['title'] if 'zipcode' in request.json: request_for_help.zipcode = request.json['zipcode'] db.session.add(request_for_help) db.session.commit() return request_for_help.to_json()
def test_base(session, db): request = Request(id=13, url='http://www.google.com', status='done') keyword = Keyword(word='carros', requests=[request]) label = Label(name='veículos', restrict=True, keywords=[keyword]) db.create_all() db.session.add(label) db.session.commit() #test create assert session.query(Request).count() == 1 assert session.query(Keyword).count() == 1 assert session.query(Label).count() == 1 #test read assert Request.query.filter_by( id=13).first().url == "http://www.google.com" assert Keyword.query.filter_by(word='carros').first().requests[0].id == 13 assert Label.query.filter_by(name='veículos').first().restrict == True #test update request.url = "http://www.twitch.tv" db.session.commit() assert Request.query.filter_by(id=13).first().url == "http://www.twitch.tv" label.restrict = False assert not Label.query.filter_by(name='veículos').first().restrict #test delete db.session.delete(label) db.session.commit() assert Label.query.filter_by(name='veículos').first() == None assert Request.query.filter_by(id=13).first().url == "http://www.twitch.tv" assert Keyword.query.filter_by(word='carros').first().requests[0].id == 13
def make_request(): data = request.json package = {"menteeId": current_user.id, "mentorId": data["mentorId"], "pitch": data["pitch"], "accepted": data["accepted"]} newRequest = Request(**package) db.session.add(newRequest) db.session.commit() return newRequest.to_dict()
def test_accept_request(self): a = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Administrator').first()) m = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Moderator').first()) user = User(name='sorvihead', password='******', role=Role.query.filter_by(name='User').first()) u = User(name='test', password='******') db.session.add_all([a, u, m, user]) db.session.commit() s = Shop(name='afi', shop_code='9066') d = Department(name='kids') r = Request(description='test', user=u, shop=s, department=d) r2 = Request(description='test2', user=u, shop=s, department=d) r3 = Request(description='test3', user=u, shop=s, department=d) db.session.add_all([s, d, r, r2, r3]) db.session.commit() a.accept_request(r) m.accept_request(r2) db.session.add(r) db.session.commit() self.assertTrue(r.approved) self.assertTrue(r2.approved) self.assertRaises(PermissionError, user.accept_request, r3)
def delete_request(): data = edict(request.get_json()) req = Request.get_by_id(data.request_id) if req is not None and req.caller_id == current_user.id: Request.delete_by_id(req.id) return "OK"
def request_create(): # if not request.json or 'description' not in request.json or 'service_id' not in request.json: # return json.dumps({'error': 'incorrect_params'}), 400, {'ContentType': 'application/json'} description = request.json['description'] service_id = request.json['service_id'] username = request.json['username'] phone = request.json['phone'] Request.create(description, service_id, username, phone) return jsonify({'success': True}), 200, {'ContentType': 'application/json'}
def project_create(request): # todo there is no validation here and... BETTER TO POST DATA WITH POST REQUEST FOLLOWING THE REST CONVENTION if request.POST: if request.is_ajax(): title = request.POST.get('title') category_name = request.POST.get('category') description = request.POST.get('description') skills = request.POST.getlist('skills[]') category = None request_instance = None if category_name: category = get_object_or_404(RequestCategory, slug=category_name) if title and category: request_instance = Request(title=title, created_by=request.user) request_instance.save() request_instance.type = category request_instance.save() if skills and request_instance: for id in skills: tag = SkillTag.objects.get(pk=id) if tag: request_instance.skills.add(tag) if description and request_instance: request_instance.description = description if request_instance: request_instance.save() return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error'}) else: return HttpResponseRedirect("/dashboard/")
def insert_one(self, request): """Insert a New Request""" request = Request( uri=request["uri"], method=request["method"], headers=request["headers"], body=request["body"], status=request["status"], endpoint=Endpoint.objects.get(pk=request["endpoint_id"])) request.save() return False if request.pk is None else request
def request_food(): form = RequestForm(request.form) times = [time[0] for time in ORDER_TIMES] requests = [ len(db.session.query(Request).filter_by(time=time).all()) for time in times ] current = [] for a, b in zip(times, requests): current.append({"time": a, "requests": b}) if request.method == 'POST' and form.validate(): db.session.rollback() db.session.expunge_all() try: food_request = Request(email=form.request_email.data + EMAIL_DOMAIN, time=form.time.data) db.session.add(food_request) db.session.commit() return redirect("/") except IntegrityError: db.session.rollback() db.session.expunge_all() return redirect("/request") return render_template('request.html', form=form, domain=EMAIL_DOMAIN, current=current)
def test_2_view_summary(self): """ Test viewing a specific test and its summary statistics """ count = Test.query.count() + 1 print(str(count)) test = Test(config=test_config + str(count), start=test_start, end=test_end, workers=num_workers) request = Request(test_id=count, time_sent=req_time, request_type=req_type, request_length=req_length, response_type=res_type, response_length=res_length, duration=duration) metric = SystemMetric(test_id=count, time=met_time, metric_type=met_type, metric_value=met_val) db.session.add(test) db.session.add(request) db.session.add(metric) db.session.commit() self.driver.get('http://localhost:5000/tests/' + str(count) + '/') self.driver.refresh()
def index(): form = RequestForm() requests = Request.query.order_by(Request.client_priority).all() sameClientRequestsA = Request.query.filter_by(client=form.client.data).order_by(Request.client_priority).all() sameClientRequestsD = Request.query.filter_by(client=form.client.data).order_by(Request.client_priority.desc()).all() if form.validate_on_submit(): request = Request(title=form.title.data, description=form.description.data, client=form.client.data, client_priority=form.client_priority.data, product_area=form.product_area.data, target_date=form.target_date.data, reporter=current_user) # Check through all priority numbers for the given client looking for a duplicate value duplicate = "no" for check in sameClientRequestsA: if check.client_priority == form.client_priority.data: duplicate = "yes" # If a duplicate was found, move through the exisitng list of requests and increase priority of all items by one to reorder list if duplicate == "yes": for item in sameClientRequestsD: if item.client_priority >= form.client_priority.data: item.client_priority = item.client_priority +1 db.session.add(item) db.session.commit() db.session.add(request) db.session.commit() flash('Your request has been posted!') return redirect(url_for('index')) return render_template("index.html", title='Home Page', form=form, requests=requests)
def request_page_student(): # module_id = session.get('moduleId') student = Student.get_full_info_by_email(current_user.email) if student is None: flash("You do not have a house yet") redirect(url_for('main.home')) switching_request = Request.get_request_by_owner_id(current_user.id) if switching_request is not None: my_house = House.get_house_by_id(switching_request.house_from) target_house = House.get_house_by_id(switching_request.house_to) switching_request.status_txt = models.status_dict.get( switching_request.status) d1 = datetime.strptime(switching_request.send_date, '%Y-%m-%d') d2 = datetime.now() delta = d2 - d1 switching_request.unfrozen_date = ( d1 + timedelta(days=7)).strftime("%Y-%m-%d") if delta.days <= 7: switching_request.is_frozen = True else: switching_request.is_frozen = False return render_template('notification/request_result_page_student.html', my_house=my_house, target_house=target_house, request=switching_request) current_house = House.query.filter_by(house_id=student.house_id).first() house_list = House.query.filter_by(year=current_house.year) return render_template('notification/request_student.html', house_list=house_list, student=student)
def getResponses(self, tglAwal, tglAkhir, noAju): self.is_idle = False # Create request id in database req = Request(app=self.ceisa_app, aju=noAju) db.session.add(req) db.session.commit() self.req_id = req.id # Store request start in status table sta = Status(id_request=self.req_id, status='start') db.session.add(sta) db.session.commit() try: checkInputTgl = EC.presence_of_element_located((By.CLASS_NAME, 'z-datebox-inp')) WebDriverWait(self.driver, 10).until(checkInputTgl) except TimeoutException: print(f'PEB [ID:{self.req_id}] - Timeout to load page..') # Store error in status table msg = 'Gagal membuka halaman pencarian. Coba beberapa saat lagi.' is_end = True self.updateStatus(msg, is_end) except Exception as e: raise e else: print(f'PEB [ID:{self.req_id}] - Collect responses..') # Update status table msg = 'Mencari respon' self.updateStatus(msg) self.find_peb(tglAwal, tglAkhir, noAju) self.is_idle = True
def sell(): form = CreateSellForm() if form.validate_on_submit(): if not form.itemcount.data.isdigit(): flash('Please input correct count data') return redirect(url_for('sell')) if not form.itemcost.data.isdigit(): flash('Please input correct cost data') return redirect(url_for('sell')) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = '/index' itemname = form.itemname.data.lower() count = int(form.itemcount.data) cost = int(form.itemcost.data) seller = current_user.id itemid = Item.query.filter_by(name=itemname).first() if itemid is None: itm = Item(name=itemname) db.session.add(itm) db.session.commit() itemid = Item.query.filter_by(name=itemname).first().id trade = Request(user_id=seller, item_id=itemid, count=count, cost=cost) db.session.add(trade) db.session.commit() flash('Request get') return redirect('/index') return render_template('cratesellreq.html', title='Create new sell rq', form=form)
def render_request(): form = RequestForm() if request.method == 'POST': name = form.name.data phone = form.phone.data goal = form.goals.data glabel = db.session.query(Goal).filter(Goal.name == goal).first() hour = form.hours.data sql = f"SELECT day_desc FROM request_timechoice where id = {hour};" hlabel = db.session.execute(text(sql)).first() created = datetime.now() db.session.add( Request(created=created, remote_addr=request.remote_addr, name=name, phone=phone, goal_id=glabel.id, timeshoice_id=hour)) db.session.commit() return render_template('request_done.html', name=name, phone=phone, goal=glabel.desc, hour=hlabel[0]) return render_template('request.html', form=form)
def request_form(): form = RequestForm() form.origin_city.choices = app.config['CITIES'] form.origin.choices = app.config['LOCATIONS'] form.destination_city.choices = app.config['CITIES'] form.destination.choices = app.config['LOCATIONS'] if form.validate_on_submit(): request = Request(origin_city=form.origin_city.data, origin=form.origin.data, destination_city=form.destination_city.data, destination=form.destination.data, date=form.date.data, time=form.time.data, author=current_user, description=form.description.data) if form.destination.data == form.origin.data: flash("Origin and Destination cannot be the same") else: db.session.add(request) db.session.commit() flash('Your request has been posted!') # return redirect(url_for('index')) return render_template('requestForm.html', title='Request', form=form)
def teacher_selection(): form = TeacherSelectionForm() if form.validate_on_submit(): goal = db.session.query(Goal).filter(Goal.slug == form.goals.data).first() new_request = Request( username=form.name.data, phone=form.phone.data, goal=goal, time=form.time.data ) db.session.add(new_request) db.session.commit() context = { 'name': new_request.username, 'phone': new_request.phone, 'goal': new_request.goal.title, 'time': new_request.time, 'subject': 'request', 'subject_description': 'Заявка на подбор преподавателя' } return redirect(url_for('sent', context=json.dumps(context))) return render_template('pick.html', form=form)
def request_get_info(): request_info = Request.get_info(request.args.getlist('id')[0]) return json.dumps({ 'username': request_info.username, 'phone': request_info.phone }), 200, { 'ContentType': 'application/json' }
def importTrainlineInfo(): trainlineRESTApi = RESTApi(name='TrainlineRESTApi', BaseUrl='https://www.trainline.eu/api/v5_1/', APIKey='A8fQLJDF94cPUKEu3Vpi') trainlineRESTApi.save() paramsgetStation = { 'q': 'Place', } getStationInformation = Request( name='getStationInformationTrainline', description='Get information about a station', PartToaddToBaseUrl='stations?context=search', funcToExtractDataFromJsonName='getStationInformation', ParamsOrDataDictStructure=paramsgetStation, typeRequests='GET', RApi=trainlineRESTApi) dataFindTrip = { "local_currency": "EUR", "search": { "passenger_ids": ["314892886"], "card_ids": ["14127110"], "departure_station_id": 33349, "arrival_station_id": 6627, "departure_date": "2021-03-29T00:00:00+01:00", "systems": [] } } headersTrainline = { 'Accept': 'application/json', 'User-Agent': 'CaptainTrain/5221(d109181b0) (iPhone8,4; iOS 13.1.2; Scale/2.00)', 'Accept-Language': 'es', 'Content-Type': 'application/json; charset=UTF-8', 'Host': 'www.trainline.eu', 'authorization': 'Token token="{token}"'.format(token=trainlineRESTApi.APIKey), } getbustrainTripsInformation = Request( name='getbustrainTripsInformationTrainline', description='Get trips information by train or bus', PartToaddToBaseUrl='search', funcToExtractDataFromJsonName='findbustrainTrips', ParamsOrDataDictStructure=dataFindTrip, typeRequests='POST', headers=headersTrainline, RApi=trainlineRESTApi) getStationInformation.save() getbustrainTripsInformation.save()
def test_create_request_rapidly(self): author = User(username='******') author.save() title = "hello world" request = Request(title=title, created_by=author) request.save() all_requests = Request.objects.all() self.assertEquals(len(all_requests), 1) # assert there is only one request self.assertEquals(request, all_requests[0]) # assert this is the first request self.assertEquals(request.title, title) # assert title self.assertEquals(request.slug, slugify(title)) # assert slug self.assertEquals(request.created_by, author) # assert author self.assertEquals(request.status, 100) # default status is opened STATUS_OPENED=100 self.assertEquals(request.created.day, timezone.now().day) # posted today self.assertEquals(request.publish, True) # default is published self.assertSequenceEqual(request.collaborators.all(), []) # assert there are no collaborators self.assertSequenceEqual(request.skills.all(), []) # assert skills are empty self.assertEquals(request.type, None) # assert type in not specified
def make_request(): data = edict(request.get_json()) # data should only contain request type # Check that it is not the same request as an existing one (e.g same user, same room, same request) call_request = Request.query.filter_by(caller=current_user, room=current_user.room, request=data.request).first() if call_request is None: call_request = Request.add(current_user, data) response = jsonify({ "request_id": call_request and call_request.id, "index": call_request and call_request.rank }) Request.check_match_in_room(current_user.room) return response
def post_help_request(): form = RequestForm() if form.validate_on_submit(): address = form.address.data location = get_location(address) Request.add({ "name": form.name.data, "phone": form.phone.data, "address": address, "latitude": location["lat"], "longitude": location["lng"], "category": form.category.data, "request": form.request.data }) flash('You request was successfully saved !', "success") # return redirect(url_for('login.login')) return render_template("get_help.html", form=form)
def create_request(): # this function enables a user create a request request_data = request.get_json() # add the data into the json object requesttype = request_data.get('requesttype') category = request_data.get('category') details = request_data.get('details') """ Capture the length of all_requests list and set it as the first _id """ _id = request_data.get('_id') _id = len(all_requests) _id += 1 # increment by 1 since the initial length is 0 # check if each required field is present in the data if not requesttype: return jsonify({'message': 'Missing request type'}), 400 if not category: return jsonify({'message': 'Missing request category'}), 400 if not details: return jsonify({'message': 'Missing request details'}), 400 if not _id: return jsonify({'message': 'Missing request id'}), 400 # create a new request as an instance of the User_request class new_req = Request(_id, request_data['requesttype'], request_data['category'], request_data['details']) new_req.create_request(request_data['_id'], request_data['requesttype'], request_data['category'], request_data['details']) # append new request to the list all_requests.append(new_req) return jsonify({ 'request': new_request, 'message': 'Request created successfully' }), 201
def seed(num_tests=10, reqs_per_test=100): """ Seed the test database with data by adding a test with a large number of requests Arguments * num_tests - number of tests to insert * reqs_per_test - number of requests to insert per test """ if os.environ['APP_CONFIG_ENV'] != 'config.TestConfig': print('You can only seed the test database.', 'Set APP_CONFIG_ENV environment variable to config.TestConfig', 'and try again.') return test_count = 0 req_count = 0 while test_count < int(num_tests): print(f'Adding test {test_count + 1} with {reqs_per_test} requests') new_test = Test(config=f"Seed {Test.query.count()}", locustfile="locustfile.py", start=now(), end=now(), workers=5000) db.session.add(new_test) db.session.commit() test_id = new_test.id reqs = [] while req_count < int(reqs_per_test): new_request = Request(test_id=test_id, name=f"Seed {req_count}", request_timestamp=now(), request_method="Request Method", request_length=250, response_length=250, response_time=random.normalvariate(240, 1), status_code=200, success=True, exception=None) reqs.append(new_request) req_count += 1 time.sleep(.001) db.session.bulk_save_objects(reqs) db.session.commit() req_count = 0 test_count += 1 print('Finished seeding database')
def get_pedido(request, id_loja): try: req = Request.objects.get(id=request.session['pedido']) try: cliente = request.user.cliente except: cliente = None req.cliente = cliente req.save() return req except (Exception, ): estabelecimento = Estabelecimento.objects.get(id=id_loja) try: cliente = request.user.cliente except: cliente = None pedido = Request(cliente=cliente, estabelecimento=estabelecimento) pedido.save() request.session['pedido'] = pedido.id return pedido
def new_request(): """ Create new request """ form = RequestForm() # Get the csrf_token from the request cookie and put it into the # form manually to validate_on_submit can be used user = None if current_user.is_authenticated: user = current_user.to_dict() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): # Add the user to the session, we are logged in! new_request = Request(title=form.data['title'], active=False, userId=user["id"]) db.session.add(new_request) db.session.commit() return new_request.to_dict() return {'errors': validation_errors_to_error_messages(form.errors)}, 401
def make_hit_request(id): player = Player.query.get(id) form = RequestForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): hit_request = Request(date=form.data['date'], requester_id=current_user.id, requestee_id=id, court_id=form.data['court_id'], response=None) db.session.add(hit_request) db.session.commit() return jsonify(hit_request.to_dict()) else: return ({"errors": "errors"}) return ({"errors": "errors"})
def post_request(): result = request.get_json().get("queryResult") data = result.get("parameters") context_parameters = result["outputContexts"][0].get("parameters") phone = context_parameters.get('caller_id', '') address = data["address"]["city"] + " " + data["address"]["street-address"] location = get_location(address) Request.add({ "name": data["name"]["name"], "phone": phone, "address": address, "latitude": location["lat"], "longitude": location["lng"], "category": data["service"], "request": "" }) return "OK"
def accept_request(id): form = RequestForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): request = Request(user_id=current_user.id, party_id=party_id, message=form.data["message"]) db.session.add(request) db.session.commit() return {"request": {request.id: request.to_dict()}} else: return "Bad Data"
def request_update(id): if not id: return json.dumps({'error': 'incorrect_params'}), 400, { 'ContentType': 'application/json' } if Request.update(id): return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } else: return json.dumps({'error': 'not found'}), 404, { 'ContentType': 'application/json' }
def get(self, current_user, ride_id): '''Gets all requests''' try: request = Request() requests = request.fetch_all() if requests == []: return jsonify({"msg": "You haven't recieved any ride requests yet"}), 200 return jsonify(requests), 200 except Exception as e: response = { 'message': str(e) } return make_response(jsonify(response)), 500
def process_request(self, request): req = Request(request=request) if request.user.is_authenticated(): req.priority = 1 req.save() return None