Skip to content

Commit 4e4a576

Browse files
committed
commit suggestions; add Post type for get_posts() response
1 parent ec518b5 commit 4e4a576

File tree

5 files changed

+38
-39
lines changed

5 files changed

+38
-39
lines changed

src/aleph/sdk/base.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
DEFAULT_PAGE_SIZE = 200
3333

3434

35-
class AlephClientBase(ABC):
35+
class BaseAlephClient(ABC):
3636
@abstractmethod
3737
async def fetch_aggregate(
3838
self,
@@ -127,10 +127,9 @@ async def get_posts_iterator(
127127
:param start_date: Earliest date to fetch messages from
128128
:param end_date: Latest date to fetch messages from
129129
"""
130-
total_items = None
131-
per_page = DEFAULT_PAGE_SIZE
132130
page = 1
133-
while total_items is None or page * per_page < total_items:
131+
resp = None
132+
while resp is None or len(resp.posts) > 0:
134133
resp = await self.get_posts(
135134
page=page,
136135
types=types,
@@ -143,7 +142,6 @@ async def get_posts_iterator(
143142
start_date=start_date,
144143
end_date=end_date,
145144
)
146-
total_items = resp.pagination_total
147145
page += 1
148146
for post in resp.posts:
149147
yield post
@@ -232,10 +230,9 @@ async def get_messages_iterator(
232230
:param start_date: Earliest date to fetch messages from
233231
:param end_date: Latest date to fetch messages from
234232
"""
235-
total_items = None
236-
per_page = DEFAULT_PAGE_SIZE
237233
page = 1
238-
while total_items is None or page * per_page < total_items:
234+
resp = None
235+
while resp is None or len(resp.messages) > 0:
239236
resp = await self.get_messages(
240237
page=page,
241238
message_type=message_type,
@@ -250,7 +247,6 @@ async def get_messages_iterator(
250247
start_date=start_date,
251248
end_date=end_date,
252249
)
253-
total_items = resp.pagination_total
254250
page += 1
255251
for message in resp.messages:
256252
yield message
@@ -304,7 +300,7 @@ def watch_messages(
304300
pass
305301

306302

307-
class AuthenticatedAlephClientBase(AlephClientBase):
303+
class BaseAuthenticatedAlephClient(BaseAlephClient):
308304
@abstractmethod
309305
async def create_post(
310306
self,

src/aleph/sdk/client.py

+6-17
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
from aleph.sdk.types import Account, GenericMessage, StorageEnum
5151
from aleph.sdk.utils import Writable, copy_async_readable_to_buffer
5252

53-
from .base import AlephClientBase, AuthenticatedAlephClientBase
53+
from .base import BaseAlephClient, BaseAuthenticatedAlephClient
5454
from .conf import settings
5555
from .exceptions import (
5656
BroadcastError,
@@ -59,7 +59,7 @@
5959
MessageNotFoundError,
6060
MultipleMessagesError,
6161
)
62-
from .models import MessagesResponse, PostsResponse
62+
from .models import MessagesResponse, PostsResponse, Post
6363
from .utils import check_unix_socket_valid, get_message_type_value
6464

6565
logger = logging.getLogger(__name__)
@@ -469,7 +469,7 @@ def submit(
469469
)
470470

471471

472-
class AlephClient(AlephClientBase):
472+
class AlephClient(BaseAlephClient):
473473
api_server: str
474474
http_session: aiohttp.ClientSession
475475

@@ -618,26 +618,15 @@ async def get_posts(
618618
response_json = await resp.json()
619619
posts_raw = response_json["posts"]
620620

621-
# All posts may not be valid according to the latest specification in
622-
# aleph-message. This allows the user to specify how errors should be handled.
623-
posts: List[AlephMessage] = []
621+
posts: List[Post] = []
624622
for post_raw in posts_raw:
625623
try:
626-
message = parse_message(post_raw)
627-
posts.append(message)
628-
except KeyError as e:
629-
if not ignore_invalid_messages:
630-
raise e
631-
logger.log(
632-
level=invalid_messages_log_level,
633-
msg=f"KeyError: Field '{e.args[0]}' not found",
634-
)
624+
posts.append(Post.parse_obj(post_raw))
635625
except ValidationError as e:
636626
if not ignore_invalid_messages:
637627
raise e
638628
if invalid_messages_log_level:
639629
logger.log(level=invalid_messages_log_level, msg=e)
640-
641630
return PostsResponse(
642631
posts=posts,
643632
pagination_page=response_json["pagination_page"],
@@ -903,7 +892,7 @@ async def watch_messages(
903892
break
904893

905894

906-
class AuthenticatedAlephClient(AlephClient, AuthenticatedAlephClientBase):
895+
class AuthenticatedAlephClient(AlephClient, BaseAuthenticatedAlephClient):
907896
account: Account
908897

909898
BROADCAST_MESSAGE_FIELDS = {

src/aleph/sdk/models.py

+21-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
from typing import List
1+
from typing import List, Optional, Any, Dict, Union
22

3-
from aleph_message.models import AlephMessage, PostMessage
4-
from pydantic import BaseModel
3+
from aleph_message.models import AlephMessage, BaseMessage, ItemHash, ChainRef
4+
from pydantic import BaseModel, Field
55

66

77
class PaginationResponse(BaseModel):
@@ -18,8 +18,25 @@ class MessagesResponse(PaginationResponse):
1818
pagination_item = "messages"
1919

2020

21+
class Post(BaseMessage):
22+
"""
23+
A post is a type of message that can be updated. Over the get_posts API
24+
we get the latest version of a post.
25+
"""
26+
hash: ItemHash = Field(description="Hash of the content (sha256 by default)")
27+
original_item_hash: ItemHash = Field(description="Hash of the original content (sha256 by default)")
28+
original_signature: Optional[str] = Field(
29+
description="Cryptographic signature of the original message by the sender"
30+
)
31+
original_type: str = Field(description="The original, user-generated 'content-type' of the POST message")
32+
content: Dict[str, Any] = Field(description="The content.content of the POST message")
33+
type: str = Field(description="The content.type of the POST message")
34+
address: str = Field(description="The address of the sender of the POST message")
35+
ref: Optional[Union[str, ChainRef]] = Field(description="Other message referenced by this one")
36+
37+
2138
class PostsResponse(PaginationResponse):
2239
"""Response from an Aleph node API on the path /api/v0/posts.json"""
2340

24-
posts: List[PostMessage]
41+
posts: List[Post]
2542
pagination_item = "posts"

tests/unit/test_asynchronous_get.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
from aleph.sdk.client import AlephClient
99
from aleph.sdk.conf import settings
10+
from aleph.sdk.models import PostsResponse
1011

1112

1213
def make_mock_session(get_return_value: Dict[str, Any]) -> AlephClient:
@@ -66,14 +67,10 @@ async def test_fetch_aggregates():
6667
@pytest.mark.asyncio
6768
async def test_get_posts():
6869
async with AlephClient(api_server=settings.API_HOST) as session:
69-
response: MessagesResponse = await session.get_messages(
70-
message_type=MessageType.post,
71-
)
70+
response: PostsResponse = await session.get_posts()
7271

73-
messages = response.messages
74-
assert len(messages) > 1
75-
for message in messages:
76-
assert message.type == MessageType.post
72+
posts = response.posts
73+
assert len(posts) > 1
7774

7875

7976
@pytest.mark.asyncio

tests/unit/test_synchronous_get.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from aleph.sdk.conf import settings
55

66

7-
def test_get_posts():
7+
def test_get_post_messages():
88
with AlephClient(api_server=settings.API_HOST) as session:
99
response: MessagesResponse = session.get_messages(
1010
pagination=2,

0 commit comments

Comments
 (0)