Python과 Js(svelte) 연동하기 예제
1. 예제용 데이터를 data/user.toml을 생성한다.
[[users]]
name = "doe"
email = "doe@gmail.com"
[[users]]
name = "foo"
email = "foo@gmail.com"
[[users]]
name = "bar"
email = "bar@gmail.com"
2. app.py 에 다음 코드가 추가 된다.
import toml
@eel.expose
def getUsers():
with open("data/users.toml") as f:
return toml.load(f)["users"]
3. 다시 앱을 실행한 후 F12를 눌러 개발자도구 콘솔에서 다음과 같이 입력하여
eel.getUsers()(users=>{console.log(users)})
python 함수를 호출하여 데이터를 확인할 수 있다.
[{name: "doe"}, {name: "foo"}, {name: "bar"}]
4. src/App.svelte를 수정하여 users를 원하는 대로 보여주기
<script>
let users = [];
// 유저를 가져오는 함수
const getUsers = ()=>{
// python eel의 함수를 호출하기
eel.getUsers()(_users=>{
users = _users
})
}
getUsers()
</script>
<h1>Users</h1>
<!-- svelte의 each 문법 -->
{#each users as user}
<strong>{user.name}</strong>
<p>{user.email}</p>
{/each}
.svelte파일들은 수정하고 npm run build 명령어를 통하여 public/build/ 디렉토리에 있는 bundle.js, bundle.css에 빌드하여야
반영된 소스를 확인 할 수 있다.
5. PROFIT!!!
ㅇㅅㅇ