Add basic sanic setup to use for REST api
This commit is contained in:
parent
4f7aebd6fb
commit
14806b42fb
@ -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()])
|
||||
|
30
grzegorz/api.py
Normal file
30
grzegorz/api.py
Normal file
@ -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
|
4
main.py
4
main.py
@ -1,3 +1,3 @@
|
||||
#!/usr/bin/env python3
|
||||
from grzegorz import main
|
||||
main()
|
||||
from grzegorz import main, test
|
||||
main(tasks=[test()])
|
||||
|
@ -1,2 +1,3 @@
|
||||
mpv==0.1
|
||||
youtube-dl
|
||||
sanic==0.7.0
|
||||
|
Loading…
Reference in New Issue
Block a user