How to use the typedload.load function in typedload

To help you get started, we’ve selected a few typedload examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ltworf / typedload / tests / test_legacytuples_dataloader.py View on Github external
def test_kwargs(self):
        with self.assertRaises(ValueError):
            load(1, str, basiccast=False)
            load(1, int, handlers=[])
github ltworf / typedload / tests / test_dataclass.py View on Github external
def test_nestedload(self):
        @dataclass
        class A:
            a: int
            b: str
        @dataclass
        class B:
            a: A
            b: List[A]

        assert load({'a': {'a': 101, 'b': 'ciao'}, 'b': []}, B) == B(A(101, 'ciao'), [])
        assert load(
            {'a': {'a': 101, 'b': 'ciao'}, 'b': [{'a': 1, 'b': 'a'},{'a': 0, 'b': 'b'}]},
            B
        ) == B(A(101, 'ciao'), [A(1, 'a'),A(0, 'b')])
github ltworf / typedload / tests / test_dataclass.py View on Github external
def test_mangle_load(self):
        @dataclass
        class Mangle:
            value: int = field(metadata={'name': 'va.lue'})
        assert load({'va.lue': 1}, Mangle) == Mangle(1)
        assert dump(Mangle(1)) == {'va.lue': 1}
github ltworf / localslackirc / slack.py View on Github external
async def get_file(self, f: Union[FileShared, str]) -> File:
        """
        Returns a file object
        """
        fileid = f if isinstance(f, str) else f.file_id
        r = await self.client.api_call("files.info", file=fileid)
        response = load(r, Response)
        if response.ok:
            return load(r['file'], File)
        else:
            raise KeyError(response)
github ltworf / localslackirc / slack.py View on Github external
async def get_user(self, id_: str) -> User:
        """
        Returns a user object from a slack user id

        raises KeyError if it does not exist
        """
        if id_ in self._usercache:
            return self._usercache[id_]

        r = await self.client.api_call("users.info", user=id_)
        response = load(r, Response)
        if response.ok:
            u = load(r['user'], User)
            self._usercache[id_] = u
            if u.name not in self._usermapcache:
                self._usermapcache_keys = list()
            self._usermapcache[u.name] = u
            return u
        else:
            raise KeyError(response)
github ltworf / localslackirc / slack.py View on Github external
async def prefetch_users(self) -> None:
        """
        Prefetch all team members for the slack team.
        """
        r = await self.client.api_call("users.list")
        response = load(r, Response)
        if response.ok:
            for user in load(r['members'], List[User]):
                self._usercache[user.id] = user
                self._usermapcache[user.name] = user
            self._usermapcache_keys = list()
github ltworf / typedload / example.py View on Github external
def main():
    raw_data = get_data(sys.argv[1] if len(sys.argv) == 2 else None)
    weather = typedload.load(raw_data, Weather)
    print(weather.item.title)
    print()
    print('Sunrise %s\t Sunset %s' % (weather.astronomy.sunrise, weather.astronomy.sunset))
    print()
    print('%s %s%s' % (weather.item.condition.text, weather.item.condition.temp, weather.units.temperature))
    print()
    print('Wind: %d%s' % (weather.wind.speed, weather.units.speed))
    print('Humidity: %s%%' % (weather.atmosphere.humidity, ))
    print('Pressure: %s%s' % (weather.atmosphere.pressure, weather.units.pressure))
    print('Visibility: %s%s' % (weather.atmosphere.humidity, weather.units.distance))
    print()
    print('Forecast')
    for i in weather.item.forecast:
        print('%s\tMin: %2s%s\tMax: %2s%s\t%s' % (i.day, i.low, weather.units.temperature, i.high, weather.units.temperature, i.text))
github ltworf / localslackirc / slackclient / client.py View on Github external
Connects to the RTM API - https://api.slack.com/rtm
        :Args:
            timeout: in seconds
        """

        # rtm.start returns user and channel info, rtm.connect does not.
        connect_method = "rtm.connect"
        reply = self._api_requester.do(connect_method, timeout=timeout, post_data=kwargs, files=None)

        if reply.status_code != 200:
            raise SlackConnectionError("RTM connection attempt failed")

        login_data = reply.json()
        if login_data["ok"]:
            self._connect_slack_websocket(login_data['url'])
            return load(login_data, LoginInfo)
        else:
            raise SlackLoginError(reply=login_data)
github ltworf / localslackirc / slack.py View on Github external
try:
                if t == 'message' and (not subt or subt == 'me_message'):
                    msg = load(event, Message)

                    # In private chats, pretend that my own messages
                    # sent from another client actually come from
                    # the other user, and prepend them with "I say: "
                    im = await self.get_im(msg.channel)
                    if im and im.user != msg.user:
                        msg = Message(user=im.user, text='I say: ' + msg.text, channel=im.id)
                    if subt == 'me_message':
                        return ActionMessage(*msg)
                    else:
                        return msg
                elif t == 'message' and subt == 'slackbot_response':
                    return load(event, Message)
                elif t == 'user_change':
                    # Changes in the user, drop it from cache
                    u = load(event['user'], User)
                    if u.id in self._usercache:
                        del self._usercache[u.id]
                        #FIXME don't know if it is wise, maybe it gets lost forever del self._usermapcache[u.name]
                    #TODO make an event for this
                else:
                    log(event)
            except Exception as e:
                log('Exception: %s' % e)
            self._triage_sent_by_self()
        return None
github ltworf / localslackirc / slack.py View on Github external
id_ = channel

        cached = self._get_members_cache.get(id_, set())
        cursor = self._get_members_cache_cursor.get(id_)
        if cursor == '':
            # The cursor is fully iterated
            return cached
        kwargs = {}
        if cursor:
            kwargs['cursor'] = cursor
        r = await self.client.api_call('conversations.members', channel=id_, limit=5000, **kwargs)  # type: ignore
        response = load(r, Response)
        if not response.ok:
            raise ResponseException(response)

        newusers = load(r['members'], Set[str])

        # Generate all the Join events, if this is not the 1st iteration
        if id_ in self._get_members_cache:
            for i in newusers.difference(cached):
                self._internalevents.append(Join('member_joined_channel', user=i, channel=id_))

        self._get_members_cache[id_] = cached.union(newusers)
        self._get_members_cache_cursor[id_] = r.get('response_metadata', {}).get('next_cursor')
        return self._get_members_cache[id_]