modified index.js

This commit is contained in:
yoshi 2025-04-30 15:09:22 -07:00
parent 52d62894b6
commit 1edc0d39c2
5 changed files with 113 additions and 119 deletions

View file

@ -1,44 +1,62 @@
# snakeapi_service/snakeapi_server.py
import os
import logging
import typing
import importlib.util
from flask import Flask, request
from flask import Flask, request, jsonify
from flask_cors import CORS
# load notebook code as module
spec = importlib.util.spec_from_file_location(
"nb_module", os.path.join("notebooks", "notebook.py")
)
nb = importlib.util.module_from_spec(spec)
spec.loader.exec_module(nb)
# load handlers from converted notebook
notebook_path = os.environ.get("NOTEBOOK_PATH")
if not notebook_path or not os.path.isfile(notebook_path):
raise RuntimeError(f"Notebook module not found: {notebook_path}")
spec = importlib.util.spec_from_file_location("notebook_module", notebook_path)
notebook_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(notebook_module)
handlers = {
"info": nb.info,
"start": nb.start,
"move": nb.move,
"end": nb.end
"info": notebook_module.info,
"start": notebook_module.start,
"move": notebook_module.move,
"end": notebook_module.end,
}
app = Flask(__name__)
CORS(app)
def run_server(handlers: typing.Dict):
app = Flask(__name__)
CORS(app)
@app.route("/", methods=["GET"])
def on_info():
return handlers["info"]()
@app.get("/")
def on_info():
return handlers["info"]()
@app.route("/start", methods=["POST"])
def on_start():
handlers["start"](request.get_json())
return "ok"
@app.post("/start")
def on_start():
game_state = request.get_json()
handlers["start"](game_state)
return "ok"
@app.route("/move", methods=["POST"])
def on_move():
return handlers["move"](request.get_json())
@app.post("/move")
def on_move():
game_state = request.get_json()
return handlers["move"](game_state)
@app.route("/end", methods=["POST"])
def on_end():
handlers["end"](request.get_json())
return "ok"
@app.post("/end")
def on_end():
end_game = request.get_json()
handlers["end"](end_game)
return "ok"
@app.get("/notebook")
def get_notebook():
with open(notebook_path.replace('.py', '.ipynb'), "r", encoding="utf-8") as f:
return f.read(), 200, {"Content-Type": "application/json"}
@app.get("/notebook/path")
def get_notebook_path():
return jsonify({"path": notebook_path})
host = "::"
port = int(os.environ.get("PORT", "3006"))
logging.getLogger("werkzeug").setLevel(logging.ERROR)
app.run(host=host, port=port)
if __name__ == "__main__":
port = int(os.environ.get("PORT", "3006"))
app.run(host="0.0.0.0", port=port)
run_server(handlers)