Exemplo n.º 1
0
    def login(self, email_address, password):
        """Log in a user"""
        url = '{0}/{1}/auth/login'.format(base_url, version)

        credentials = {"email_address": email_address, "password": password}

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.post(url,
                                     data=json.dumps(credentials),
                                     headers=headers,
                                     timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code == 401:
                return None
            else:
                user_dict = json.loads(response.text)
                user = self
                for k, v in user_dict.items():
                    setattr(user, k, v)
                return user
Exemplo n.º 2
0
    def create(self, first_name, last_name, date_of_birth, users):
        """Create a new child."""
        url = '{0}/{1}/children'.format(base_url, version)

        new_child = {
            "first_name": first_name,
            "last_name": last_name,
            "date_of_birth": date_of_birth,
            "users": users
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.post(url,
                                     data=json.dumps(new_child),
                                     headers=headers,
                                     timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 201:
                raise InternalServerError()
            else:
                return json.loads(response.text)
Exemplo n.º 3
0
    def create(self, password, first_name, last_name, email_address):
        """Create a new user."""
        url = '{0}/{1}/users'.format(base_url, version)

        new_user = {
            "password": password,
            "first_name": first_name,
            "last_name": last_name,
            "email_address": email_address
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.post(url,
                                     data=json.dumps(new_user),
                                     headers=headers,
                                     timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 201:
                raise InternalServerError()
            else:
                user_dict = json.loads(response.text)
                user = self
                for k, v in user_dict.items():
                    setattr(user, k, v)
                return user
Exemplo n.º 4
0
    def create(self, user_id, child_id, type, started_at, ended_at, feed_type,
               change_type, amount, unit, side, notes):
        """Create a new event."""
        url = '{0}/{1}/children/{2}/events'.format(base_url, version, child_id)

        new_event = {
            "user_id": user_id,
            "type": type,
            "started_at": started_at,
            "ended_at": ended_at,
            "feed_type": feed_type,
            "change_type": change_type,
            "amount": amount,
            "unit": unit,
            "side": side,
            "notes": notes
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.post(url,
                                     data=json.dumps(new_event),
                                     headers=headers,
                                     timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 201:
                raise InternalServerError()
            else:
                return json.loads(response.text)
Exemplo n.º 5
0
    def __call__(self, environ, start_response):
        if 'wsgi.websocket' in environ:
            ws = environ["wsgi.websocket"]
            while not ws.closed:
                message = self.queue.get()
                try:
                    ws.send(message)
                except WebSocketError:
                    break
            raise RequestTimeout()
        elif environ["PATH_INFO"] == self.js_path:
            if environ.get('HTTP_HOST'):
                base = environ['HTTP_HOST']
            else:
                host = environ['SERVER_NAME']
                port = environ['SERVER_PORT']
                base = ':'.join((host, port))
            response = Response(JAVASCRIPT.format(base=base))
            return response(environ, start_response)

        # request non-compressed response
        http_accept_encoding = environ.pop('HTTP_ACCEPT_ENCODING', '')
        response = Response.from_app(self.app, environ)

        # inject JS
        if response.mimetype == 'text/html':
            response = self.inject(response)

        # compress response, if necessary
        if http_accept_encoding:
            environ['HTTP_ACCEPT_ENCODING'] = http_accept_encoding
        response = gzip()(response)

        return response(environ, start_response)
Exemplo n.º 6
0
    def update_profile(self, id, first_name, last_name, email_address):
        """Update a user."""
        url = '{0}/{1}/users/{2}/profile'.format(base_url, version, str(id))

        updated_profile = {
            "first_name": first_name,
            "last_name": last_name,
            "email_address": email_address
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.put(url,
                                    data=json.dumps(updated_profile),
                                    headers=headers,
                                    timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 200:
                raise InternalServerError()
            else:
                user_dict = json.loads(response.text)
                user = self
                for k, v in user_dict.items():
                    setattr(user, k, v)
                return user
Exemplo n.º 7
0
    async def get_data(self,
                       cache: bool = True,
                       as_text: bool = False,
                       parse_form_data: bool = False) -> AnyStr:
        """Get the request body data.

        Arguments:
            cache: If False the body data will be cleared, resulting in any
                subsequent calls returning an empty AnyStr and reducing
                memory usage.
            as_text: If True the data is returned as a decoded string,
                otherwise raw bytes are returned.
            parse_form_data: Parse the data as form data first, return any
                remaining data.
        """
        if parse_form_data:
            await self._load_form_data()

        try:
            raw_data = await asyncio.wait_for(self.body,
                                              timeout=self.body_timeout)
        except asyncio.TimeoutError:
            raise RequestTimeout()
        else:
            if not cache:
                self.body.clear()

            if as_text:
                return raw_data.decode(self.charset, self.encoding_errors)
            else:
                return raw_data
Exemplo n.º 8
0
    def change_password(self, id, current_password, new_password):
        """Update a user."""
        url = '{0}/{1}/users/{2}/password'.format(base_url, version, str(id))

        updated_profile = {
            "current_password": current_password,
            "new_password": new_password
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.put(url,
                                    data=json.dumps(updated_profile),
                                    headers=headers,
                                    timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code == 401:
                return None
            # Need to handle 400's here too...
            elif response.status_code != 200:
                raise InternalServerError()
            else:
                user_dict = json.loads(response.text)
                user = self
                for k, v in user_dict.items():
                    setattr(user, k, v)
                return user
Exemplo n.º 9
0
    def update(self, id, first_name, last_name, date_of_birth, users):
        """Update a child."""
        url = '{0}/{1}/children/{2}'.format(base_url, version, str(id))

        updated_profile = {
            "first_name": first_name,
            "last_name": last_name,
            "date_of_birth": date_of_birth,
            "users": users
        }

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        try:
            response = requests.put(url,
                                    data=json.dumps(updated_profile),
                                    headers=headers,
                                    timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 200:
                raise InternalServerError()
            else:
                return json.loads(response.text)
Exemplo n.º 10
0
    def delete(self, id):
        """Delete a child."""
        url = '{0}/{1}/children/{2}'.format(base_url, version, str(id))
        headers = {"Accept": "application/json"}

        try:
            response = requests.delete(url, headers=headers, timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 204:
                raise InternalServerError()
            else:
                return True
Exemplo n.º 11
0
    def get_for_user(self, user_id):
        """Get children for a user."""
        url = '{0}/{1}/children?user_id={2}'.format(base_url, version,
                                                    str(user_id))
        headers = {"Accept": "application/json"}

        try:
            response = requests.get(url, headers=headers, timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 200:
                raise InternalServerError()
            else:
                return json.loads(response.text)
Exemplo n.º 12
0
 async def _load_form_data(self) -> None:
     async with self._parsing_lock:
         if self._form is None:
             parser = self.make_form_data_parser()
             try:
                 self._form, self._files = await asyncio.wait_for(
                     parser.parse(
                         self.body,
                         self.mimetype,
                         self.content_length,
                         self.mimetype_params,
                     ),
                     timeout=self.body_timeout,
                 )
             except asyncio.TimeoutError:
                 raise RequestTimeout()
Exemplo n.º 13
0
    def get(self, child_id):
        """Get events for child."""
        url = '{0}/{1}/children/{2}/events'.format(base_url, version, child_id)

        headers = {"Accept": "application/json"}

        try:
            response = requests.get(url, headers=headers, timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code == 404:
                return None
            elif response.status_code != 200:
                raise InternalServerError()
            else:
                return json.loads(response.text)
Exemplo n.º 14
0
    def search(self, email_address):
        """Search for user by email address."""
        url = '{0}/{1}/users?email_address={2}'.format(base_url, version,
                                                       email_address)
        headers = {"Accept": "application/json"}

        try:
            response = requests.get(url, headers=headers, timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code == 404:
                return None
            elif response.status_code != 200:
                raise InternalServerError()
            else:
                user_dict = json.loads(response.text)
                user = self
                for k, v in user_dict.items():
                    setattr(user, k, v)
                return user
Exemplo n.º 15
0
    def get(self, id):
        """Get a user."""
        url = '{0}/{1}/users/{2}'.format(base_url, version, str(id))
        headers = {"Accept": "application/json"}

        try:
            response = requests.get(url, headers=headers, timeout=timeout)
        except requests.exceptions.Timeout:
            raise RequestTimeout()
        else:
            if response.status_code != 200:
                raise InternalServerError()
            else:
                user_dict = json.loads(response.text)
                user = self
                for k, v in user_dict.items():
                    setattr(user, k, v)
                user.created_at = dateutil.parser.parse(user.created_at)
                user.updated_at = dateutil.parser.parse(
                    user.updated_at) if user.updated_at else None
                user.login_at = dateutil.parser.parse(user.login_at)
                return user
Exemplo n.º 16
0
 [
     (
         BadRequest("This is a Bad Request"),
         (
             {
                 "error": {
                     "title": "This is a Bad Request",
                     "status": 400,
                     "details": "()",
                 }
             },
             400,
         ),
     ),
     (
         RequestTimeout("Request has timed out"),
         (
             {
                 "error": {
                     "title": "Request has timed out",
                     "status": 408,
                     "details": "()",
                 }
             },
             408,
         ),
     ),
     (
         BadGateway("This is a Bad Gateway"),
         (
             {
Exemplo n.º 17
0
 def handle_eof_error(e):
     return handle_error(RequestTimeout())