From 14806b42fb2d57dadb7ab4ee69808587976c2edf Mon Sep 17 00:00:00 2001 From: Peder Bergebakken Sundt Date: Fri, 16 Feb 2018 23:19:50 +0100 Subject: [PATCH] Add basic sanic setup to use for REST api --- grzegorz/__init__.py | 40 ++++++++++++++++++++++++++++++---------- grzegorz/api.py | 30 ++++++++++++++++++++++++++++++ main.py | 4 ++-- requirements.txt | 1 + 4 files changed, 63 insertions(+), 12 deletions(-) create mode 100644 grzegorz/api.py diff --git a/grzegorz/__init__.py b/grzegorz/__init__.py index fbed340..34d40aa 100644 --- a/grzegorz/__init__.py +++ b/grzegorz/__init__.py @@ -1,21 +1,41 @@ import asyncio +from sanic import Sanic from . import mpv from . import nyasync +from . import api -mpv_control = mpv.MPVControl() +#global variable: +mpv_control = None#mpv.MPVControl() async def test(): await mpv_control.loadfile('grzegorz/res/logo.jpg') -async def entry(): - await asyncio.gather( - mpv_control.run(), - test(), - ) - -def main(): - nyasync.run(entry()) +def main(host="0.0.0.0", port=8080, tasks:list = None): + app = Sanic(__name__) + app.blueprint(api.bp, url_prefix="/api") + + #used to ensure sanic/uvloop creates its asyncio loop before MPVControl tries to use one itself + async def runMPVControl(): + global mpv_control + + mpv_control = mpv.MPVControl() + app.config["mpv_control"] = mpv_control + try: + await mpv_control.run() + except Exception as e: + print(e) + + print("mpv is no longer running. Stopping Sanic...") + app.stop() + if not tasks: tasks = [] + tasks.insert(0, runMPVControl()) + + for task in tasks: + app.add_task(task)#instead of ensure_future + + app.run(host=host, port=port) + if __name__ == '__main__': - main() + main(tasks=[test()]) diff --git a/grzegorz/api.py b/grzegorz/api.py new file mode 100644 index 0000000..8d1a041 --- /dev/null +++ b/grzegorz/api.py @@ -0,0 +1,30 @@ +from sanic import Blueprint, response +import asyncio +from . import mpv + +bp = Blueprint("grzegorz-api") +#this blueprint assumes a mpv.MPVControl instance is available at request.app.config["mpv_control"] + +#route decorators: +def response_json(func): + async def newfunc(*args, **kwargs): + body = await func(*args, **kwargs) + return response.json(body) + return newfunc +def response_text(func): + async def newfunc(*args, **kwargs): + body = await func(*args, **kwargs) + return response.text(body) + return newfunc + +#routes: +@bp.get("/") +@response_text +async def root(request): + return "Hello World!" + +@bp.get("/playlist") +@response_json +async def get_playlist(request): + request.app.config["mpv_control"].send_request() + pass diff --git a/main.py b/main.py index 557c32f..59cca91 100755 --- a/main.py +++ b/main.py @@ -1,3 +1,3 @@ #!/usr/bin/env python3 -from grzegorz import main -main() +from grzegorz import main, test +main(tasks=[test()]) diff --git a/requirements.txt b/requirements.txt index 88d6d6f..5c1e7eb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ mpv==0.1 youtube-dl +sanic==0.7.0