CSC/ECE 517 Fall 2014/ch1a 7 kz

From Expertiza_Wiki
Jump to navigation Jump to search

Background

“Web2py is an open source web application framework written in the Python programming language.”<ref>[1], Web2py. Retrieved 18 September 2014.</ref> Web2py originally started as an educational tool when, in October 2007, Massimo Di Pierro developed web2py as a way to introduce his students to web programming. From this, it quickly grew through user adoption to become a strong competitor to Django, another python based web framework. Web2py has design principles similar to that of other popular web application frameworks. Simply put, web2py embraces the principles of don't repeat yourself <ref name="dryWiki">[2],"Wikipedia entry for Don't Repeat Yourself". Retrieved 25 September 2014.</ref>, there should only be one way of doing things (form processing, managing sessions, and handling cookies), and explicit is better than implicit. <ref name="web2PyOnlineBook">[3],"Web2py's Free Online Book". Retrieved 18 September 2014.</ref> Web2py Online Book is an excellent start for those who wish to learn more.

Web2py is considered a full-stack framework, which simply means that the individual components of the framework were designed and built to work together. <ref name="webAppFrameworkwiki">[4], "Web Application Framework Wiki". Retrieved 25 September 2014.</ref> "Almost all of its components are built from scratch and are designed to work together, but they function just as well outside of the complete web2py framework. For example, the Database Abstraction Layer (DAL) or the template language can be used independently of the web2py framework by importing gluon.dal or gluon.template into your own Python applications. gluon is the name of the web2py module that contains system libraries. Some web2py libraries, such as building and processing forms from database tables, have dependencies on other portions of web2py. web2py can also work with third-party Python libraries, including other template languages and DALs, but they will not be as tightly integrated as the original components." <ref name="web2PyOnlineBook"/>


Some popular websites powered by web2py are<ref name="web2PyPoweredWebsites">[5], Sites Powered by Web2py. Retrieved 25 September 2014.</ref>:

Fig 1: Typical workflow in web2py
<ref name="web2PyOnlineBook" />

Key Features

Security

Web2py addresses many issues related to security vulnerabilities.

  1. Validates all input to prevent database injections
  2. Escapes all output to prevent cross-site scripting
  3. Renames uploaded files to prevent directory traversal attacks

By following established web security practices, web2py helps prevent some of the most popular security attack, “so developers have less chances of introducing vulnerabilities”. <ref name="web2PyOnlineBook" />

Database Abstraction Layer

Web2py includes, by default, a Database Abstraction Layer (DAL) that is capable of dynamically writing SQL (Structured Query Language) for the most popular database management systems (DBMS) including, among others:

  1. SQLite
  2. MySqL
  3. Oracle

Web 2.0

According to web2py’s own documentation, it is the only web framework to fully embrace the Web 2.0 paradigm. Web 2.0 describes changes to the way that web pages are created and used rather than an update to any technical specification.<ref>[6], "Web 2.0". Retrieved 18 September 2014.</ref> Web2py accomplishes this by not requiring any installation or configuration and running on any architecture that can run python.

Examples

After downloading web2py, starting the server, and navigating to http://localhost:8000 you will be greeted by web2py's default home page. An excellent feature of web2py, the admin interface (pictured below) can quickly be accessed by clicking, "administrative interface" from the default home page.

Model Example

Through the use of a DAL, web2py provides for simple ways to create database tables for web applications.

db.define_table(
    'person',
    Field('name'),
    Field('email'),
    format = '%(name)s')

# ONE (person) TO MANY (products)

db.define_table(
    'product',
    Field('seller_id',db.person),
    Field('name'),
    Field('description', 'text'),
    Field('picture', 'upload', default=''),
    format = '%(name)s')

# MANY (persons) TO MANY (purchases)

db.define_table(
    'purchase',
    Field('buyer_id', db.person),
    Field('product_id', db.product),
    Field('quantity', 'integer'),
    format = '%(quantity)s %(product_id)s -> %(buyer_id)s')

purchased = (db.person.id==db.purchase.buyer_id)&(db.product.id==db.purchase.product_id)

db.person.name.requires = IS_NOT_EMPTY()
db.person.email.requires = [IS_EMAIL(), IS_NOT_IN_DB(db, 'person.email')]
db.product.name.requires = IS_NOT_EMPTY()
db.purchase.quantity.requires = IS_INT_IN_RANGE(0, 10)

From web2py's online reference <ref name="web2pyExamples">[7], "Web2py Quick Examples", Retrieved 19 September 2014.</ref>

Tables are created if they do not exist (try... except). Here "purchased" is an Query object, "db(purchased)" would be a Set objects. A Set object can be selected, updated, deleted. Sets can also be intersected. Allowed field types are string, integer, password, text, blob, upload, date, time, datetime, references(*), and id(*). The id field is there by default and must not be declared. references are for one to many and many to many as in the example above. For strings you should specify a length or you get length=32.

You can use db.tablename.fieldname.requires= to set restrictions on the field values. These restrictions are automatically converted into widgets when generating forms from the table with SQLFORM(db.tablename).

define_tables creates the table and attempts a migration if table has changed or if database name has changed since last time. If you know you already have the table in the database and you do not want to attempt a migration add one last argument to define_table migrate=False.

