niming_igapi/interface/example.py

76 lines
No EOL
1.6 KiB
Python

import datetime
import requests
import io
"""
Interface
The bridge between web application(niming) and igapi.
An interface should have a get() function.
"""
def get(index:int, media:bool=True) -> dict | None:
"""
Every interface should have this function.
Backend calls this function to get data of a post.
Args:
index (int): ID of the post
media (bool): Send media or not
Returns:
dict: Data of a post. Formatted as shown in Note 1 (an_example_of_context)
None: An error occurred, and nothing was returned.
"""
# get data
## fake server in localhost
### where is the api of web application?
res = requests.get("http://localhost:5000/article/%d?media_count=1"%index)
if res.status_code != 200:
return None
rj = res.json()
media = []
# get media
if media:
for m in rj["media"]:
_m = requests.get(m)
if _m.status_code == 200:
media.append(io.BytesIO(_m.content))
# return
result = {
"id": rj["id"],
"metadata": {
"create_time": rj["create_time"],
"author": "",
"tags": [],
"category": ""
},
"content": {
"text": rj["content"],
"media": media
}
}
return result
# Note 1
an_example_of_context = {
"id": int,
"metadata": {
"create_time": int | datetime.datetime,
"author": str,
"tags": list[str],
"category": str
},
"content": {
"text": str,
"media": [
io.BytesIO
]
}
}