Create, Update, Delete e Search Function seem work correctly.

In the JS Gui, the workflow stops at the Save Button, but data
area rightly managed.
This commit is contained in:
antifaz 2013-11-24 23:43:56 +01:00
parent ffa0f1784d
commit 83f0c79564
9 changed files with 527 additions and 212 deletions

View file

@ -1,4 +1,61 @@
techrec
=======
==========================================
techrec
==========================================
--------
Client
--------
The Client is a JS script that exchange data with server via JSON
--------
Server
--------
The Server is a python software and uses the bottle library to implements a web
services
Data Format
===================================
--------
Create
--------
JSON = {
'starttime-rec-1385231288390': '2013/11/23 19:32:49',
'endtime-rec-1385231288390': '2013/11/23 19:32:49',
'recid': 'rec-1385231288390',
'name-rec-1385231288390': 'adasd',
'op': 'new'
}
--------
Retrieve
--------
--------
Update
--------
JSON = {
'starttime-rec-1385231288390': '2013/11/23 19:32:49',
'endtime-rec-1385231288390': '2013/11/23 19:32:49',
'recid': 'rec-1385231288390', ### VALID REC ID
'name-rec-1385231288390': 'adasd',
'op': 'update'
}
--------
Delete
--------
JSON = {
'recid': 'rec-1385231288390', ### VALID REC ID
'op': 'delete'
}
BUG
Da Salva button lo stato non va. Per il resto sembra funzionare.
techrec

View file

@ -97,10 +97,13 @@ a{
border-top: 1px dashed #A60000;
}
#newrec .logarea {
/* NEW REC AREA */
.logarea {
min-width:200px;
min-height:100px;
border:1px solid black;
font-size:0.8em;
}
#newrec, #formsearchrec {

View file

@ -18,6 +18,7 @@ $(document).ready(function(){
rec_new();
});
//rec_active();
rec_new();
});

View file