Wiki Creation Example

The following example code embeds a fully working wiki.

def index(): return auth.wiki()

Authorization Example

The following example prevents a visitor from accessing a function unless the member has read permissions.

@auth.requires_permission('read','person')
   def f(): ....

Architecture

Model View Controller

Like most popular web frameworks, web2py uses a Model View Controller (MVC) architecture. <ref name="aboutWeb2Py">[8], "What is web2py?". Retrieved 18 September 2014.</ref> In an MVC architecture the user’s request goes through the controller, which requests information from the model (usually some type of database) and then passes it along to the view for renderer. This type of architecture separates the data, logic and the user interfaces into separate components, making them more modular and maintainable.

Model

In web2py, the model is the db.py file. This is where you define the type of database engine you are using and any table and fields. For example, if you wanted to define a sqlite database with a table with car make and models, you would have the following code:

db = DAL('sqlite://production.sqlite')
db.define_table('cars',
   Field('make'),
   Field('model'))

Controller

Controllers are functions that will be run when a user tries to access a certain URL. A controller can have different actions it can call. For example, if you want to define a cars controller that has an all action, your cars.py would look like this:

def all():
    grid=SQLFORM.grid(db.cars, user_signature=False)
    return locals()

View

The final portion of the user request pipeline is the view. When the all() function in cars.py finishes running it calls a view to render the data. In our case, since our controller is car and our action is all, the view file would be cars/all.html and this is how it could look like:

<h1>Car Make and Models</h1>
{{=grid}}


Portability

The framework itself is very portable. It can run on any operating system that supports Python which means it will work on most cloud services like Amazon EC2 and Google App Engine. It also supports numerous databases including SQLite, MySQL, MSSQL, MariaDB, Oracle etc.. <ref name="aboutWeb2Py" />. Not only that, it can speak multiple protocols like REST, XML/HTML, and JSON among others. <ref name="aboutWeb2Py" /> This is a great example of web2py’s MVC architecture coming into play. The database (model) or the protocol (view) can be switched around with very little work.

Components

Fig 2: Overview of the architecture of web2py
<ref name="web2PyArchSlide">[9], "web2py, ideas we stole - ideas we had". Retrieved 18 September 2014.</ref>

According to the slide seen on the right, web2Py is split into a few major components. <ref name="web2PyArchSlide" />The lowest component in the python interpreter. Right above that there is a web server to serve web pages. By default, web2py comes with rocket, but it can be switched for third party web server like Apache or nginx. Running on top of that are the web2py core libraries. This contains the code that handles HTTP requests, responses, cookies, the database APIs (ORM), templating engine and other helpers. Finally, on top of that is where all the applications the developer writes will go. By default, web2py comes with a few example and admin applications, but they can be removed and new ones can be added either through the admin GUI or through the actual codebase itself.

Comparison

Web2py most often gets associated with Django, another Python web framework, and Rails, a web framework based on Ruby. Web2py is heavily inspired by both of those frameworks. <ref name="aboutWeb2Py"/> Like Rails and Django, web2py also follows a MVC architecture, has a templating engine and an ORM (Object Relational Mapper). Web2py has a few unique features that it’s competitors don’t have. One of the most appealing features of web2py is that web2py “applications” can be created and imported into the server via a admin web interface. <ref name="aboutWeb2Py" /> Unlike Rails and Django, you do not have to open up a text editor and create models by hand, you can do it using a graphical interface. You can also package and download applications from the server so you can import it elsewhere. Web2py is also one of the few frameworks to properly adopt the Web 2.0 paradigm. It is also very lightweight compared to most other web frameworks that have similar feature lists.

Django

Django and web2py have a lot of things in common. Firstly, they are both Python web MVC frameworks, which means the basic flow of control is the same. A user request gets routed to the controller, which will consult the model(s) and generate some kind of output. Django is the more popular framework out of the two. A few popular sites built using Django are Mozilla, Pinterest and Instagram. <ref name="djangoWeb2PyCompare">[10], "Comparing Django, TurboGears2 and Web2py". Retrieved 18 September 2014.</ref> However, Web2py supports a more variety of database engines than Django does and is a lot more lightweight to install and run. <ref name="djangoWeb2PyCompare" />

Rails

Rails and web2py both follow the MVC architectural pattern. However, Rails applications are written in Ruby and web2py applications are written in Python. One of the main advantages of web2py vs Rails is the installation process. To install Rails, you have to install Ruby, gems and other database and database plugins; installation of web2py is as easy and installing Python and unzipping a zip file. <ref name="railsVsWeb2Py">[11], "Rails vs Web2py". Retrieved 18 September 2014.</ref> Other things such as user/role support, uploading files are supported by web2py but plugins are needed for them for Rails. <ref name="railsVsWeb2Py" />

In summary, web2py has a lot of things common with other framework like Rails and Django. The syntax for the ORM and the templating might be different between the different frameworks, but they all use the MVC framework and have the same underlying concept. Where web2py really beats the other frameworks is it’s size; it’s very lightweight, but still contains all the features the other ORMs have!

Hyperlinks to important terms

References

<references/>