Last active
March 17, 2021 04:25
-
-
Save dmachi/8112a5c891b33ab94ef50b6599aba0a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sanic import Sanic | |
from sanic.response import json,text | |
import asyncio | |
app = Sanic("service") | |
# import concurrent | |
# thread_pool = concurrent.futures.ThreadPoolExecutor() | |
async def do_step(step,duration,opts={}): | |
# run your task here instead of sleeping | |
# if it is not an async method, you will | |
# uncomment the import concurrent and threadpool above | |
# and then run your method with with something like: | |
#loop = asyncio.get_running_loop() | |
#return await loop.run_in_executor(thread_pool,YOUR_METHOD,PARAM1,PARAM2) | |
#example load | |
await asyncio.sleep(5) | |
# whatever you return here will get sent back to the client | |
return {"success": True} | |
@app.route("/") | |
async def root(request): | |
return text("OK") | |
#A simple get could like this passing in the step and duration | |
#on the url could suffice | |
#curl http://localhost:8000/step/1/5 | |
@app.route("/step/<step>/<duration>", methods=["GET"]) | |
async def get_step(request,step,duration): | |
results = await do_step(step,duration,opts={}) | |
return json(results) | |
#if you want to pass a whole dictionary of stuff, | |
#you could post a JSON object to /step using this method | |
#curl -X POST --data-binary '{"step": 1, "duration": 5, "someoption": "blah"}' http://localhost:8000/step | |
@app.route("/step", methods=["POST"]) | |
async def post_step(request): | |
input = request.json | |
results = await do_step(input['step'],input['duration'],opts=input) | |
return json(results) | |
#Shutdown the server. You'd call this when the simulation is done so that the task will | |
#complete and the slurm job will end. | |
@app.route("/shutdown", methods=["GET"]) | |
async def shutdown(request): | |
async def stop(): | |
await asyncio.sleep(1) | |
app.stop() | |
app.add_task(stop) | |
return text("Shutting Down") | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment