Skip to content

Commit

Permalink
use FastAPI to create a backend
Browse files Browse the repository at this point in the history
  • Loading branch information
superstar54 committed Dec 9, 2023
1 parent 95b0f7e commit 4bdae47
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
Empty file.
43 changes: 43 additions & 0 deletions aiida_worktree/web/backend/app/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from aiida import load_profile, orm

load_profile()

app = FastAPI()

origins = ["http://localhost:3000", "localhost:3000"]


app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


@app.get("/", tags=["root"])
async def read_root() -> dict:
return {"message": "Welcome to your todo list."}


@app.get("/worktree/{id}")
async def read_item(id: str):
from fastapi import HTTPException
from .utils import worktree_to_json

try:
node = orm.load_node(id)
from aiida.orm.utils.serialize import deserialize_unsafe

wtdata = node.base.extras.get("worktree", None)
if wtdata is None:
print("No worktree data found in the node.")
return
wtdata = deserialize_unsafe(wtdata)
content = worktree_to_json(wtdata)
return {"id": id, "content": content}
except KeyError:
raise HTTPException(status_code=404, detail=f"Worktree {id} not found")
20 changes: 20 additions & 0 deletions aiida_worktree/web/backend/app/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def worktree_to_json(wtdata):
"""Export a worktree to a JSON serializable dictionary."""
wtdata_short = {
"name": wtdata["name"],
"uuid": wtdata["uuid"],
"state": wtdata["state"],
"nodes": {},
"links": wtdata["links"],
}
for name, node in wtdata["nodes"].items():
wtdata_short["nodes"][name] = {
"name": node["name"],
"identifier": node["metadata"]["identifier"],
"node_type": node["metadata"]["node_type"],
"uuid": node["uuid"],
"state": node["state"],
"action": node["action"],
"inputs": node["inputs"],
}
return wtdata_short
5 changes: 5 additions & 0 deletions aiida_worktree/web/backend/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import uvicorn


if __name__ == "__main__":
uvicorn.run("app.api:app", host="0.0.0.0", port=8000, reload=True)

0 comments on commit 4bdae47

Please sign in to comment.