def on_post(self, req, resp): print(json.dumps(req.params)) if self.geodata is None: self.geodata = GeoData() query = req.get_param('Body').strip() try: location = geolocate(query) except LocationNotFound: raise falcon.HTTPStatus( falcon.HTTP_200, body=f"I could not find the location: {query}") except Exception as e: print(e) raise falcon.HTTPStatus( falcon.HTTP_200, body="Sorry, I having some technical trouble right now.") place_type = location['place_type'][0] response_class = self.type_dispatch.get(place_type, GenericResponse) response = response_class(query, location, self.geodata) resp.body = str(response)
async def _check_error(req, isasync): assert (await req.get_media(42)) if isasync else req.get_media(42) == 42 try: (await req.get_media()) if isasync else req.get_media() except falcon.MediaNotFoundError: raise falcon.HTTPStatus(falcon.HTTP_749) raise falcon.HTTPStatus(falcon.HTTP_703)
def process_resource(self, request, response, resource, params): if request.url.endswith('/user') or request.url.endswith( '/auth') or request.url.endswith('/'): return if 'budgetapp_login' not in request.cookies: raise falcon.HTTPStatus(falcon.HTTP_UNAUTHORIZED) id = int(request.cookies['budgetapp_login']) if id <= 0: raise falcon.HTTPStatus(falcon.HTTP_UNAUTHORIZED)
def check_empty_input(req, resp, resource, params): '''Hook to intercept empty messages or messages with predictable greetings''' greetings = {'hello', 'hi', 'help'} query = req.get_param('Body') and req.get_param('Body').strip() if not query or query.lower() in greetings: body = "Hello. Please tell me the town and state you are in. For example, 'Anchorage, AK'" raise falcon.HTTPStatus(falcon.HTTP_200, body=body) elif len(query) < 3: body = "Hmm, that seems a little vague. Try sending a city and state such as 'Anchorage, AK'" raise falcon.HTTPStatus(falcon.HTTP_200, body=body)
def process_request(self, req, resp): resp.set_header('Access-Control-Allow-Origin', '*') resp.set_header('Access-Control-Allow-Methods', '*') resp.set_header('Access-Control-Allow-Headers', '*') resp.set_header('Access-Control-Max-Age', 1728000) # 20 days if req.method == 'OPTIONS': raise falcon.HTTPStatus(falcon.HTTP_200, body='\n')
def process_request(self, req, resp): resp.set_header('Access-Control-Allow-Origin', '*') resp.set_header('Access-Control-Allow-Methods', 'DELETE, PUT, POST, GET') resp.set_header('Access-Control-Allow-Headers', 'content-type, apisid, publickey, sessionid') resp.set_header('Access-Control-Expose-Headers', '*') resp.set_header('Access-Control-Max-Age', 1728000) if req.method == 'OPTIONS': raise falcon.HTTPStatus(falcon.HTTP_200, body='\n')
def on_post(self, req, resp): print(json.dumps(req.params)) if self.geodata is None: self.geodata = GeoData() query = req.get_param('Body').strip() location = self.geodata.query_location(query) if location is None: raise falcon.HTTPStatus(falcon.HTTP_200, body=f"I could not find the location: {query}") r = self.geodata.native_land_from_point(location['latitude'], location['longitude']) if not r: body = f"Sorry, I could not find anything about {location['city']}, {location['state']}." raise falcon.HTTPStatus(falcon.HTTP_200, body=body) resp.body = response_from_locations(location, r)
def on_put(self, request, response): ''' Register ''' first_name = request.media.get('first_name', '') last_name = request.media.get('last_name', '') username = request.media['username'] password = request.media['password'] if first_name is None or last_name is None: response.media = json.dumps({ 'Success': False, 'Message': 'Empty first or last name' }) raise falcon.HTTPStatus(falcon.HTTP_OK) if username is None or password is None: response.media = json.dumps({ 'Success': False, 'Message': 'Empty username or password' }) raise falcon.HTTPStatus(falcon.HTTP_OK) id = self._user_repo.register_user(first_name, last_name, username, password) response.media = json.dumps({'Success': True, 'Message': id})
def process_request(self, req, resp): prefixed = req.path.startswith(self.static_url) if not prefixed: return stripped = req.path.replace(self.static_url, '') cleaned = self.clean_path(stripped) path = self.static_folder.joinpath(cleaned).resolve() try: resp.stream = open(str(path), 'rb') except FileNotFoundError: raise falcon.HTTPNotFound() resp.content_type = self.extension_content_types.get( path.suffix.lstrip('.'), 'application/octet-stream') raise falcon.HTTPStatus('200 OK')
def process_resource(self, req, resp, resource, params): should_parse = ( # Veriy that it is safe to parse this resource req.method in ('POST', 'PUT'), # If there is no data in the body, there is nothing to look at bool(req.content_length), # If the resource doesn't have a schema the loading would be impossible hasattr(resource, 'schema'), # If the resource has turned off auto marshaling getattr(resource, 'auto_marshall', True), # Only consider JSON requests for auto-parsing (req.content_type and req.content_type.startswith('application/json')), ) # Check that all the conditions for parsing are met if not all(should_parse): req.context['_marshalled'] = False return req.context['marshalled_stream'] = req.stream.read() data = req._media = ujson.loads(req.context['marshalled_stream']) loaded = (self._default_load(data, req, resource, params) if not hasattr(resource, 'schema_loader') else resource.schema_loader(data, req, resource, params)) if loaded.errors: # This should probably return whatever the accept header indicates raise falcon.HTTPStatus( falcon.HTTP_400, headers={'Content-Type': 'application/json'}, body=ujson.dumps({'errors': loaded.errors}), ) req.context['dto'] = loaded req.context['_marshalled'] = True
async def _http_error_handler_async(error, req, resp, params): raise falcon.HTTPStatus(falcon.HTTP_201)
def process_response(self, req, resp, resource, req_succeeded): raise falcon.HTTPStatus(falcon.HTTP_201)
def on_get(self, req, resp): raise falcon.HTTPStatus("748 Confounded by ponies")
def on_post(self, request, response): response.unset_cookie('budgetapp_login') raise falcon.HTTPStatus(falcon.HTTP_OK)
def _bad_token(error): body = json.dumps({'message': str(error)}) return falcon.HTTPStatus(falcon.HTTP_401, body=body)
def process_resource(self, request, response, resource, params): super().process_resource(request, response, resource, params) # Raise 200 for OPTIONS requests so middleware lower in the stack are skipped if request.method == 'OPTIONS': raise falcon.HTTPStatus(falcon.HTTP_OK)