Web2py Tutorial: Build a Simple Database Driven Note Taking App in Less Than 40 Steps
1. Web2py Tutorial
This presentation is a summary of the
documentation to create a simple database
driven application using the web2py python
framework. The documentation can be found
here.
2. Download and Run
Download the framework from here. Go to the
directory where you downloaded the
application, and run python web2py.py.
7. Database Model Implementation
''' We create a table notes, with the columns title, description, author,
subject and a publication date. We also mention that the fields title, description,
author are required, and that the publication date will be automatically assigned the current time.'''
db.define_table('notes',
Field('title', length=200, required=True, requires=IS_NOT_EMPTY()),
Field('description', length=2000, required=True, requires=IS_NOT_EMPTY()),
Field('author', db.auth_user, required=True, requires=IS_NOT_EMPTY()),
Field('subject', length=20,requires=IS_IN_SET(('english', 'philosophy', 'metaphysics'))),
Field('pub_date', 'datetime', default=request.now, writable=False)
)
9. Function Definition to handle CRUD
operations. (index)
def index():
''' Makes a db query to select all the notes,
orders the notes by the publication date and
returns a dictionary to the template, containing
all the notes.'''
response.flash = "Welcome to the index view!"
notes = db(db.notes).select(orderby=db.notes.pub_date)
return dict(notes=notes)
10. Function Definition contd.. (create)
def create():
''' Generates a form corresponding to the model and
renders it, if the form sends some data, the function
validates the data and saves the data in the database.'''
response.flash = "This is the create page"
form=SQLFORM(db.notes)
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill the form'
return dict(form=form)
11. Function Definitions contd.. (edit)
def edit():
''' The function pre-populates the data from the note instance
that has been requested to be edited and renders it,
once client sends in some data, it saves it in the database.'''
note = db.notes(request.args(0)) or redirect(URL('error'))
form=SQLFORM(db.notes, note, deletable = True)
if form.validate():
if form.deleted:
db(db.notes.id==note.id).delete()
redirect(URL('index'))
else:
note.update_record(**dict(form.vars))
response.flash = 'records changed'
else:
response.flash = 'Something went wrong!'
return dict(form=form)
13. 2 basic templates would do the job!
The previous slide shows how to create a
template. We need to create a template to
show all the content (index.html) and a
template to create/edit the content(create.html)
The files can be found here.
14. Its Done!!
Its time to reap the fruits of the hard work
web2py just did for us :)
The source code is available here.
You can share it if you liked it, in case of doubts
send a mail to: contact@fruiapps.com.