bottle works as class

This commit is contained in:
antifaz 2013-09-08 19:13:23 +02:00
parent a7a2b8b955
commit 62aa87346a
9 changed files with 214 additions and 422 deletions

View file

@ -17,7 +17,7 @@ a{
max-width:50%;
margin:auto;
background-color:#F6F7BD;
background-image: url("7915.png") ;
background-image: url("img/7915.png") ;
background-repeat:no-repeat;
background-attachment:fixed;
background-position: 2% 35%;

View file

@ -1 +0,0 @@
vuota

View file

@ -1,337 +0,0 @@
<?
// phpinfo();
// exit;
include_once("utils.php");
?>
<html>
<head>
<!--[if lt IE 9]>
<script src="jquery-1.9.1.min.js"></script>
<![endif]-->
<!-- <meta http-equiv="refresh" content="30;url=https://techrec.ondarossa.info/index.php"> -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message">
Le registrazioni antecendeti a dom 14 apr 2013, 23.00.00 non sono
disponibili.
</div>
<!-- PAGE CONTAINER -->
<div class="pagecontainer">
<div class="newrec">
<form action="index.php" method=POST>
<input type="hidden" name="op" value="new">
<input type="hidden" id="starttime" name="starttime" value="<? echo DEFAULT_START?>" />
<input type="hidden" id="endtime" name="endtime" value="<? echo DEFAULT_END?>" />
<div class="fieldtitle">
<p>titolo della registrazione</p>
<input type="text" id="title" name="title" value="<? echo DEFAULT_TITLE?>" />
</div>
<input type="submit" value="start now!" class="startbutton" />
</form>
</div>
<?php
/* DB SQLITE CONNECTION */
try {
$sq = new SQLite3( DEFAULT_DBNAME , SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE );
// $sq->open( DEFAULT_DBNAME , SQLITE3_OPEN_READWRITE);
} catch (Exception $e) {
myerror("Unable to open DB ". DEFAULT_DBNAME .". (".$e->getMessage().")\n");
exit;
}
# http://www.sqlite.org/datatype3.html
/* INSTALALZIONE DEL NUOVO DB */
$sqlstring = "CREATE TABLE IF NOT EXISTS registrazioni (
id INTEGER PRIMARY KEY,
starttime DATE,
endtime DATE,
stopped boolean DEFAULT 0,
extracted boolean DEFAULT 0,
title varchar(500),
outfile text
)";
if ( ($res = $sq->exec( $sqlstring )) == FALSE ) {
myerror("impossibile installare");
exit;
}
$title = ( isset($_POST['title']) ) ? $_POST['title'] : DEFAULT_TITLE;
$starttime = ( isset($_POST['starttime']) ) ? $_POST['starttime'] : DEFAULT_START;
$endtime = ( isset($_POST['endtime']) ) ? $_POST['endtime'] : DEFAULT_END;
/*
* CREO NUOVA REGISTRAZIONE
*/
if ( isset($_POST['op']) && $_POST['op'] === "new" ) {
//print "NewFile...".FIFO_DIR."/$title<br/>";
# esempio:
# s="2012/02/14 10:20"
# e="2012/02/14 11:15"
# outfile="cross-55.mp3"
if ( $starttime == DEFAULT_START ) {
$starttime = date("Y/m/d H:i" );
}
$sqlstring = "INSERT into registrazioni (title,starttime,endtime)
VALUES ('$title','$starttime','$endtime')";
try {
$sq->exec($sqlstring);
mymessage("Informazioni registrate");
} catch (Exception $e) {
myerror("Errore registrazione informazioni". $e->getMessage() .")\n");
}
}
/*
* FERMO UNA NUOVA REGISTRAZIONE
*/
/*
if ( isset($_GET['op']) && isset($_GET['stop']) && $_GET['stop'] == "stop" ) {
print "QUIIIII" ;
$id = $_GET['id'];
// end time = NOW!
if ( $_GET['endtime'] == DEFAULT_END) {
$endtime = date("Y/m/d H:i");
} else {
$endtime = $_GET['endtime'] ;
}
$sqlstring = "UPDATE registrazioni
set endtime='$endtime', stopped=1
where id='$id'";
if ( $sq->exec($sqlstring) == FALSE ) {
myerror("Impossibile Terminare la registrazione ($sqlstring)");
} else {
mymessage("Registrazione fermata!");
}
}
*/
/*
* CANCELLA UNA REGISTRAZIONE
*/
if ( isset($_GET['op']) && isset($_GET['delete']) && $_GET['delete'] == "cancella" ) {
$id = $_GET['id'];
$sqlstring = "DELETE from registrazioni where id='$id'";
if ( ($result = $sq->exec($sqlstring)) == FALSE) {
myerror("Impossibile cancellare");
} else {
mymessage("Registrazione correttamente cancellata!");
}
}
/*
* MODIFICA / FERMA UNA REGISTRAZIONE
*/
/* print "OP". $_GET['op']."<br/>";
print "UPDATE". $_GET['update']."<br/>";
print "STOP". $_GET['stop']."<br/>";
*/
if (isset($_GET['op']) && ( $_GET['op'] == "update" ))
{
// Anyway, update!
// Get values from form
$id = $_GET['id'];
$title = $_GET['title'];
$starttime = $_GET['starttime'];
$endtime = ( $_GET['endtime'] == DEFAULT_END) ? date("Y/m/d H:i") : $endtime = $_GET['endtime'] ;
$sqlstring = "UPDATE registrazioni
set title = '$title', starttime = '$starttime', endtime = '$endtime', stopped=1
where id='$id'";
if ( ($result = $sq->exec($sqlstring)) == FALSE) {
myerror("Impossibile Modificare i contenut ($sqlstring)");
} else {
mymessage("Aggiornamento eseguito");
}
}
/*
* ESTRAI UNA REGISTRAZIONE
*/
if ( isset($_GET['op']) && isset($_GET['extract']) && $_GET['extract'] == "estrai" ) {
// Anyway, update!
// Get values from form
$id = $_GET['id'];
$title = $_GET['title'];
$starttime = $_GET['starttime'];
$endtime = $_GET['endtime'];
$outfile = AUDIO_DIR."/".date("Y")."-".date("m")."/".date("d")."/".$title."-".date("U").".mp3";
$content = "s=\"$starttime\"\ne=\"$endtime\"\noutfile=\"$outfile\"\n";
$outfile_rel = AUDIO_DIR_R."/".date("Y")."-".date("m")."/".date("d")."/".$title."-".date("U").".mp3";
#s="2013/03/31 18:37"
#e="END"
#outfile="mimmo.mp3"
if ( data2file( FIFO_DIR . "/$title.fifo", $content ) ) {
$sqlstring = "UPDATE registrazioni set outfile = '$outfile_rel ' , extracted = 1 where id='$id'";
if ( ($result = $sq->exec($sqlstring)) == FALSE) {
myerror( "Impossibile segnare come fermata");
}
mymessage( "Registrazione in processamento ma non segnalata come fermata ($sqlstring)");
} else {
myerror("Impossibile SALVARE la richiesta");
}
}
?>
<!--
Visualizzazione dati passati!
TODO: FORM per filtrare le richieste
-->
<div class="resultcontainer">
<?php
$order = "starttime desc";
# qui c'e' il bug perche' passo in input "starttime desc" e questo non viene rilevato
// if ( isset($_GET['sort']) && in_array($_GET['sort'], array("starttime","endtime","title") ) ) {
if ( isset($_GET['sort']) ) {
$order = $_GET['sort'];
}
$sqlstring = "SELECT * FROM registrazioni ORDER BY $order";
myerror($sqlstring);
if ( ($result = $sq->query( $sqlstring )) == FALSE) {
myerror("Impossibile prelevare dati");
}
print "
<table width=\"100%\">
<tr>
<td> <p> <a href=\"index.php?sort=title\">Titolo</a> (<a href=\"index.php?sort=title desc\">desc</a>)</p> </td>
<td> <p> <a href=\"index.php?sort=starttime\">Inizio</a> (<a href=\"index.php?sort=starttime desc\">desc</a>)</p> </td>
<td> <p> <a href=\"index.php?sort=endtime\">Fine</a> (<a href=\"index.php?sort=endtime desc\">desc</a>)</p> </td>
<td> Stop/Aggiorna </td>
<!-- <td> Aggiorna </td> -->
<td> Estrai </td>
<td> Download </td>
<td> Cancella </td>
</tr>";
while ($data = $result->fetchArray() )
{
// se e' stata stoppata (aggiornata almeno una volta) => Pulsate STOP/Aggiorna
$stoplabel = ( $data['stopped'] == 1) ? "aggiorna" : "stop";
$updatedisabled = ( $data['extracted'] == 1) ? "disabled" : "";
$extractiondisabled = ( $data['stopped'] == 1 && $data['extracted'] == 0 ) ? "": "disabled" ;
print "
<tr class=\"rec$updatedisabled\"><form action=\"index.php\" method=\"GET\">
<td><input type=\"text\" id=\"title\" name=\"title\" value=\"". $data['title'] ."\" $updatedisabled /></td>
<td><input type=\"text\" id=\"starttime\" name=\"starttime\" value=\"". $data['starttime'] ."\" $updatedisabled /> </td>
<td><input type=\"text\" id=\"endtime\" name=\"endtime\" value=\"". $data['endtime'] ."\" $updatedisabled /> </td>
<td><input type=\"hidden\" name=\"op\" value=\"update\">
<input type=\"hidden\" name=\"id\" value=\"". $data['id'] ."\">";
print "<input type=\"submit\" name=\"stop\" value=\"$stoplabel\" $updatedisabled > </td>";
// print "<td><input type=\"submit\" name=\"update\" value=\"aggiorna\" $aggiornadisabled> </td>";
print "<td><input type=\"submit\" name=\"extract\" value=\"estrai\" $extractiondisabled> </td>";
if ( $data['extracted'] == 1) {
$f = trim( str_replace( getcwd(), "", $data['outfile']) );
// print "F" . $f;
// print "OUT" . $data['outfile'];
// print "OUT" .realpath( $data['outfile'] );
// print "COMPLETE" . getcwd()."/".$data['outfile'] . " --- " . is_readable( $data['outfile'] ) ;
// if ( ($f = fopen($data['outfile'] ,'r')) !== FALSE ) {
// if ( is_readable( getcwd()."/".$data['outfile'] ) ) {
//if ( is_readable( $data['outfile'] ) ) {
$finfo = pathinfo($f);
$logfile = urlencode( $f ).".log";
$logfile = trim($f).".log";
$logcontent = file_get_contents( $logfile , FILE_USE_INCLUDE_PATH);
// print $logcontent;
print "<td>";
// print "<br>File: $f";
// print "<br>LogFile: $logfile";
// print "<br>logcontent: $logcontent";
if ( file_exists($f) ) {
print "<a href=\"".$f."\" title=\"log: \n$logcontent\"> scarica </a>";
} else {
print "<a href=\"#\" title=\"log: \n$logcontent\">..processando..</a> <br/> $f <br/> $logfile";
}
print "</td>";
} else {
print "<td>(estrai prima di scaricare)</td>";
}
print "<td><input type=\"submit\" name=\"delete\" value=\"cancella\"> </form> </td>";
print "</tr>";
}
print "
</table>";
$sq->close();
?>
</div>
<div style="clear:both;"></div>
</div>
<div id="footer">
techbl*c
</div>
</body>
</html>