@ -3,186 +3,309 @@ console.log("Loading...");
function trx_startbut( code ) { return "startbutton-"+code; }
function trx_stopbut( code ) { return "stopbutton-"+code; }
function trx_downbut( code ) { return "downloadbutton-"+code; }
function trx_endbut( code ) { return "endbutton-"+code; }
function trx_logarea( code ) { return "logarea-"+code; }
function rs_button( code ) { return "button"+code; }
function rs_trxarea( code ) { return "recarea-"+code; }
function rs_trxname( code ) { return "trxname-"+code; }
function rs_buttonarea( code ) { return "endtime-"+code; }
function rs_inputstart( code ) { return "startime-"+code; }
function rs_inputend( code ) { return "endtime-"; }
function rs_trxname( code ) { return "name-"+code; }
function rs_buttonarea( code ) { return "butarea-"+code; }
function rs_inputstart( code ) { return "starttime-"+code; }
function rs_inputend( code ) { return "endtime-"+code; }
function rs_formid(code) { return "form-"+code; }
function rs_dellink(code) { return "dellink-"+code;}
function rs_id(code) { return code; }
var txt_start = "Inizia";
var txt_stop = "Ferma";
var txt_download = "Scarica";
var srvaddr = "http://127.0.0.1:8000/";
var srvaddr = "http://127.0.0.1:8000";
var almostone = false;
var noplusbotton = true;
var maxrec = 0 ; // Number of Active Record
var rec_name_default = "";
/*
TODO: cambiare logica
Quando premo il primo tasto, faccio la crazione,
per ogni altro pulsante, faccio solo e sempre UPDATE
*/
/**
* Perform Ajax async loading
**/
function newformstr ( recid , butflag=false )
{
var formid = rs_formid( recid );
var str = "<form id=\""+formid+"\" name=\""+formid+"\" action=\"#\">";
if (butflag) {
str = str + "<input type=\"button\" name=\""+trx_startbut(recid)+"\" id=\""+trx_startbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Inizia\" />";
str = str + "<input type=\"button\" name=\""+trx_stopbut(recid)+"\" id=\""+trx_stopbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Stop\" />";
str = str + "<input type=\"submit\" name=\""+trx_downbut(recid)+"\" id=\""+trx_downbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Salva\" />";
str = str + "<input type=\"submit\" name=\""+trx_endbut(recid)+"\" id=\""+trx_endbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Download\" />";
}
str = str + "<input type=\"hidden\" id=\"recid\" name=\"recid\" value=\""+recid+"\" />";
str = str + "<input type=\"text\" id=\""+rs_trxname(recid)+"\" name=\""+rs_trxname(recid)+"\" />";
str = str + "<input type=\"text\" id=\""+rs_inputstart(recid)+"\" name=\""+rs_inputstart(recid)+"\" />";
str = str + "<input type=\"text\" id=\""+rs_inputend(recid)+"\" name=\""+rs_inputend(recid)+"\" />";
if (! butflag) {
str = str + "<input type=\"button\" name=\""+trx_downbut(recid)+"\" id=\""+trx_downbut(recid)+"\" ";
str = str + " class=\"downloadbutton\" value=\"scarica\" />";
}
/*
str = str + "<input type=\"text\" id=\"name\" name=\"name\" />";
str = str + "<input type=\"text\" id=\"starttime\" name=\"starttime\" />";
str = str + "<input type=\"text\" id=\"endtime\" name=\"endtime\" /> ";
*/
str = str + "</form>";
return str;
}
/**
* GetActive Recs
**/
function rec_active( recid ) {
dataString = "";
var request = RecAjax("search", dataString);
request.done( function(data) {
$.each(data, function(key, val) {
console.log("Key " + key + " > VAL " + val );
$("#"+trx_logarea( recid )).append( "Key " + key + " > VAL " + val + "<br>" );
});
console.log("Req OK: "+ data);
// console.log("request"+ req);
ChangeState(recid, trx_downbut(recid) , trx_endbut(recid));
});
}
/**
* New record
**/
function rec_new( ) {
var recid = "rec-"+maxrec;
maxrec += 1;
function rec_new( )
{
var myDate = new Date()
console.log("New ID "+ myDate.getTime());
var recid = "rec-"+ myDate.getTime();
console.log("[rec_new] New Rec " + recid);
$("#buttonscontainer").append( "<div id=\""+rs_trxarea(recid)+"\" class=\"recarea\"> </div>" );
console.log("[rec_new] add div TRXArea "+ rs_trxarea(recid) );
$("#"+rs_trxarea(recid)).append( "<div id=\""+rs_buttonarea(recid)+"\" class=\"buttonarea\"> </div>" );
console.log("[rec_new] add div ButtonArea "+ rs_buttonarea(recid) );
console.log("[rec_new"+recid+"] add div (TRXArea, ButtonArea) ok " );
var formid = rs_formid( recid );
var str = "<form id=\""+formid+"\" name=\""+formid+"\" action=\"#\">";
str = str + "<input type=\"button\" name=\""+trx_startbut(recid)+"\" id=\""+trx_startbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Inizia\" />";
str = str + "<input type=\"button\" name=\""+trx_stopbut(recid)+"\" id=\""+trx_stopbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Stop\" />";
// ADD SUBITO TEXTBUTTON
str = str + "<input type=\"submit\" name=\""+trx_downbut(recid)+"\" id=\""+trx_downbut(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Scarica\" />";
str = str + "<input type=\"text\" id=\""+rs_inputstart(recid)+"\" name=\""+rs_inputstart(recid)+"\"/>";
str = str + "<input type=\"text\" id=\""+rs_inputend(recid)+"\" name=\""+rs_inputend(recid)+"\"/> ";
str = str + "</form>";
var str = newformstr(recid, butflag=true);
$("#"+rs_buttonarea(recid)).append( str );
$("#"+trx_stopbut(recid)).hide();
$("#"+trx_downbut(recid)).hide();
$("#"+trx_endbut(recid)).hide();
console.log("[rec_new] Hide Start Button");
//$("#"+trx_startbut(recid)).css("display","none");
console.log("[rec_new "+recid+"] Form OK");
console.log("[rec_new] add form "+ formid );
$("#"+rs_buttonarea(recid)).append( "\<div class=\"dellink\" \> <a href=\"#\"> cancella</a> \</div\>" );
$("#"+rs_buttonarea(recid)).append( "<div class=\"dellinkarea\" > <a href=\"#\" id="+rs_dellink(recid)+"> cancella</a> </div>" );
// INSERT AND POPULATE BUTTON AREA
$("#"+rs_trxarea(recid)).append( "<div id=\""+trx_logarea(recid)+"\" class=\"logarea\">Nuova trasmissione </div>" );
$("#"+trx_startbut(recid)).click(function(){
ChangeState(recid, trx_startbut(recid) , trx_stopbut(recid));
});
$("#"+rs_trxarea(recid)).append( "<div id=\""+trx_logarea(recid)+"\" class=\"logarea\"> Nuova trasmissione </div>" );
$("#"+trx_stopbut(recid)).click(function(){
ChangeState(recid, trx_stopbut(recid) , trx_downbut(recid));
// Bind the Delete Links
$("#"+rs_dellink(recid)).click(function(){
console.log("Remove " + rs_trxarea(recid) + "[ID"+recid+"]");
$("#"+rs_trxarea(recid)).remove();
alert("Premuto del link. Invio al server ?");
});
// $("#"+trx_downbut(recid)).submit(function(e){
// FORM SUBMIT: THE REC IS STOPPEND AND MUST BE PROCESSED
$("#"+formid).submit(function(event){
event.preventDefault();
dataString = $(this).serialize();
alert("Mando:" + dataString);
RecAjax("/create", dataString);
/*
var request = $.ajax({
type: "POST",
cache: false,
url: "http://127.0.0.1:8000/create",
data: dataString,
dataType: "json"
});
// Immediately, mark the end time (stop action)
ChangeState(recid, trx_stopbut(recid) , trx_downbut(recid));
request.done( function(data) {
$.each(data, function(key, val) {
console.log("Key " + key + " > VAL " + val );
$("#"+trx_logarea( recid )).append( "Key " + key + " > VAL " + val + "<br>" );
});
// Force a Name
while (true) {
if ( $("#"+rs_trxname(recid)).val() == "" )
{
var tmpname = prompt("Nessun nome di trasmissione!!!");
$("#"+rs_trxname(recid)).val(tmpname);
$("#"+trx_logarea(recid)).append("Titolo: <b>"+ tmpname +"</b> <br/>");
}
else { break; }
}
console.log("Req OK: "+ data);
console.log("req"+ request);
} );
event.preventDefault();
// Update data (send to server) in order to save some information
recUpdate(recid);
recStart(recid);
request.fail(function (jqXHR, textStatus, errorThrown){
}); // End of form SUBMIT
console.error("The following error occured: "+
jqXHR.status, +"-"+ textStatus + "-" + errorThrown
);
});
*/
});
// Bind the STOP button
$("#"+trx_stopbut(recid)).click( function(event){
console.log("Form readyReady");
event.preventDefault();
ChangeState(recid, trx_stopbut(recid) , trx_downbut(recid));
recUpdate(recid);
}); // End of STOP button
// Bind the START button
$("#"+trx_startbut(recid)).click( function(event){
// Immediately, mark the start time (start action) and send it to Server
ChangeState(recid, trx_startbut(recid) , trx_stopbut(recid));
event.preventDefault();
recNew( recid );
}); // End of START button
console.log("New form has been built.");
}
function RecAjax(apipath, dataString) {
/* New Record */
function recNew ( recid ) {
var formid = rs_formid( recid );
var dataString = $("#"+formid).serialize();
console.log("New rec: "+dataString);
var request = RecAjax("create", dataString);
request.done( function(data) {
$.each(data, function(key, val) {
console.log("Received (K:V) ("+key+":"+val+")") ;
if (key == "msg") {
$("#"+trx_logarea(recid)).html("Nuova Registrazione </br> (recid:"+recid+") </br>");
$("#"+trx_logarea(recid)).append("Inizio: "+ $("#"+rs_inputstart(recid)).val() +"<br/>");
}
if (key == "error") {
$("#"+trx_logarea( recid )).html("Errore: impossibile creare una nuova registrazione"+val+" </ br>");
}
});
} );
return request;
}
/* Update Record */
function recUpdate( recid ) {
var formid = rs_formid( recid );
var dataString = $("#"+formid).serialize();
console.log("Sending Ajax Update request: "+ dataString);
//event.preventDefault();
var request = RecAjax("update", dataString );
request.done( function(data) {
$.each(data, function(key, val) {
console.log("recUpdate receive (k:v) ("+key+":"+val+")" );
if (key == "message") {
var str = "";
str += "<b>RecID</b> "+ recid + "</br>"
str += "<b>nome</b> "+ $("#"+rs_trxname(recid)).val() + "</br>"
str += "<b>Inizio</b> "+ $("#"+rs_inputstart(recid)).val() + "</br>"
str += "<b>Fine</b> "+ $("#"+rs_inputend(recid)).val() + "</br>"
$("#"+trx_logarea(recid)).html( str );
// if all elements have been recorded
if ($("#"+rs_trxname(recid)).val() != "") {
$("#"+trx_logarea(recid)).append( "<b>In Elaborazione</b>" );
}
}
if (key == "error") {
$("#"+trx_logarea( recid )).append( "Error:" + val +"<br>" );
}
}); // end of each
}); // end of request.done
}
/*
*
* AJAX REQUEST
*
*/
function RecAjax(apipath, dataString ) {
var srv = srvaddr + "/" + apipath ;
var request = $.ajax({
type: "POST",
cache: false,
url: srvaddr + "/" + apipath,
url: srv,
data: dataString,
dataType: "json"
});
request.done( function(data) {
$.each(data, function(key, val) {
console.log("Key " + key + " > VAL " + val );
$("#"+trx_logarea( recid )).append( "Key " + key + " > VAL " + val + "<br>" );
});
console.log("Req OK: "+ data);
console.log("req"+ request);
} );
request.fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: "+
jqXHR.status, +"-"+ textStatus + "-" + errorThrown );
});
console.error("The following error occured: "+ jqXHR.status +"-"+ textStatus + "-" + errorThrown );
if (jqXHR.status == 0 && jqXHR.readyState === 4)
{
alert("Errore di connessione, impossibile inviare i dati al server "+ srv);
} else {
alert("Error: "+jqXHR.status +"\nTextStatus: "+ textStatus + "\n Ready State "+jqXHR.readyState+"\n" + errorThrown );
}
});
return request;
}
function ChangeState(eid, from, to) {
/*
* GetNow (data parser)
*/
function getnow()
{
var myDate = new Date()
var displayDate = myDate.getFullYear() + '/' + (myDate.getMonth()+1) + '/' + myDate.getDate();
displayDate = displayDate +' '+ myDate.getHours()+':'+myDate.getMinutes()+':'+myDate.getSeconds();
return displayDate;
}
/*
FUNCTION: CHANGE STATE (gui)
*/
function ChangeState(recid, from, to) {
console.log("ChangeState: " + from + " --> " + to );
$("#"+from).css("display", "none");
$("#"+to).css("display", "inline");
// take the date
var myDate = new Date()
var displayDate = (myDate.getMonth()+1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear();
displayDate = displayDate +' '+ myDate.getHours()+':'+myDate.getMinutes()+':'+myDate.getSeconds();
var formid = rs_formid( eid );
var logdiv = trx_logarea( eid );
if ( from == trx_startbut(eid) ) {
$("#"+logdiv).append("<br/>Inizio: "+ displayDate);
$("#"+rs_inputstart(eid)).val( displayDate);
console.log("set "+rs_inputstart(eid)+ " to "+ displayDate )
var displayDate = getnow();
if ( from == trx_startbut(recid) ) {
$("#"+rs_inputstart(recid)).val( displayDate );
console.log("ChangeState: set "+rs_inputstart(recid)+ " to "+ displayDate )
}
if ( from == trx_stopbut(eid) ) {
$("#"+logdiv).append("<br/>Fine: "+ displayDate);
$("#"+rs_inputend(eid)).val( displayDate);
console.log("set "+rs_inputend(eid)+ " to "+ displayDate )
if ( from == trx_stopbut(recid) ) {
$("#"+rs_inputend(recid)).val( displayDate );
console.log("ChangeState: set '"+rs_inputend(recid)+ "' to "+ displayDate )
}
if ( from == trx_downbut(recid) ) {
$("input[type=submit]").attr("disabled", "disabled");
console.log("ChangeState: set '"+rs_inputend(recid)+ "' to "+ displayDate );
}
} // End function ChangeState

Binary file not shown.

View file

@ -21,31 +21,50 @@ $(document).ready(function(){
function (event) {
event.preventDefault();
dataString = $(this).serialize();
var request = RecAjax("search", dataString, "dads");
var request = RecAjax("search", dataString);
$("#searchresult").html(" ");
request.done( function(data) {
console.log("Ricevuto data", data);
$.each(data, function(key, val) {
console.log("Extract " + key );
var divstring = "<div class=\"searchresult\" id=\""+ rs_trxarea(key) +"\"> </div>";
var divstring = "<div class=\"searchresult\" id=\""+ rs_trxarea(key) +"\"> </div>";
$("#searchresult").append( divstring );
// var str = newformstr( key ); // new form
var str = "<div class=\"namevalues\">"+val.name+" - <a href=\"\">Scarica</a></div>";
str += "<span class=\"timevalues\">["+val.starttime+" >>> "+val.endtime+"]</span>"
var str = "";
str += "<div class=\"namevalues\">"+val.name+" - <a href=\"\">Scarica</a> <a href=\"\" id=\"delete-"+val.id+"\">Cancella</a></div>";
str += "<div class=\"namevalues\">RECID: "+val.recid+" ID: "+ val.id + " Active " + val.active + "</div>";
str += "<div class=\"timevalues\">["+val.starttime+" >>> "+val.endtime+"]</div>"
$("#"+rs_trxarea(key)).html(str);
$("#"+rs_trxarea(key)).html(str);
$("#delete-"+val.id).click(function(evt) {
evt.preventDefault();
console.log("Delete request for ID "+ val.id);
var dataString = "id="+val.id
var req_del = RecAjax("delete", dataString);
req_del.done (function(data) {
$.each(data, function(del_key, del_val) {
console.log("K:V " + del_key +":"+del_val );
if (del_key == "message") {
$("#"+rs_trxarea(key)).fadeOut( 500, function() { $(this).remove(); });
console.log("delete area "+rs_trxarea(key));
// $("#"+rs_trxname(key)).val( val.name );
// $("#"+rs_inputstart(key)).val( val.starttime );
// $("#"+rs_inputend(key)).val( val.endtime );
if (val.state == "CODA") {}
if (val.state == "RUN") {}
if (val.state == "DONE") {}
}
if (del_key == "error") {
alert("Impossibile cancellare elemento");
}
});
});
}
); // End of delete link handler
});
});
});
@ -66,9 +85,10 @@ $(document).ready(function(){
<div id="buttonscontainer">
<form action="#" method="POST" id="searchform">
<input type="text" id="name" name="name" placeholder="name" />
<input type="text" id="starttime" name="starttime" placeholder="Start: 2014-05-01-44-55-01" />
<input type="text" id="endtime" name="endtime" placeholder="End: 2014-05-01-44-55-01" />
<input type="text" id="recid" name="recid" placeholder="Codice Registrazione" /> <br />
<input type="text" id="name" name="name" placeholder="name" /> <br />
<input type="text" id="starttime" name="starttime" placeholder="Start: 2012/11/24 22:37:361" />(timepicker http://puna.net.nz/timepicker.htm#) <br />
<input type="text" id="endtime" name="endtime" placeholder="End: 2012/11/24 22:37:36" /> <br />
<input type="submit" value="Cerca" />
</form>
</div>

View file

@ -32,60 +32,92 @@ class RecServer:
self._app.route('/help/', callback=self.help)
self._app.route('/create', method="POST", callback=self.create)
self._app.post('/create', callback=self.create)
# self._app.post('/create', callback=self.create)
self._app.route('/update', method="POST", callback=self.update)
# self._app.route('/get', method="GET", callback=self.getrec)
# self._app.route('/get/', method="GET", callback=self.getrec)
# self._app.route('/get/<recid>', method="GET", callback=self.getrec)
self._app.route('/search', method="POST", callback=self.search)
# self._app.route('/search/', method="POST", callback=self.search)
# self._app.route('/search/<recid>', method="POST", callback=self.search)
# self._app.route('/oldsearch/<key>/<value>', method="POST", callback=self.search)
# self._app.route('/search/<args:path>', method="POST", callback=self.search)
self._app.route('/delete/<recid>', method="GET", callback=self.delete)
self._app.route('/delete/<recid>/', method="GET", callback=self.delete)
self._app.route('/delete', method="POST", callback=self.delete)
def extsearch( self, args ):
print "ARG", args
return self.rec_err("EXT")
"""
CREATE HANDLER
"""
# @route('/create', method=['OPTIONS','POST'])
def create(self):
self.enable_cors()
req = dict( request.POST.allitems() )
ret = {}
print "REQ", req
print "Server:: Create request %s " % req
starttime = ""
if req["starttime-"+req["recid"]] != "":
starttime = datetime.datetime.strptime( req["starttime-"+req["recid"]] , "%Y/%m/%d %H:%M:%S")
else:
starttime = ""
endtime = datetime.datetime.now()
if req["endtime-"+req["recid"]] != "":
endtime = datetime.datetime.strptime( req["endtime-"+req["recid"]] , "%Y/%m/%d %H:%M:%S")
else:
endtime = ""
self.db.add( Rec(name=req["name-"+req["recid"]],
starttime=starttime,
endtime=endtime )
)
return { "msg": "Nuova registrazione aggiunta" }
print "Name %s RECID %s Starttime %s EndTime %s" %(req["name-"+req["recid"]],req["recid"], starttime,endtime )
ret = self.db.add( Rec(name=req["name-"+req["recid"]],
recid=req["recid"],
starttime=starttime,
endtime=endtime )
)
return { "msg": "Nuova registrazione aggiunta", }
return self.rec_msg("Nuova registrazione creata! (id:" + ret.id *")")
# @route('/active')
def getactive(self):
print "GetActive"
"""
DELETE HANDLER
"""
# @route('/delete/<recid>') # @route('/delete/<recid>/')
def delete( self, recid = None ):
if not recid:
self.rec_err("No recid!")
self.rec_err("Delete")
self.enable_cors()
req = dict( request.POST.allitems() )
if not req.has_key( "id" ):
return self.rec_err("No valid ID")
def rec_err(self, msg):
return { "error": msg }
print "Server request delete for id %s " % ( req["id"] )
if self.db.delete( req["id"] ):
return self.rec_msg("DELETE OK")
else:
return self.rec_err("DELETE error: %s" % (self.db.get_err()))
"""
UPDATE HANDLER
"""
# @route('/delete/<recid>') # @route('/delete/<recid>/')
def update( self ):
self.enable_cors()
req = dict( request.POST.allitems() )
ret={}
ret["starttime"] = req ["starttime-"+req["recid"]]
ret["endtime"] = req["endtime-"+req["recid"]]
ret["name"] = req["name-"+req["recid"]]
if self.db.update( req["recid"], ret ):
return self.rec_msg("Aggiornamento completato!");
else:
return self.rec_err("Errore Aggiornamento");
"""
JSON' RESPONDER
"""
def rec_msg(self, msg): return self.rec_xerr("message", msg)
def rec_err(self, msg): return self.rec_xerr("error", msg)
def rec_xerr(self,_type,_msg): return { _type : _msg }
"""
@ -95,34 +127,38 @@ class RecServer:
self.enable_cors()
req = dict( request.POST.allitems() )
name = req["name"]
print "Search request: %s" % (req)
name = "%s" % req["name"]
if req["name"] == "": name = None
starttime = req["starttime"]
if req["starttime"] == "": name = None
if req["starttime"] == "": starttime = None
endtime = req["endtime"]
if req["endtime"] == "": endtime = None
values = self.db._search(name=name, starttime=starttime, endtime=endtime)
recid = req["recid"]
if req["recid"]== "": recid = None
active = True
values = self.db._search(recid=recid,name=name, starttime=starttime, endtime=endtime,active=active)
print "Returned Values %s" % values
ret = {}
for rec in values:
recid = "rec-" + str(rec.id)
ret [recid] = {}
ret [recid]["name"] = rec.name
ret [recid]["id"] = rec.id
ret [recid]["recid"] = rec.recid
ret [recid]["starttime"] = rec.starttime.strftime("%Y-%m-%d-%H-%H-%s")
if rec.endtime != None:
ret [recid]["endtime"] = rec.endtime.strftime("%Y-%m-%d-%H-%H-%s")
else:
rec.endtime = ""
ret [recid]["state"] = rec.state
# print "RET ", ret
"""
print "VALUES ", values
print type(self.rec_err("sdiaso")), " - " , type(values)
print "ERR" , self.rec_err("sdiaso")"""
ret [recid]["active"] = rec.active
logging.info("Return: %s" % ret);
return ret

Binary file not shown.

View file

@ -7,7 +7,7 @@ import json
import yaml
try:
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Boolean
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
except:
@ -16,27 +16,32 @@ except:
logging.basicConfig(level=logging.INFO)
STATE_ACTIVE = 0
STATE_RUN = 1
STATE_DOWN = 2
PAGESIZE = 10
"""
This class describe a single Record (Rec() class) and the
records manager (RecDB() class)
"""
Base = declarative_base()
PAGESIZE = 10
"""
Rec entry
"""
class Rec(Base):
__tablename__ = 'rec'
id = Column(Integer, primary_key=True)
name = Column(String)
starttime = Column(DateTime, nullable = True)
endtime = Column(DateTime, nullable = True)
state = Column(String)
id = Column(Integer, primary_key=True)
recid = Column(String)
name = Column(String, nullable = True)
starttime = Column(DateTime, nullable = True)
endtime = Column(DateTime, nullable = True)
active = Column(Boolean, default = True)
def __init__(self, name="", starttime=None, endtime=None, asjson=""):
def __init__(self, recid="", name="", starttime=None, endtime=None, asjson=""):
self.error = 0
self.job = None
@ -44,6 +49,7 @@ class Rec(Base):
self.name = name
self.starttime = starttime
self.endtime = endtime
self.recid = recid
else:
#try:
# dec = json.loads( unicode(asjson) )
@ -54,36 +60,40 @@ class Rec(Base):
print("dec %s %s" % (dec,type(dec)))
print("asjson %s %s" % (asjson,type(asjson)))
self.recid = asjson[0]['recid']
self.name = asjson[0]['name']
self.starttime = asjson[0]['starttime']
selfendtime = asjson[0]['endtime']
self.endtime = asjson[0]['endtime']
self.state = "CODA"
self.state = STATE_ACTIVE
# launch the job for processing files
def start(self):
self.job = RecJob( self )
"""
def getvalues(self,val=None):
return { "id":self.id,
"recid":self.recid,
"name":self.name,
"starttime":self.starttime,
"endtime":self.endtime,
"state": self.state
"active": self.active
}
"""
def err(self):
return self.error
def set_run(self):
self.state = "RUN"
self.active = STATE_RUN
def set_done(self):
self.state = "DONE"
self.active = STATE_DOWN
def __repr__(self):
return "<Rec('%s','%s','%s', '%s', '%s')>" % (self.id, self.name, self.starttime, self.endtime, self.state)
return "<Rec(id:'%s',recid:'%s',name:'%s',Start: '%s',End: '%s',Active: '%s')>" \
% (self.id, self.recid, self.name, self.starttime, self.endtime, self.active)
""" ************
RecDB
@ -105,50 +115,115 @@ class RecDB:
Session = sessionmaker(bind=self.engine)
self.session = Session()
self.err = ""
self.recordtimeformat = "%Y/%m/%d %H:%M:%S"
def add(self, simplerecord):
logging.debug("New Record: %s" % simplerecord)
self.session.add( simplerecord )
print self.session.add( simplerecord )
self.commit()
logging.info("New Record: %s" % simplerecord)
return ( simplerecord )
def delete(self,id):
_r = self.get_by_id(id)
""""
UPDATE RECORD
"""
def update(self, recid, rec):
_rlist = self._search(recid=recid)
if not len(_rlist) == 1:
return False
logging.info("DB:: Update request %s:%s " % (recid, rec))
logging.info("DB:: Update: data before %s" % _rlist[0])
# 2013-11-24 22:22:42
_rlist[0].starttime = datetime.datetime.strptime(rec["starttime"], self.recordtimeformat)
_rlist[0].endtime = datetime.datetime.strptime(rec["endtime"], self.recordtimeformat)
_rlist[0].name = rec["name"]
logging.info("DB:: Update: data AFTER %s" % _rlist[0])
self.commit()
logging.info("DB:: Update complete")
return True
""""
DELETE RECORD
"""
def delete(self,_id):
if _r:
self.session.delete( _r )
self.commit()
return
logging.info("Delete error: ID %s not found!", id)
_rlist = self._search(_id=_id)
if len(_rlist) == 0:
logging.info("DB: Delete: no record found!")
self.err = "No rec found"
return False
if len(_rlist) > 1:
logging.info("DB: Delete: multilpe records found!")
self.err = "multiple ID Found %s" % (_rlist)
return False
self.session.delete( _rlist[0] )
logging.info("DB: Delete: delete complete")
self.commit()
return True
def commit(self):
logging.info("DB: Commit!!")
self.session.commit()
def get_all(self, page=0, page_size=PAGESIZE):
return self._search(page=page, page_size=page_size)
def _search(self, _id=None, name=None, starttime=None, endtime=None, state=None, page=0, page_size=PAGESIZE):
def _search(self, _id=None, name=None, recid=None, starttime=None, endtime=None, active=None, page=0, page_size=PAGESIZE):
logging.info("DB: Search => id:%s recid:%s name:%s starttime:%s endtime=%s active=%s" % (_id,recid,name,starttime,endtime,active))
query = self.session.query(Rec)
if _id: query = query.filter_by(id=_id)
if name: query = query.filter_by(name=name)
if starttime: query = query.filter(Rec.starttime>starttime)
if endtime: query = query.filter(Rec.endtime<endtime)
if state: query = query.filter(state=state)
if not _id == None: query = query.filter_by(id=_id)
if not recid == None: query = query.filter_by(recid=recid)
if not name == None: query = query.filter(Rec.name.like("%"+name+"%"))
try:
if not starttime == None:
_st = datetime.datetime.strptime(starttime, self.recordtimeformat)
query = query.filter(Rec.starttime > _st )
except:
logging.info("DB: search : no valid starttime")
try:
if not endtime == None:
_et = datetime.datetime.strptime(endtime, self.recordtimeformat)
query = query.filter(Rec.endtime < _et )
except ValueError:
logging.info("DB: search : no valid endtime")
if not active == None: query = query.filter(Rec.active==active)
if page_size: query = query.limit(page_size)
if page: query = query.offset(page*page_size)
return query.all()
print query
ret = query.all()
# print "Sending: %s" % ret
return ret
def get_by_id(self,id):
def get_err(self):
print "DB error: %s" % (self.err)
t = self.err
self.err = ""
return t
"""def get_by_id(self,id):
try:
return self._search( _id=id )[0]
except:
return None
"""
# Just for debug
def printall( queryres ):
for record in queryres:
print "R: %s" % record
for record in queryres: print "Record: %s" % record
# Job in thread
@ -161,7 +236,7 @@ class RecJob():
self.starttime = rec.starttime
self.endtime = rec.endtime
def run(self):
def extract(self):
if type(self.starttime) != type(datetime.datetime.now()):
logging.info("Starttime format error")
@ -218,8 +293,8 @@ if __name__ == "__main__":
a = Rec(name="Mimmo1", starttime=_mytime, endtime=_endtime)
j = RecJob( a )
# print (j)
j.run()
# j.extract()
printall( db._search() )
sys.exit("End test job")
# a = Rec(name="Mimmo1", starttime=_mytime, endtime=None)