def test_get_description(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) self.assertEqual(twitterProfile.description, "Jugador de Boca Juniors y Piola Vago frontman")
def test_requests(self): request = Request(path = "/foo") request.save() django_response = HttpResponse(self.text) # No rules, should pass self.assertEqual(len(check_request_rules(request, django_response)), 0) # Should have one error now that the status is not 200 django_response.status_code = 442 self.assertEqual(len(check_request_rules(request, django_response)), 1) # set it back for the rest of the tests django_response.status_code = 200 self.assertEqual(len(check_request_rules(request, django_response)), 0) rule1 = RequestRule(request = request, target = "content", operator = "contains", value = "Teletubbies") rule1.save() self.assertEqual(len(check_request_rules(request, django_response)), 0) # add a rule that fails rule2 = RequestRule(request = request, target = "content", operator = "!contains", value = "Teletubbies") rule2.save() self.assertEqual(len(check_request_rules(request, django_response)), 1) # Done testing requests, now test functionality on the models that have been created # str the request to test the __unicode__ method str(request) # Test the display_operator self.assertEqual(rule2.display_operator, "does not contain") rule2.operator='foo' # Should not fail on unrecognized operator self.assertEqual(rule2.display_operator, "foo")
def test_request_completed(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) request = Request.objects.latest() self.assertEqual(request.status, "Completed")
def requestsv2(): if not request.args or not request.args['key'] or request.args['key'] != IOS_API_KEY: abort(401) if request.method == "POST": if not request.json or not 'google_places_id' in request.json or not 'name' in request.json or not 'vicinity' in request.json: abort(400) report_request = Request(google_places_id=request.json['google_places_id'], name=request.json['name'], vicinity=request.json['vicinity']) questions = '' more_questions = '' if 'ios_device_id' in request.json: report_request.populate(ios_device_id=request.json['ios_device_id']) if 'questions' in request.json: report_request.populate(questions=request.json['questions']) questions = request.json['questions'] if 'more_questions' in request.json: report_request.populate(more_questions=request.json['more_questions']) more_questions = request.json['more_questions'] try: report_request.put() sender_address = "Scout Support <*****@*****.**>" user_address = "*****@*****.**" subject = "Update requested at %s" % request.json['name'] body = """Name: %s\nAddress: %s\nQuestions: %s\nMore Questions: %s""" % (request.json['name'], request.json['vicinity'], ', '.join(questions), more_questions) logging.info('questions: %s', ', '.join(questions)) logging.info('more_questions: %s', more_questions) mail.send_mail(sender_address, user_address, subject, body) return jsonify(report_request.to_dict()) except CapabilityDisabledError: abort(400)
def test_request_account_not_found(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) request = Request.objects.latest() self.assertEqual(request.status, "User not found")
def test_request_account_suspended(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) request = Request.objects.latest() self.assertEqual(request.status, "Account suspended")
def create(request): if request.method=='POST': name = request.POST['username'] email = request.POST['email'] sex = request.POST['sex'] mobile_number = request.POST['mobile_number'] exam_city = request.POST['exam_city'] current_city = request.POST['current_city'] exam_date = request.POST['exam_date'] if exam_date == '' or name == '' or email == '' or mobile_number == '' : return render_to_response('share/create.html') else : new_obj = Users(name = name, email = email, sex = sex, mobile_number = mobile_number,exam_city_id = exam_city,exam_date = exam_date, current_city = current_city) new_obj.save() if "requested_to" in request.session: obj = Request(requester = new_obj.id,requested_to = request.session["requested_to"]) obj.save() del request.session["requested_to"] return HttpResponseRedirect('/thanks/') return HttpResponseRedirect('/thankyou/') if "exam_city" in request.session: return render_to_response('share/create.html',{'exists':1,'exam_date':request.session["exam_date"]}) return render_to_response('share/create.html',{'exists':0})
def test_get_valid_profile1(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) self.assertEqual(twitterProfile.name, "Mauricio Morero (@maurimorero) | Twitter")
def get(self): user = self.user_model get_notifications(user) current_date = datetime.datetime.now() - datetime.timedelta(hours=8) all_requests = Request.query(Request.start_time >= current_date).order(Request.start_time) all_requests = [r for r in all_requests if r.sender != user.key] pending_requests = Request.query(Request.status == 'pending').order(Request.start_time) pending_requests = [r for r in pending_requests if r.start_time < current_date] # Sort by food type type_sort = sorted(all_requests, key=lambda x:x.food_type) types = {} for r in type_sort: # Get all types if r.food_type not in types: types[r.food_type] = [] for r in type_sort: for t in types: if r.food_type == t: types[t].append(r) break self.response.out.write(template.render('views/feed.html', {'user': user, 'pending_requests': pending_requests, 'all_requests': all_requests, 'food_type':types}))
def test_get_valid_profile2(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) self.assertEqual(twitterProfile.name, "Diario Olé (@DiarioOle) | Twitter")
def get(self, url): ip = self.request.remote_addr #to prevent abuses, only a request every minute is served request = Request.gql("where ip='%s'" % ip).get() #Look for request from the same IP address if not request is None: delta = request.is_allowed() if delta > 0: #too little time has passed from the previous request #self.error(408) #Timeout Error self.response.set_status(408, "Your IP address has issued a request less than 1 min ago. Please wait %d seconds" % delta) return else: request = Request(ip=ip, page_crawled=url) request.save() self.response.headers['Content-Type'] = 'application/json' handler = CrawlerHandler() site_image = memcache.get(url) if site_image is None: home_page = handler.start_crawling(url, MAX_PAGE_DEPTH, MAX_PAGES_TO_CRAWL, 0.01) #causes a little delay, but not too big (one 100th of a sec) if home_page is None: self.error(400) #Bad Request return else: site_image = handler.page_graph(home_page) memcache.set(url, site_image) self.__responde(site_image)
def test_login_as(self): user = User.objects.create_user(username = TEST_USER, password = TEST_PASS, email = TEST_USER) request = Request(path = "/foo", login_as_user = user) request.save() response = create_django_response(request) self.assertTrue(response.context["user"].is_authenticated())
def requests(): '''Route to Requests Collection.''' if ('past' == request.args.get('date')): requests = Request.get_past_reqs() else: requests = Request.get_open_reqs() user = g.user return render_template('request/requests.html', requests=requests, user=user)
def process_request(self, request): method = request.method path = request.path time = datetime.now().strftime('%d/%b/%Y %H:%M:%S') if not request.is_ajax() and path != '/requests/': request = Request(method=method, path=path, time=time) request.save()
def test_get_imageURI(self): request = Request() request.username = "******" request.save() twitterProfile = GetTwitterProfile(request) self.assertEqual( twitterProfile.imageURI, "https://pbs.twimg.com/profile_images/959194538182103041/q6heJEdD_400x400.jpg" )
def test_login_as(self): user = User.objects.create_user(username=TEST_USER, password=TEST_PASS, email=TEST_USER) request = Request(path="/foo", login_as_user=user) request.save() response = create_django_response(request) self.assertTrue(response.context["user"].is_authenticated())
def process_request(self, request): data = {} data['Path'] = request.path data['Method'] = request.method data['Meta'] = str(request.META) req = Request(request=data) if request.user.is_authenticated(): req.priority = 1 req.save() return None
def login(): # first check if this ip should be banned r = Request.query.filter_by(request_addr=request.remote_addr).first() if r == None: r = Request(request_addr=request.remote_addr) db.session.add(r) db.session.commit() else: r.attempts += 1 should_ban = True if r.attempts > 3 else False if should_ban: r.banned_until = datetime.now() + timedelta(hours=1) # remove the ban after 1 hour oneHourInSecond = 1 * 60 * 60 threading.Timer(oneHourInSecond, remove_ban, (request.remote_addr, )).start() db.session.add(r) db.session.commit() if should_ban: abort(403) if current_user.is_authenticated: return render_template(url_for('index')) form = PNOForm() if form.validate_on_submit(): pno = form.pno.data user = User.get_by_pno(pno) # user has registered before if user is not None: session['pno'] = pno return redirect(url_for('login4')) # no such user ever existed else: user = User(pno) db.session.add(user) db.session.commit() # generate random for verification code # not doing anything for now, reserved for future probably rand = randint(1000, 9999) flash('this is your verification code: {}'.format(rand)) session['pno'] = pno session['verif_code'] = rand return redirect(url_for('login2')) return render_template('index.html') return render_template('login.html', form=form)
def get(self): current_time = datetime.datetime.now() - datetime.timedelta(hours=8) max_time = current_time + datetime.timedelta(hours=1) dead_accepted_requests = Request.query(Request.start_time > current_time, Request.start_time < max_time).fetch() dead_accepted_requests = [x for x in dead_accepted_requests if x.status == "sms" and x.recipient != None] for request in dead_accepted_requests: request.status = "dead" dead_requests = Request.query(Request.start_time < current_time).fetch() dead_requests = [x for x in dead_requests if x.status == "waiting for a bid" or x.status =="pending"] for request in dead_requests: print "Removing request: " + str(request) request.key.delete()
def getallrequests(): roles = g.jwt_oidc_token_info['realm_access']['roles'] userid = g.jwt_oidc_token_info['sub'] userrole = 'user_role' approverrole = 'approver_role' if userrole in roles: requests = Request.get_requests_by_user(userid) elif approverrole in roles: requests = Request.get_requests_by_role() else: requests = Request.get_requests() jsondata = json.dumps(requests) return jsondata, 200
def starting_page(): print 'Submitting a task' r = Request() r.name = 'Some random name' db.session.add(r) db.session.commit() context = dict() context['id'] = r.id db.session.close() db.session.remove() run_workflow(context) return ('Task submitted %r' % context['id']), 201
def TakeRequest(request, url): request_url = URL(url) robj = Request.objects.filter(target__contains=request_url.host) if not robj: r = Request(request_type='HttpRequest', storage_type='UrlStorage', action='mirror', target=request_url.host, flag='requested') else: r = robj[0] r.flag = 'requested' r.save() return HttpResponseRedirect('http://%s/%s' % (getifip(web_server_interface), request_url.with_www().replace('http://', '')))
def test_request_model_does_not_find_row_if_it_does_not_exist(initialize_db): """ Tests that model does not find row correctly if it does not exist in the db. Args: initialize_db (None): initializes the database and drops tables when test function finishes. """ with raises(ClientError) as err: Request.find_by_id(1) assert err.value.message == 'cannot find specified request' assert err.value.status_code == 404
def get_notifications(user): #Get Requests for Notifications accepted_requests = [] new_requests = [] current_time = datetime.datetime.now() - datetime.timedelta(hours=8) # Check for last login/update check_time = user.last_check print "Last Check: " , check_time if check_time is None: # Pull all results from previous week check_time = datetime.datetime.now() - datetime.timedelta(days=7, hours=8) print "Updated time: ", check_time # New requests available_requests = Request.query(Request.sender != user.key).fetch() available_requests = [r for r in available_requests if r.creation_time >= check_time] available_requests = [r for r in available_requests if r.start_time >= current_time] available_requests = [r for r in available_requests if r.recipient == None] # Approved requests approved_requests = Request.query(Request.recipient == user.key).fetch() approved_requests = [r for r in approved_requests if r.accept_time != None] approved_requests = [r for r in approved_requests if r.start_time >= current_time] approved_requests = [r for r in approved_requests if r.accept_time >= check_time] # Pending requests pend_requests = Request.query(Request.sender == user.key).fetch() pend_requests = [r for r in pend_requests if r.start_time >= current_time] pend_requests = [r for r in pend_requests if len(r.bidders) > 0] new_bidders = 0 if len(pend_requests) > 0: for r in pend_requests: for bid in r.bidders: bid = bid.get() if bid.bid_time != None: if bid.bid_time > check_time: print "Bid Time: " , bid.bid_time new_bidders += 1 else: pend_requests = [r for r in pend_requests if r.creation_time >= check_time] print "No bidders: ", pend_requests user.pending_requests = new_bidders user.available_requests = len(available_requests) print len(available_requests) user.approved_requests = len(approved_requests) print len(approved_requests) user.put() print "user updated"
def api_view_request(request_rid): check_admin() request = Request.find_by('where rid = ?', request_rid) response = Response.find_by('where rid = ?', request_rid) if request is None or response is None: raise notfound() return dict(request=content_escape(request), response=html_encode(response))
def fetch_request(self, username): cursor = self.conn.execute( """ SELECT * FROM request where status == 0 AND to_user = (?)""", (username, )) donations = [] consumptions = [] for row in cursor: request_id = row[0] from_user = row[1] # to_user = row[2] appointment_date = row[3] appointment_time = row[4] request_type = row[5] beneficiary = row[6] frequency = row[7] description = row[8] status = row[9] create_date = row[10] new_request = Request(from_user, username, appointment_date, appointment_time, request_type, beneficiary, frequency, description, status, create_date, request_id) if request_type == constants.REQUEST_DONATION: donations.append(new_request) else: consumptions.append(new_request) return donations, consumptions
def submit_donate_request(): if session['logged_in'] and request.method == 'POST': from_user = session['username'] to_user = request.form['to_user'] appointment_date = request.form['date'] appointment_time = request.form['time'] request_type = constants.REQUEST_DONATION beneficiary = request.form['beneficiary'] frequency = request.form['frequency'] description = request.form['description'] food_item_id = request.form['food_item_id'] category_id = request.form['category_id'] quantity = request.form['quantity'] weight = request.form['weight'] expiry_date = request.form['expiry_date'] new_request = Request(from_user, to_user, appointment_date, appointment_time, request_type, beneficiary, frequency, description, constants.REQUEST_PENDING) request_id = db.create_request_header(new_request) new_request_detail = Request_Detail(request_id, food_item_id, category_id, quantity, weight, expiry_date) db.create_request_detail_entry(new_request_detail) return "succeed"
def render_request_done(): # Если данные не были отправлены if request.method != "POST": abort(404) # Если данные были отправлены form = RequestForm() if not form.validate_on_submit(): # отправляем форму назад return render_template('request.html', form=form) # получаем данные client_name = form.clientName.data client_phone = form.clientPhone.data client_goal = form.clientGoal.data client_time = form.clientTime.data time = next((t[1] for t in form.clientTime.choices if t[0] == client_time), -1) goal = Goal.query.filter(Goal.code == client_goal).scalar() request_t = Request(name=client_name, phone=client_phone, goal=goal.goal, time=time) db.session.add(request_t) db.session.commit() # переходим на request_done return render_template('request_done.html', clientName=client_name, clientPhone=client_phone, clientGoal=request_t.goal, clientTime=request_t.time)
def update_request(id): user = g.user req = session.query(Request).filter( and_(Request.id == id, user.id != Request.user_id)) if not req: abort(400) errors = Request.validate(request.json) if len(errors) == 0: meal_type = request.json.get('meal_type') location_string = request.json.get('location_string') latitude = request.json.get('latitude') longitude = request.json.get('longitude') meal_time = request.json.get('meal_time') new_req = { 'meal_type': meal_type, 'meal_time': meal_time, 'latitude': latitude, 'longitude': longitude, 'location_string': location_string } req.update(new_req) session.commit() return jsonify({'response': True}) else: return jsonify({'errors': errors}), 400
def multiple_valid_request_models(multiple_valid_client_models, multiple_valid_staff_models): """ A fixture for creating a multiple valid requests. Args: multiple_valid_client_models (list): a list of valid client models created by a fixture. multiple_valid_staff_models (list): a list of valid staff models created by a fixture. """ requests = [ Request( title='Improve customer care services', description='The current customer care services are reported to ' 'be abysmal with representatives dropping calls on customer or ' 'being rather unpleasant.', product_area=ProductArea.POLICIES, target_date=datetime.utcnow(), priority=i, staff_id=1, client_id=1, ).save() for i in range(12) ] return requests
def addARequest(user_id): if request.method == 'POST': phone_no = request.json.get('phone_no') delivery_state = request.json.get('delivery_state') delivery_city = request.json.get('delivery_city') item_location_state = request.json.get('item_location_state') item_location_city = request.json.get('item_location_city') posted_on = request.json.get('posted_on') deliver_before = request.json.get('deliver_before') picture = request.json.get('picture') offer_amount = request.json.get('offer_amount') time_updated = request.json.get('time_updated') item_name = request.json.get('item_name') user = session.query(User).filter_by(id=user_id).first() profile_image = user.picture user_first_name = user.first_name user_last_name = user.last_name user_id = user_id newRequest = Request(phone_no=phone_no, delivery_state=delivery_state, delivery_city=delivery_city, item_location_state=item_location_state, item_location_city=item_location_city, deliver_before=deliver_before, posted_on=posted_on, time_updated=time_updated, profile_image=profile_image, user_id=user_id, user_first_name=user.first_name, user_last_name=user.last_name, item_name=item_name, offer_amount=offer_amount, picture=picture) session.add(newRequest) session.commit() payload = {} payload['profile_image'] = user.picture payload['id'] = newRequest.id payload['phone_no'] = phone_no payload['delivery_state'] = delivery_state payload['delivery_city'] = delivery_city payload['item_location_state'] = item_location_state payload['item_location_city'] = item_location_city payload['deliver_before'] = deliver_before payload['posted_on'] = posted_on payload['offer_amount'] = offer_amount payload['item_name'] = item_name payload['time_updated'] = time_updated payload['picture'] = picture payload['user_id'] = user_id payload['user_first_name'] = user_first_name payload['user_last_name'] = user.last_name raw = {"data": payload} request_data = json.dumps(raw) #result = push_service.notify_single_device(registration_id = reg_id, data_message= payload) result = push_service.notify_topic_subscribers( topic_name=REQUEST_TOPIC, data_message=payload) pprint(result) return request_data
def request_from(): """ request money from a new Mutual Aid """ user_id = request.args.get('user_id', None) situation = request.args.get('situation', None) identities = request.args.get('identities', None) amount = request.args.get('amount', None) venmo_username = request.args.get('venmo_username', None) #Keeping this here as a note to how to get the elements of the identity #identities_array = re.split(', |,',identities) user = User.query.filter_by(id=user_id).first() if user is None: return "Could not find a mutual aid by that id", 404 request_obj = Request(situation=situation, identities=identities, amount=amount, user_id=user_id, venmo_username=venmo_username) db.session.add(request_obj) db.session.commit() #return the id so the requestor can search up their 'ticket' and know their progress return jsonify(id=request_obj.id), 200
def test_flask_seed_model_cli_seeds_to_db_with_all_option(cli_app): """ Tests that db tables are populated `flask seed model` when passed an `all` option. Args: cli_app (function): a flask app factory function that also manages its context. """ # Create a script for running application. obj = ScriptInfo(create_app=cli_app) # Call command, apply arguments and create app. result = CliRunner().invoke(seed_model, ['all'], obj=obj) clients = Client.get_all() staff = Staff.get_all() requests = Request.get_all() comments = Comment.get_all() assert len(clients) == 3 assert len(staff) == 3 assert len(comments) == 14 assert len(requests) == 12 assert result.exit_code == 0
def test_create_django_response(self): request = Request(path="/foo") response = create_django_response(request) self.assertEqual(response.status_code, 404, "status code on create_django_response") self.assertTrue("File not found" in response.content, "content on create_django_response")
def add_request(): if request.method == 'POST': data = request.get_json() req1 = Request(day=data["daySelect"], requester=data["requester"], startTime=data["startTime"], endTime=data["endTime"], reason=data["reason"], weekly=data["weekly"], status=False) db.session.add(req1) db.session.commit() print(Request.query.all()) req = Request.query.all() newls = [] for i in range(len(req)): newls.append({}) newls[i]["id"] = req[i].id newls[i]["day"] = req[i].day newls[i]["requester"] = req[i].requester newls[i]["startTime"] = req[i].startTime newls[i]["endTime"] = req[i].endTime newls[i]["reason"] = req[i].reason newls[i]["status"] = req[i].status newls[i]["weekly"] = req[i].weekly return json.dumps(newls)
def requestsEliminator(msgBody, reqer): text = msgBody['Body'].lower() numOfMedia = msgBody['NumMedia'] if numOfMedia == '0' and len(text) < 10: # change latter to 150 Request(requester=reqer, message=str(msgBody), status=99).save() return True return False
def save_request(request_data): """ Reorders entries for a client if priority already exists and saves new request. Args: request_data (dict): request data to be saved. """ priority = request_data['priority'] client_id = request_data['client_id'] # Check for row with similar priority request = Request.query.filter_by(client_id=client_id, priority=priority).all() # Update every duplicate we find. while request: # Increment priority. priority += 1 # Check for row with the newly updated priority value. new_request = Request.query.filter_by(client_id=client_id, priority=priority).all() # Update request with previous priority value. request[0].update(priority=priority) # Update request request = new_request Request(**request_data).save()
def registerOptimizationRequest(request, user): assert user is not None ip = RequestUtils.getIPAddress(request) url = request.get_full_path() req = Request(ip=ip, url=url, request_user=user) req.save() optreq = OptimizationRequest(ip=ip, url=url, request=req, request_user=user) #req = Request(ip=ip,url=url,request_user = user) optreq.save() return optreq.id
def get(self): user = self.user_model date = cgi.escape(self.request.get("date")) time = cgi.escape(self.request.get("time")) active_request = cgi.escape(self.request.get("edit_request")) if active_request: edit_request = ndb.Key(urlsafe=active_request).get() # Check for lack of values if len(date) < 1: if active_request: date = edit_request.start_time.strftime("%Y-%m-%d") else: self.response.out.write('Please choose date') # Convert date and time to datetime format_date = str(date+ " " +time+":00.0") start_time = datetime.datetime.strptime(format_date, "%Y-%m-%d %H:%M:%S.%f") # Check for current request within time limit ongoing_request = Request.query(Request.sender == user.key).fetch() # Remove current request if applicable if active_request: ongoing_request.remove(edit_request) alloted_date = start_time + datetime.timedelta(minutes=20) #Max limit create = timeCheck(ongoing_request, alloted_date, start_time) if create is True: self.response.out.write('Available') else: self.response.out.write('Time Already Passed/Reserved')
def get(self, id): try: currentRequest = Request.get(id = id) except peewee.DoesNotExist: abort(404, message="Request {} doesn't exist".format(args.request_id)) return currentRequest
def authentication_request_get(message): ''' This is the url that other system uses to redirect the user in order to authenticate them ''' try: message = JWS().verify_compact(message, keys=[public_key]) except BadSignature: return "Signature invalid" # todo check whether signed correctly raise BadSignature satosa_request = Request(message) user = database.get_user(satosa_request.userId) if not database.request_exists(satosa_request): database.save_request(satosa_request) else: return "REPLAY ATTACK" if not user: database.save_user(satosa_request.userId) new_user = database.get_user(satosa_request.userId) login_user(new_user) return render_template('satosa_registration_index.html', username1=satosa_request.userId, redirect_url1=cfg['caller']['callback-url']) if len(database.get_credentials(satosa_request.userId)) == 0: new_user = database.get_user(satosa_request.userId) login_user(new_user) return render_template('satosa_registration_index.html', username1=satosa_request.userId, redirect_url1=cfg['caller']['callback-url']) if cfg['host']['turn-off'] and database.is_turned_off(user.id): database.turn_on(user.id) login_user(user) satosa_request = Request() satosa_request.userId = user.id database.make_success(satosa_request) username = current_user.id credentials_array = database.get_credentials(username) return render_template("credentials.html", credentials=credentials_array, username1=username, url=ORIGIN, turn_off=cfg['host']['turn-off'], timeout=int( cfg['host']['turn-off-timeout-seconds'])) return render_template('satosa_index.html', username1=satosa_request.userId, redirect_url1=cfg['caller']['callback-url'])
def post(self): data = request.get_json() loggedInUser = User.query.filter_by(id=LOGGED_IN_USER).first() req = Request(str(loggedInUser.id), str(data['driver']), str(data['rating'])) db.session.add(req) db.session.commit() return
async def take_turn(self, message): player = getattr(self.game, f"player_{message.body['player_id']}") player.drawing_block() await self.pick_block(player=player, index=message.body['block_index']) request = await player.ws.recv() request = Request.deserialize(value=request) guess = Guess(**request.body) await self.guess_block(player, guess=guess)
def api_request(): """Send user's search request""" request_text = request.values.get('request') result = { 'ok': 1, 'request_id': -1 } # create request_id in DB try: session_key = request.cookies.get('beaker.session.id') # session_key = request.cookies.get('sessionid') request_obj = Request( request=request_text, session=session_key ) db.session.add(request_obj) db.session.commit() print("Created %s" % str(request_obj)) result['request_id'] = request_obj.id except Exception as ex: print(ex) # associate all found results with this request_id results = [] t = [] try: t = translate(request_text) except Exception as ex: print("Translation failed: %s" % str(ex)) pg_conn = psycopg2.connect( get_pg_connection_string( app.config['DBHOST'], app.config['DBNAME'], app.config['DBUSER'], app.config['DBPASS'])) cur = pg_conn.cursor() if t and isinstance(t, str): t = t.strip().replace('\n', ' ').replace('[1m', '').replace('[0m', '').replace('OOV', "'OOV' OR 1 = 1") t = t.split(';') results_count = float(len(t)) for i, r in enumerate(t): if r: results.append(Result(request_obj.id, r, results_count - float(i), resolve_report_type(cur, r))) for r in results: db.session.add(r) db.session.commit() return jsonify(result)
def get(self): current_time = datetime.datetime.now() - datetime.timedelta(hours=8) # Get all requests in accepted state completed_requests = Request.query(Request.status == "foodie").fetch() #completed_requests = [x for x in completed_requests if x.start_time + datetime.timedelta(minutes=10) < current_time] for request in completed_requests: send_fire_notification(request) request.status = "attempt_fire" request.put()
def update_request(id): user = g.user if not request.json: abort(400) errors = Request.validate(request.json) if len(errors) == 0: return jsonify( { 'result': True } ) return jsonify({"message": "The request is invalid."},errors = [error for error in errors]) ,400
def local_search(request, place_type): if request.GET.get('coords', ''): form = SearchForm(request.GET) if form.is_valid(): (lat,lon) = form.cleaned_data['coords'].split(',') search_point = Point(float(lat),float(lon)) r = Request(point=search_point, place_type=place_type) r.save() places = Place.objects.distance(search_point).filter(place_type=place_type).filter(point__distance_lte=(search_point, distance(mi=2))).order_by('distance') return render_to_response('_local_search.html', { 'title': place_type, 'places': places }) else: form = SearchForm() return render_to_response('search.html', { 'form': form, })
def lookup(request): if request.GET.get('coords', ''): form = SearchForm(request.GET) if form.is_valid(): (lat,lon) = form.cleaned_data['coords'].split(',') pnt=Point(float(lat),float(lon)) n = get_neighborhood_by_point(pnt) r = Request(point=pnt, place_type="neighborhood") r.save() search_response = {'name': n.name.title(), 'polygon': n.gpoly(), 'slug': n.slug, 'wiki': n.wiki, 'centroid_x': "%.5f" % n.poly.centroid.x, 'centroid_y': "%.5f" % n.poly.centroid.y} return HttpResponse(simplejson.dumps(search_response), mimetype='application/json') else: form = SearchForm() return render_to_response('search.html', { 'form': form, })
def post(self): args = request_parser.parse_args() try: currentRequest = Request.get(id = args.request_id) currentRequest.status = 1 # status: the request is canceled currentRequest.save() except peewee.DoesNotExist: abort(404, message="Request {} doesn't exist".format(args.request_id)) return args.request_id, 200
def post(self): args = request_parser.parse_args() try: currentRequest = Request.get(id = args.request_id) currentRequest.current_latitude = args.current_latitude currentRequest.current_longitude = args.current_longitude currentRequest.save() except peewee.DoesNotExist: abort(404, message="Request {} doesn't exist".format(args.request_id)) return currentRequest.id, 200
def details(id, page=20): actor = Schedule.select().where(Schedule.id == id).get() actor_requests = Request.select().where(Request.url_id == id).order_by(Request.insert_date.desc()) pages = PaginatedQuery(actor_requests, page) content = pages.get_list() stats = {} stats['site_changes'] = actor_requests.select(Request.content_len).distinct().count() stats['total_hits'] = actor_requests.count() stats['ok_hits'] = actor_requests.select(Request.id).where(Request.status_code == '200').count() stats['avg_response_time'] = (sum([row.response_time for row in actor_requests])/stats['total_hits']) return render_template('details.html', actor=actor, actor_requests=content, pages=pages, stats=stats)
def post(self): args = request_parser.parse_args() try: currentRequest = Request.get(id = args.request_id) currentRequest.status = 6 # status: the request is closed currentRequest.board_price = args.end_price_estimate currentRequest.product = args.product_id currentRequest.save() except peewee.DoesNotExist: abort(404, message="Request {} doesn't exist".format(args.request_id)) return args.request_id, 200
def get(self): current_time = datetime.datetime.now() - datetime.timedelta(hours=8) # 5 min before current min_time = current_time - datetime.timedelta(minutes=5) # 5 min after current max_time = current_time + datetime.timedelta(minutes=5) # Get all requests in accepted state completed_requests = Request.query(Request.status == "accepted").fetch() completed_requests = [x for x in completed_requests if x.recipient != None] #completed_requests = [x for x in completed_requests if x.start_time >= min_time and x.start_time < max_time] for request in completed_requests: send_sms(request) request.status = "sms" request.put()
def post(self): args = request_parser.parse_args() currentRequest = Request.create(user = args.user_id, depart_latitude = args.start_latitude, depart_longitude = args.start_longitude, request_time = datetime.datetime.now(), dest_latitude = args.end_latitude, dest_longitude = args.end_longitude, accept_price = args.target_price, depart_price = args.start_price_estimate, current_latitude = args.start_latitude, current_longitude = args.start_longitude, status = 3) return currentRequest.id, 200
def services(request): r = Request(request_method=request.method, request_path=request.path, request_accept=request.META['HTTP_ACCEPT'], request_body=request.body) try: action = Action.objects.get(request_method=request.method, request_path=request.path, request_accept=request.META['HTTP_ACCEPT']) except ObjectDoesNotExist: r.response_status_code = 404 r.save() return HttpResponse(status=404) else: r.response_status_code = action.response_status_code r.response_content = action.response_content r.response_content_type = action.response_content_type r.save() return HttpResponse(status=action.response_status_code, content=action.response_content, content_type=action.response_content_type)
def new_request(): user = g.user if not request.json: abort(400) errors = Request.validate(request.json) if len(errors) == 0: meal_type = request.json.get('meal_type') longitude = request.json.get('longitude') latitude = request.json.get('latitude') location_string = request.json.get('location_string') meal_time = request.json.get('meal_time') r = Request(user_id = user.id,meal_type = meal_type, longitude = longitude, latitude = latitude, location_string = location_string, meal_time = meal_time) session.add(r) session.commit() return jsonify( { 'result': True } ),201 return jsonify({"message": "The request is invalid."},errors = [error for error in errors]) ,400
def home(request): if request.method == 'POST': song_req = Request() song_req.user = request.POST.get('user', '') song_req.song = request.POST.get('song', '') song_req.message = request.POST.get('message', '') song_req.save() else: req = get_latest_request() listeners = get_listeners() title = get_title() return render_to_response('home.html', {'latest':req, 'listeners':listeners, 'title':title})
def process_request(self, request): path_info = request.META['PATH_INFO'] exlude_list = [reverse('request-counter'), reverse('admin:jsi18n'), settings.MEDIA_URL, settings.STATIC_URL] if not any(url in path_info for url in exlude_list): new_http_request = Request() new_http_request.method = request.META['REQUEST_METHOD'] new_http_request.path_info = path_info new_http_request.server_protocol = request.META['SERVER_PROTOCOL'] new_http_request.viewed = False new_http_request.save()