View file

@ -2,13 +2,13 @@
<html>
<head>
<title> TechREC </title>
<script src="jquery-1.9.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="reclibrary.js"></script>
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/reclibrary.js"></script>
<script>
/*
@ -21,7 +21,6 @@ $(document).ready(function(){
</script>
</head>
<body>

View file

@ -32,7 +32,7 @@ var rec_name_default = "";
/**
* Perform Ajax async loading
**/
function async_load( destdiv, uri, postdata) {
function DELETEasync_load( destdiv, uri, postdata) {
postdata = postdata || '';
console.log("[ASYNC] " + destdiv + " <- " + uri)
@ -40,7 +40,7 @@ function async_load( destdiv, uri, postdata) {
$(destdiv).html("\<div class=\"imageloader\"\> \<img src=\"img/ajax-loader.gif\" /\> \</div\>");
console.log("Tolta uri" + uri + "NOW -> http://127.0.1.1:8000/sampleJSON");
var request = $.ajax( { url: "http://127.0.0.1:8000/sampleJSON",
var request = $.ajax( { url: "http://127.0.0.1:8000/create",
type:"GET",
//data: postdata,
//dataType: 'json',
@ -144,9 +144,8 @@ function rec_new( ) {
var request = $.ajax({
type: "POST",
cache: false,
// url: "http://127.0.0.1:8000/sampleJSON",
url: "http://127.0.0.1:8000/sampleJSON",
cache: false,
url: "http://127.0.0.1:8000/create",
data: dataString,
dataType: "json"
});
@ -161,12 +160,12 @@ function rec_new( ) {
console.log("req"+ request);
} );
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error("The following error occured: "+
jqXHR.status, +"-"+ textStatus + "-" + errorThrown
);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: "+
jqXHR.status, +"-"+ textStatus + "-" + errorThrown
);
});
});

View file

@ -13,6 +13,8 @@ var txt_start = "Inizia";
var txt_stop = "Ferma";
var txt_download = "Scarica";
var srvaddr = "http://127.0.1.1:8000/";
var almostone = false;
var noplusbotton = true;
var maxrec = 0 ;
@ -23,23 +25,47 @@ var rec_name_default = "";
function async_load( destdiv, uri, postdata) {
postdata = postdata || '';
console.log("[ASYNC] " + destdiv + " <- " + uri + " --- DATA "+postdata );
console.log("[ASYNC] " + destdiv + " <- " + uri)
console.log( postdata );
$(destdiv).html("\<div class=\"imageloader\"\> \<img src=\"ajax-loader.gif\" /\> \</div\>");
var request = $.ajax( { url: uri, type:"POST", data: postdata } );
request.fail(function(jqXHR) {
console.log("Errore async ajax: " + jqXHR.status)
$(destdiv).html("\<div class=\"imageloader\"\> \<img src=\"img/ajax-loader.gif\" /\> \</div\>");
console.log("Tolta uri" + uri + "NOW -> http://127.0.1.1:8000/sampleJSON");
var request = $.ajax( { url: "http://127.0.1.1:8000/sampleJSON",
type:"POST",
data: postdata,
dataType: 'json',
success : function( msg ) {
$(".imageloader").remove();
resmsg = "["+jqXHR.status+"]";
alert("Ma ci sei ?");
$(destdiv).append( resmsg );
},
error: function(xhr) {
var errmsg = "";
console.log("Errore async ajax: " + xhr.status );
switch( xhr.status )
{
case 0: errmsg="[0] Network Problem."; break;
case 404: errmsg="[404] Requested page not found."; break;
case 500: errmsg="[500] Internal Server Error."; break;
default: errmsg="[ErrCode: "+xhr.status+"] Error uncatched!"; break;
}
console.log("ErrMSG" + errmsg);
$(".imageloader").remove();
//$(destdiv).html("Err: "+ errmsg);
alert("Err: "+ errmsg);
}
}
).always(function( jqXHR ) {
$(".imageloader").remove();
$(destdiv).html("error code: " + jqXHR.status );
});
request.done(function( msg ) {
$(".imageloader").remove();
$(destdiv).append(msg);
});
resmsg = "ALSWAST["+jqXHR.status+"]";
$(destdiv).append( resmsg );
}
).complete(
function (jqXHR, msgstatus) {
alert("Comlpete " +jqXHR + " - " + msgstatus);
}
);
}
@ -49,6 +75,7 @@ function rs_trxname( code ) { return code+"_name"; }
function rs_buttonarea( code ) { return code+"_buttonarea"; }
function rs_inputstart( code ) { return code+"_startime"; }
function rs_inputend( code ) { return code+"_endtime"; }
function rs_formid(code) { return "form-"+code; }
function rs_id(code) { return code; }
function rs_log(code) { return code + "_log"; }
@ -67,9 +94,15 @@ function rec_new( ) {
$("#"+rs_trxarea(recid)).append( "<div id=\""+rs_buttonarea(recid)+"\" class=\"buttonarea\"> </div>" );
// POPULATE BUTTON AREA
var str = "\<input type=\"button\" id=\""+rs_button(recid)+ "\" name=\""+rs_button(recid)+"\" ";
// var str = "\<input type=\"image\" src=\"img/button.jpg\"id=\""+rs_button(recid)+ "\" name=\""+rs_button(recid)+"\" ";
var formid = rs_formid( recid );
var str = "<form id=\""+formid+"\">";
str = str + "\<input type=\"submit\" name=\""+rs_button(recid)+"\" id=\""+rs_button(recid)+"\" ";
str = str + " class=\"recbutton\" value=\"Inizia\" /\>";
str = str + "</form>";
$("#"+formid).attr("action","#") .attr("method","post") //set the form attributes
$("#"+rs_buttonarea(recid)).html( str );
// DELETE BUTTON (NO FIRST ELEMENT)
if ( recid > 0 ){
@ -80,11 +113,24 @@ function rec_new( ) {
$("#"+rs_trxarea(recid)).append( "<div id=\""+rs_log(recid)+"\" class=\"logarea\">Nuova trasmissione </div>" );
// BINDING CLICK TO FUNCTION
$("#"+rs_button(recid) ).click(function(){
// $("#"+rs_button(recid) ).click(function(){
$("#"+rs_button(recid) ).submit(function(){
rec_changestate( rs_button(recid) );
});
}
function download( eid ){
alert("DEntro download");
var trxnameobj = document.getElementById( rs_trxname(eid) );
var trxname = trxnameobj.value;
var starttime = $("#"+rs_inputstart(eid)).val();
var endtime = $("#"+rs_inputstart(eid)).val();
var jsondata = {"name":'"'+trxname+'"', "starttime":'"'+ starttime +'"', "endtime":'"'+ endtime +'"'};
async_load( destdiv, srvaddr, jsondata);
alert("FINE download");
}
function rec_changestate( eid ) {
console.log("[CS] change state for "+eid+"");
@ -104,6 +150,8 @@ function rec_changestate( eid ) {
***/
console.log("RECBUTTON value :"+recbutton.value);
//console.log("TXT " + txt_star.toUpperCase() );
if ( recbutton.value.toUpperCase() == txt_start.toUpperCase() ) {
/*
@ -117,9 +165,11 @@ function rec_changestate( eid ) {
var str = "\<input type=\"text\" id=\""+rs_trxname(eid)+"\" placeholder=\"Nome trasmissione\" /\>";
str = str + "\<input type=\"hidden\" id=\""+rs_inputstart(eid)+"\" value=\""+displayDate+"\" /\>";
$("#"+rs_buttonarea(eid)).append( str );
//$("#"+rs_buttonarea(eid)).append( str );
var formid = rs_formid( eid );
$("#"+formid).append(str)
console.log("[CS] rs_log(eid) " + rs_log(eid) );
console.log("[CS] Update log div (" + rs_log(eid) +")");
$("#"+rs_log(eid)).append("<br /\>Inizio: "+displayDate);
console.log("[CS] change text for "+eid);
@ -147,8 +197,40 @@ function rec_changestate( eid ) {
$("#"+rs_log(eid)).append("<br /\>Fine: "+displayDate);
recbutton.type = "submit";
recbutton.value = txt_download;
$("#"+eid).click(function(e){
e.preventDefault();
dataString = $("#JqAjaxForm").serialize();
$.ajax({
type: "POST",
url: "http://127.0.1.1:8000/sampleJSON",
data: {"value":"value"},
dataType: "json",
success: function(data) {
alert("QUI"+ data);
},
error: function (x) {
alert("error" + x.status);
}
});
});
$("#"+ rs_trxarea(eid)).css("background-color","green");
console.log("EID" + eid);
$("#"+ rs_trxarea(eid)).append( "<a href=\"#\" id=\"but-down-"+eid+"\" onclick=\"Javascript:download("+eid+");\") >SCARICA LINK</a>" );
/*$("#but-down-"+eid).click(function(){
var trxname = trxnameobj.value;
var starttime = $("#"+rs_inputstart(eid)).val();
var endtime = $("#"+rs_inputstart(eid)).val();
var jsondata = {"name":'"'+trxname+'"', "starttime":'"'+ starttime +'"', "endtime":'"'+ endtime +'"'};
async_load( destdiv, srvaddr, jsondata);
});*/
} else if ( recbutton.value.toUpperCase() == txt_download.toUpperCase() ) {
@ -160,7 +242,9 @@ function rec_changestate( eid ) {
console.log("[CS] GetID"+ eid+ "_name");
var trxname = trxnameobj.value;
var starttime = $("#"+rs_inputstart(eid)).val();
var endtime = $("#"+rs_inputstart(eid)).val();
console.log("[CS] ID = "+eid+"_name ==> "+trxname ) ;
console.log("[CS] "+trxname+" != "+rec_name_default);
@ -182,11 +266,16 @@ function rec_changestate( eid ) {
}
console.log("recarea"+eid);
console.log($("#recarea"+eid).innerHTML);
$("#recarea"+eid).css("background-color","#ccc");
console.log( "Recarea "+rs_trxarea(eid) +" -> " + $("#"+rs_trxarea(eid)).innerHTML );
$("#"+rs_trxarea(eid)).css("background-color","#ccc");
// TODO: fare i controlli su starttime, endtime
async_load( "#"+rs_log(eid), "techrecapi.php?op=new", {location:"roma", name:"ciccio"});
var jsondata = {"name":'"'+trxname+'"', "starttime":'"'+ starttime +'"', "endtime":'"'+ endtime +'"'};
destdiv = "#"+rs_log(eid)
console.log( destdiv +" <- " + srvaddr + "\n" + jsondata );
async_load( destdiv, srvaddr, jsondata);
}
@ -201,13 +290,11 @@ function rec_changestate( eid ) {
}
/* GESTIONE CAMBIO DI STATO */
$(document).ready(function(){
rec_new();
});
</script>
@ -220,7 +307,7 @@ $(document).ready(function(){
L'INTERFACCIA COERENTE CON LA BASE DI DATI
-->
<div id="pagecontainer">
<form action="" method="POST">
<!-- <form action="#" method="POST"> -->
<h1> techr*c </h1>
@ -230,7 +317,7 @@ $(document).ready(function(){
<div id="addnewrecarea"> </div>
</form>
<!-- </form>-->
</div>

View file

@ -3,23 +3,42 @@ import sys,os
import logging
logging.basicConfig(level=logging.INFO)
"""
RESPONSE HTML
http://stackoverflow.com/questions/6391280/simplehttprequesthandler-override-do-get
"""
import ast
# include data object
from techrec import *
import SimpleHTTPServer
""" CONNECTION HANDLER """
class ConnHandler(SocketServer.BaseRequestHandler):
def __init__(self, db, *args, **keys):
self.db = db
# class ConnHandler(SocketServer.BaseRequestHandler):
class ConnHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def __init__(self, *args, **keys):
self.db = RecDB()
# logging.info("Connected from: %s" % self.client_address[0] )
SocketServer.BaseRequestHandler.__init__(self, *args, **keys)
# SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **keys)
def strip_http_headers(self,http_reply):
p = http_reply.find('\r\n\r\n')
if p >= 0:
return http_reply[p+4:]
return http_reply
def handle(self):
self.data = self.request.recv(1024).strip()
logging.debug("DATA: %s - %s" % (self.client_address[0], self.data) )
tmp = Rec(asjson=self.data)
body = [ ast.literal_eval( self.strip_http_headers( self.data ) ) ]
print("DATA:", self.data)
logging.debug("Received from %s:\n%s\n%s" % (self.client_address[0], self.data, body) )
try:
tmp = Rec(asjson=body)
except:
self.request.send( "ERORE" )
return
if tmp.err():
respmsg = "Data ERROR"
else:
@ -29,45 +48,64 @@ class ConnHandler(SocketServer.BaseRequestHandler):
self.db.add( tmp )
self.db.printall()
self.request.sendall( respmsg )
def handler_factory(db):
_responsemsg = "{}"
responsemsg = formatresponse( _responsemsg )
# print "SEND RESPONSE:", responsemsg
# self.request.sendall( responsemsg )
# self.request.send( responsemsg )
_resmsg = json.dumps({'return':'ok'})
print "SEnd BACK:" , _resmsg
#TODO: check response
#if True:
#else:
self.request.sendall( _resmsg )
return
def formatresponse( data ):
return "HTTP/1.0 200 OK\r\nContent-Type:application/json\r\nConnection:close\r\n\r\n{0}\r\n".format( data )
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
"""def handler_factory(db):
def createHandler(*args, **keys):
return ConnHandler(db, *args, **keys)
return createHandler
"""
""" MAIN SERVER """
class recserver:
def __init__(self, host="localhost", port=9999):
self.host = host
self.port = port
self.db = RecDB()
def start(self):
try:
# self.server = SocketServer.TCPServer((self.host, self.port), ConnHandler)
self.server = SocketServer.TCPServer((self.host, self.port), handler_factory( self.db ) )
except:
sys.exit("Bind error.")
self.server = SocketServer.TCPServer((self.host, self.port), ConnHandler)
self.server = MyTCPServer((self.host, self.port), ConnHandler)
# self.server = SocketServer.TCPServer((self.host, self.port), handler_factory( self.db ) )
logging.info("Server ready to serve forever.")
self.server.serve_forever()
try:
self.server.serve_forever()
except KeyboardInterrupt:
logging.debug("Closing Socket")
self.server.socket.close()
def loadall():
"""
# Testing DB
def testdb():
db = RecDB()
a = Rec(name="Mimmo1",starttime="ora",endtime="fine")
db.add( a )
db.printall()
db.search( Rec(name="Mimmo1") )
"""
# Loading Server TODO: make thread
def loadall():
# TODO: make thread
r = recserver()
r.start()
# Loading Server
if __name__ == "__main__":
loadall()
loadall()

Binary file not shown.

View file

@ -45,14 +45,21 @@ class Rec(Base):
self.starttime = starttime
self.endtime = endtime
else:
try:
#try:
# dec = json.loads( unicode(asjson) )
dec = yaml.load( asjson )
except:
self.error = 0
self.name = dec[0]['name']
self.starttime = dec[0]['starttime']
self.endtime = dec[0]['endtime']
# dec = yaml.load( asjson )
dec = json.dumps( asjson )
# except:
# self.error = 0
print("dec %s %s" % (dec,type(dec)))
print("asjson %s %s" % (asjson,type(asjson)))
# self.name = dec[0]['name']
# self.starttime = dec[0]['starttime']
# self.endtime = dec[0]['endtime']
self.name = asjson[0]['name']
self.starttime = asjson[0]['starttime']
self.endtime = asjson[0]['endtime']
# self.id = None
self.state = QUEUE
print "DECC" , dec
@ -94,18 +101,18 @@ class RecDB:
# print all records
def printall(self):
logging.info("DB")
print("DB")
allrecords = self.session.query(Rec).all()
for record in allrecords:
logging.info("R: %s " % record)
print("R: %s" % record)
def execsql(self,sql):
records = self.conn.execute( sql )
def search(self, name="", starttime="", endtime=""):
logging.info("Looking for %s" % recfilter)
logging.debug("Looking for %s" % recfilter)
# self.session.query( Rec ).filter( Rec.name=name ).first()