How can I call my own host API? #1137
-
I can call APIs of different domains, how can I call my own API? @component
def ViewUserData(data=None):
data = httpx.get('http://127.0.0.1:8000/api/getUser', timeout=5).json()
return html.table(html.tr(...), html.tr(...)) However, it blocks and then throws a timeout error Code:from reactpy import component, html, run, hooks
import time
import httpx
@component
def Index():
return html.div(
# {'on_mouse_move': lambda e: print(e['x'], e['y'])},
html.h1(
{'style': {'color': 'Blue'}},
"This is a title",
),
html.img(
{
"src": "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
}
),
html.p("This is a paragraph"),
html.a({"text": "This is a link", "href": "https://www.google.com"}),
html.div(),
PrintButton("Play", "Playing"),
html.div(),
PrintButton("Pause", "Paused"),
html.div(),
Label(),
ClickButton(),
)
@component
def PrintButton(display_text, message_text):
def handle_event(event):
print(message_text)
return html.button({"on_click": handle_event}, display_text)
@component
def ClickButton():
mytext, set_mytext = hooks.use_state("Hello World")
return html.div(
{
'name': 'use_state',
},
html.button(
{
"on_click": lambda e: set_mytext(f'Hello World {time.time()}'),
},
'ClickButton',
),
html.div(),
html.button(
{
"on_click": handle_http_request,
},
'ClickButton For Http Request',
),
html.div(mytext),
Label(mytext),
ViewUserData(),
)
def handle_http_request(e):
print('handle_http_request')
# data = httpx.get('http://127.0.0.1:8000/api/getUser', timeout=5).json()
data = httpx.get('https://api.github.com/events', timeout=5).json()
print(data)
@component
def Label(text=''):
return html.div(text)
@component
def ViewUserData(data=None):
# print('data:', 'UserData')
return data
if __name__ == '__main__':
run(Index) API:import time
from dataclasses import dataclass
from typing import Callable, Generic, TypeVar
from fastapi import FastAPI, Request
from reactpy.backend.fastapi import configure
from index import Index
app = FastAPI()
app.debug = True
T = TypeVar("T")
@dataclass
class UserData:
id: int
name: str
age: int
avatar: str
@dataclass
class RespList(Generic[T]):
code: int
data: list[T]
@app.middleware("http")
async def add_process_time_header(request: Request, call_next: Callable):
time_start = time.time()
response = await call_next(request)
process_time = time.time() - time_start
response.headers["X-Process-Time"] = str(process_time)
return response
@app.get("/api/getUser")
def index() -> RespList[UserData]:
return RespList[UserData](
code=200,
data=[
UserData(
id=i,
name=f"test_{i}",
age=i,
avatar=f"https://avatars.dicebear.com/v2/avataaars/{i}.svg",
)
for i in range(10)
],
)
configure(app, Index)
# pip install pydantic --upgrade
# uvicorn main:app --reload |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Currently my implementation add below code? # ViewUserData(),
# html.script(
# """
# fetch('http://127.0.0.1:8000/api/getUser')
# .then().then(res => res.json())
# .then(res => console.log(res))
# """
# ),
html.embed(
{'src': '/user/view', 'border': '0', 'width': '100%', 'height': '300px'}
), @app.get('/user/view')
def userView():
html = """\
<head>
<script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.min.js'></script>
<style>
.container { display: flex; flex-wrap: wrap; }
.avatar { width: 100px; height: 100px; border-radius: 50%; }
</style>
</head>
<div id='vue-app'>
<div class='container'>
<div v-for='item in user' :key='item.id'>
<img :src='item.avatar' class='avatar' />
<div>
<span>{{ item.name }}</span>
<span> </span>
<span>{{ item.age }}</span>
</div>
</div>
</div>
</div>
<script>
Vue.createApp({
data() {
return {
user: {}
}
},
mounted() {
fetch('/api/getUser')
.then(r => r.json()).then(res => {
this.user = res.data
}
)
},
watch: {
user: function() {
console.log(this.user)
}
},
}).mount('#vue-app')
</script>
"""
return Response(html, media_type='text/html') |
Beta Was this translation helpful? Give feedback.
-
All code in ReactPy runs server-side so you don't actually need to call an API endpoint. Instead, you would do so inside a |
Beta Was this translation helpful? Give feedback.
-
Well, I tried both ways and it worked, thanks very much! @component
def ViewUserData(data=None):
data, set_data = hooks.use_state({})
@hooks.use_effect
async def _():
if data:
return
url = 'https://jsonplaceholder.typicode.com/users'
# async with aiohttp.ClientSession() as client:
# async with client.get(url) as resp:
# res = await resp.json()
# set_data(res)
async with httpx.AsyncClient() as client:
res = await client.get(url)
set_data(res.json())
return html.div(html.code(f'{data}')) |
Beta Was this translation helpful? Give feedback.
To add on to this answer...
As long as you are trying to fetch data hosted on your local server, you don't need to perform a HTTP API request. Accessing local data in your situation might look something like this: