I'm working on an open source OFFLINE pyramid application running on a raspberry pi so I want to keep everything as simple and efficient as possible. The application is happily communicating with my postgresql db using sqlalchemy. I don't want to complicate things by using Deform or other widgets or add authentication or use session cookies (as in the Pyramid Doc examples). My template (chameleon) using the twitter bootstrap contains a form (snippets):
<form action="." method="post">
<a class="btn" href="#" id="actionbtn" onclick="camCapture()">Capture</a>
<p><input type="text" class="input-small' id="projfld" value="Project Name">
<p><label class="control-label" for "select01">Brightness</label>
<div class="btn-group' data-toggle="buttons-radio" id="bright">
<button type="button" class="btn btn-small" id="btnoff">Off</button>
<button type="button" class="btn btn-small" id="btn10">10%</button>
<button type="button" class="btn btn-small" id="btn50">50%</button>
<button type="button" class="btn btn-small" id="btnfu">Full</button>
</div>
<p><label class="checkbox"><input type="checkbox" id="auto">Auto</label>
</form>
There are other buttons and fields in the form, but this is the diversity. When user clicks the actionbtn the javascript in the template:
function camCapture()
{
jQuery.ajax({
url: '/camcapture',
dataType:"json",
type: 'POST',
data: "test",
});
}
is triggering the function in views.py (trimmed code below) and adding system data to a postgresql database using sqlalchemy.
@view_config(renderer="json", name="camcapture")
def camcapture_view(self):
#
# stuff happens
#
now = datetime.datetime.utcnow()
outfile = ("/home/brian/cam/%s" % now.strftime("CAM_%Y%m%d%H%M%S") + ".jpg")
cam_event = Event('fileprefix',now,'CAM',outfile,'memo field content','project')
DBSession.add(cam_event) # data, Event arguments above, are written to database
#
# other stuff happens
#
return []
The user needs only return to the original page (no redirect) as they are likely to alter data in one or more fields and submit the form again.
I reckon this is a common application but I cannot find an example or tutorial to help new developers like me. Perhaps it is too simple and I am missing important fundamental information? My db schema is, I believe appropriately defined in models.py:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
engine = create_engine('postgresql://scan:scan@localhost:5432/scan', echo=True) # Establishes SQLAlchemy link to postgresql db
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
class ORMClass(object): # Allows grabs of database values as variables in python
@classmethod
def query(class_):
return DBSession.query(class_)
@classmethod
def get(class_, record):
return Session.query(class_).get(record)
Base = declarative_base(cls=ORMClass)
class Event(Base): #Schema description which allows automated table generation if it doesn't already exist
__tablename__ = 'event'
record = Column(Integer, Sequence('event_record_seq'), primary_key=True, nullable=False)
fileprefix = Column(String)
date = Column(DateTime, nullable=False)
eventtype = Column(String(3))
filename = Column(String)
memo = Column(String)
project = Column(String)
extend_existing = True
def __init__(self, fileprefix, date, eventtype, filename, memo, project): #constructor for new event records
self.fileprefix = fileprefix
self.date = date
self.eventtype = eventtype
self.filename = filename
self.memo = memo
self.project = project
def __repr__(self):
return "<Event('%s','%s','%s','%s','%s','%s')>" % (self.fileprefix, self.date, self.eventtype, self.filename, self.memo, self.project)
Base.metadata.create_all(engine)
Thank you. Yes, @Sergey, I'm having problems accessing the values in the JSON dict. I have gone through that tutorial prior to posting my query. In my attempts to emulate it, I am used stringify to construct the JSON body. I'm taking form information and setting the values into a variable.
jsondata= JSON.stringify({"var1name" : $(#projfld").val(), "var2name" and so on.
On my post--> data: jsondata.
In the tutorial they print the tuples. I'm trying to set each pair as variables for use in the code and can't find the syntax to do that. I want to do something like
var1 = request.json_body(index(0)), var2 = request.json_body(index(1)), and so on.
In the simplified version above I'm sending the string "test" as JSON data. I can then set a string in my Python code to that string, but how do I parse the parts of the JSON body? variablez = request.json_body is the tutorial example equivalent. Since the tuples contain name and value pairs I thought variables might already be declared in the body and I could use them in my code and send some of the values off to my database.
The reason I'm not using a simple submit button is that there are several buttons on the form (mentioned) each of which will take different pieces of information from the form and activate different pieces of code on the server side for immediate hardware action (sending serial commands in this case). Were you trying to suggest that pressing enter in a field will automatically submit the form? Not true, at least not on the system I'm using (which I have control over in this offline application).