search APIs are more RESTful

This commit is contained in:
boyska 2013-11-26 14:45:31 +01:00
parent 0348e2cc2e
commit a8406e74be
5 changed files with 145 additions and 173 deletions

View file

@ -1,8 +1,7 @@
# from bottle import hook, response, route, run, static_file, request
import datetime
import logging
from bottle import Bottle, hook, response, request,static_file, redirect
from bottle import Bottle, request, static_file, redirect
from techrec import Rec, RecDB
@ -19,15 +18,10 @@ class RecServer:
def start(self):
self._app.run(host=self._host, port=self._port, debug=True)
@hook('after_request')
def enable_cors(self):
#These lines are needed for avoiding the "Access-Control-Allow-Origin" errors
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
def _route(self):
### This is the API part of the app
# TODO: move to namespace /api/
# TODO: create a "sub-application"
self._app.route('/favicon.ico', callback=self.favicon)
self._app.route('/help', callback=self.help)
self._app.route('/help/', callback=self.help)
@ -36,8 +30,10 @@ class RecServer:
# self._app.post('/create', callback=self.create)
self._app.route('/update', method="POST", callback=self.update)
self._app.route('/search', method="POST", callback=self.search)
self._app.route('/search', method=["GET", "POST"], callback=self.search)
self._app.route('/delete', method="POST", callback=self.delete)
## Static part of the site
self._app.route('/static/<filepath:path>',
callback= lambda filepath: static_file(filepath, root='static/'))
self._app.route('/js/<f>',
@ -61,7 +57,6 @@ class RecServer:
"""
# @route('/create', method=['OPTIONS','POST'])
def create(self):
self.enable_cors()
req = dict( request.POST.allitems() )
ret = {}
print "Server:: Create request %s " % req
@ -94,7 +89,6 @@ class RecServer:
"""
# @route('/delete/<recid>') # @route('/delete/<recid>/')
def delete( self, recid = None ):
self.enable_cors()
req = dict( request.POST.allitems() )
logging.info("Server: request delete %s " % ( req ) )
if not req.has_key( "recid" ):
@ -110,7 +104,6 @@ class RecServer:
"""
# @route('/delete/<recid>') # @route('/delete/<recid>/')
def update( self ):
self.enable_cors()
req = dict( request.POST.allitems() )
ret={}
@ -126,17 +119,17 @@ class RecServer:
"""
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 }
def rec_msg(self, msg): return {"message": msg, "status": True}
def rec_err(self, msg): return {"error": msg, "status": False}
"""
@route('/search') # @route('/search/') # @route('/search/<key>/<value>')
"""
def search( self, args=None):
self.enable_cors()
if request.method == 'GET':
req = dict( request.GET.allitems() )
else:
req = dict( request.POST.allitems() )
print "Search request: %s" % (req)

View file

@ -22,7 +22,7 @@ var txt_start = "Inizia";
var txt_stop = "Ferma";
var txt_download = "Scarica";
var srvaddr = "http://127.0.0.1:8000";
var srvaddr = "/";
var almostone = false;
var noplusbotton = true;
@ -271,7 +271,7 @@ function recUpdate( recid ) {
*/
function RecAjax(apipath, dataString ) {
var srv = srvaddr + "/" + apipath ;
var srv = srvaddr + apipath ;
var request = $.ajax({
type: "POST",

View file

@ -8,7 +8,7 @@ $(document).ready(function(){
function (event) {
event.preventDefault();
dataString = $(this).serialize();
var request = RecAjax("search", dataString);
var request = $.getJSON('/search', dataString);
$("#searchresult").html(" ");
request.done( function(data) {

Binary file not shown.

View file

@ -4,7 +4,6 @@ import logging
import sys
import datetime
import json
import yaml
try:
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Boolean
@ -32,7 +31,6 @@ Base = declarative_base()
Rec entry
"""
class Rec(Base):
__tablename__ = 'rec'
id = Column(Integer, primary_key=True)
recid = Column(String)
@ -72,16 +70,6 @@ class Rec(Base):
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,
"active": self.active
}
"""
def err(self):
return self.error
@ -238,21 +226,12 @@ class RecJob():
def extract(self):
if type(self.starttime) != type(datetime.datetime.now()):
logging.info("Starttime format error")
return
if type(self.endtime) != type(datetime.datetime.now()):
logging.info("Endtime format error")
return
if self.starttime >= self.endtime:
logging.info("Starttime > Endtime (%s > %s)" % (self.starttime,self.endtime) )
return
assert type(self.starttime) == type(datetime.datetime.now())
assert type(self.endtime) == type(datetime.datetime.now())
assert self.starttime < self.endtime
start = self.starttime
end = self.endtime
app = self.starttime
while True:
print
@ -287,13 +266,13 @@ class RecJob():
"""
if __name__ == "__main__":
db = RecDB()
_mytime = datetime.datetime(2014,05,24,15,12,17)
_mytime = datetime.datetime(2014,05,23,15,12,17)
_endtime = datetime.datetime(2014,05,24,17,45,17)
a = Rec(name="Mimmo1", starttime=_mytime, endtime=_endtime)
j = RecJob( a )
# print (j)
# j.extract()
print (j)
j.extract()
printall( db._search() )
sys.exit("End test job")