adapting APIs to fastapi

current status is still non-functional, though
This commit is contained in:
boyska 2021-08-24 22:09:52 +02:00
parent d929839025
commit 6ef8704715
2 changed files with 82 additions and 52 deletions

View file

@ -1,13 +1,15 @@
#!/usr/bin/env python3
import logging
import time
import os
import unicodedata
from datetime import datetime
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import FileResponse, RedirectResponse
from fastapi.responses import FileResponse, RedirectResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from .cli import common_pre
from .config_manager import get_config
@ -67,69 +69,80 @@ def help():
+ "/custom?strftime=FORMAT : get now().strftime(FORMAT)"
)
class CreateInfo(BaseModel):
starttime: str = None
endtime: str = None
name: str = ""
@app.post("/api/create")
def create():
req = dict(request.POST.decode().allitems())
async def create(req: CreateInfo = None):
ret = {}
logger.debug("Create request %s " % req)
if req is None:
req = CreateInfo()
now = datetime.now()
start = date_read(req["starttime"]) if "starttime" in req else now
name = req["name"] if "name" in req else ""
end = date_read(req["endtime"]) if "endtime" in req else now
start = date_read(req.starttime) if req.starttime is not None else now
name = req.name
end = date_read(req.endtime) if req.endtime is not None else now
rec = Rec(name=name, starttime=start, endtime=end)
ret = db.add(rec)
return self.rec_msg(
return rec_msg(
"Nuova registrazione creata! (id:%d)" % ret.id, rec=rec_sanitize(rec)
)
class DeleteInfo(BaseModel):
id: int
@app.post("/api/delete")
def delete():
req = dict(request.POST.decode().allitems())
logging.info("Server: request delete %s " % (req))
if "id" not in req:
return self.rec_err("No valid ID")
if db.delete(req["id"]):
return self.rec_msg("DELETE OK")
def delete(req: DeleteInfo):
if db.delete(req.id):
return rec_msg("DELETE OK")
else:
return self.rec_err("DELETE error: %s" % (db.get_err()))
return rec_err("DELETE error: %s" % (db.get_err()))
def timefield_factory():
return int(time.time())
TimeField = Field(default_factory=timefield_factory)
class UpdateInfo(BaseModel):
name: str = ""
starttime: int =Field(default_factory=timefield_factory)
endtime: int =Field(default_factory=timefield_factory)
filename: str = None
@app.post("/api/update/{recid}")
def update(recid: int):
req = dict(request.POST.decode().allitems())
async def update(recid: int, req: UpdateInfo):
newrec = {}
now = datetime.now()
if "starttime" not in req:
newrec["starttime"] = now
else:
newrec["starttime"] = date_read(req["starttime"])
if "endtime" not in req:
newrec["endtime"] = now
else:
newrec["endtime"] = date_read(req["endtime"])
if "name" in req:
newrec["name"] = req["name"]
newrec["starttime"] = date_read(req.starttime)
newrec["endtime"] = date_read(req.endtime)
if req.name:
newrec["name"] = req.name
try:
logger.info("prima di update")
result_rec = db.update(recid, newrec)
logger.info("dopo update")
except Exception as exc:
return self.rec_err("Errore Aggiornamento", exception=exc)
return self.rec_msg("Aggiornamento completato!", rec=rec_sanitize(result_rec))
return rec_err("Errore Aggiornamento", exception=exc)
return rec_msg("Aggiornamento completato!", rec=rec_sanitize(result_rec))
class GenerateInfo(BaseModel):
id: int
class GenerateResponse(BaseModel):
status: str
message: str
@app.post("/api/generate")
def generate():
async def generate(req: GenerateInfo, response: Response):
# prendiamo la rec in causa
recid = dict(request.POST.decode().allitems())["id"]
recid = req.id
rec = db._search(_id=recid)[0]
if rec.filename is not None and os.path.exists(rec.filename):
return {
@ -142,12 +155,12 @@ def generate():
and (rec.endtime - rec.starttime).total_seconds()
> get_config()["FORGE_MAX_DURATION"]
):
response.status = 400
return {
"status": "error",
"message": "The requested recording is too long"
return JSONResponse(
status_code = 400,
status= "error",
message= "The requested recording is too long"
+ " (%d seconds)" % (rec.endtime - rec.starttime).total_seconds(),
}
)
rec.filename = get_config()["AUDIO_OUTPUT_FORMAT"] % {
"time": rec.starttime.strftime(
"%y%m%d_%H%M"
@ -165,7 +178,7 @@ def generate():
),
}
db.get_session(rec).commit()
job_id = self._app.pq.submit(
job_id = pq.submit(
create_mp3,
start=rec.starttime,
end=rec.endtime,
@ -177,7 +190,7 @@ def generate():
},
)
logger.debug("SUBMITTED: %d" % job_id)
return self.rec_msg(
return rec_msg(
"Aggiornamento completato!",
job_id=job_id,
result="/output/" + rec.filename,
@ -188,7 +201,7 @@ def generate():
@app.get("/api/jobs/{job_id}")
def check_job(job_id: int):
try:
job = pq.check_job(job_id)
job = check_job(job_id)
except ValueError:
abort(400, "job_id not valid")
@ -287,7 +300,7 @@ def rec_msg(msg, status=True, **kwargs):
def rec_err(msg, **kwargs):
return self.rec_msg(msg, status=False, **kwargs)
return rec_msg(msg, status=False, **kwargs)
app.mount("/output", StaticFiles(directory=get_config()["AUDIO_OUTPUT"]))

View file

@ -19,31 +19,48 @@ var RecAPI = {
create: function () {
return $.ajax('/api/create', {
method: 'POST',
contentType: 'application/json',
data: "{}",
dataType: 'json'
})
},
stop: function (rec) {
return $.post('/api/update/' + rec.id, {
starttime: rec.starttime
return $.ajax('/api/update/' + rec.id,
{
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
starttime: parseInt(rec.starttime, 10)
})
})
},
update: function (id, data) {
return $.post('/api/update/' + id, data)
return $.ajax(
'/api/update/' + data.id, {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data)
})
},
fullcreate: function (name, start, end) {
return $.ajax(
'/api/create', {
method: 'POST',
dataType: 'json',
data: { name: name,
contentType: 'application/json',
data: JSON.stringify({ name: name,
starttime: config.date_write(start),
endtime: config.date_write(end)
}
})
})
},
generate: function (rec) {
return $.post('/api/generate', {
id: rec.id
return $.ajax('/api/generate', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ id: rec.id })
})
},
get_archive: function () {