Skip to content

Commit

Permalink
Merge pull request webpy#261 from asldevi/docs
Browse files Browse the repository at this point in the history
Improved docs for user input and db
  • Loading branch information
anandology committed Nov 6, 2013
2 parents 945c0c3 + bdeec7d commit 618466a
Show file tree
Hide file tree
Showing 3 changed files with 255 additions and 24 deletions.
160 changes: 160 additions & 0 deletions docs/db.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
Accessing the database
======================

Web.py provides a simple and uniform interface to the database that you want to work with, whether it is PostgreSQL, MySQL, SQLite or any other. It doesn't try to build layers between you and your database. Rather, it tries to make it easy to perform common tasks, and get out of your way when you need to do more advanced things.


Create database object
------------------------

You could create a database object with `web.database()`. Make sure that you have appropriate database library installed.

PostgreSQL
``````````
Database Library: `psycopg2`
::

db = web.database(dbn='postgres', db='dbname', user='username', pw='password')

MySQL
`````
Database Library: `MySQLdb`
::

db = web.database(dbn='mysql', db='dbname', user='username', pw='password')


SQLite
``````

Database Library: `sqlite3`
::

db = web.database(dbn='sqlite', db='dbname')


Multiple databases
``````````````````

Working with more databases is not at all difficult with web.py. Here's what you do.

::

db1 = web.database(dbn='postgres', db='dbname1', user='username1', pw='password2')
db2 = web.database(dbn='postgres', db='dbname2', user='username2', pw='password2')

And use `db1`, `db2` to access those databases respectively.


Operations
----------
`web.database()` returns an object which provide you all the functionality to insert, select, update and delete data from your database. For each of the methods on `db` below, you can pass `_test=True` to see the SQL statement rather than executing it.


Inserting
`````````
::

# Insert an entry into table 'user'
userid = db.insert('user', firstname="Bob", lastname="Smith", joindate=web.SQLLiteral("NOW()"))


The first argument is the table name and the rest of them are set of named arguments which represent the fields in the table. If values are not given, the database may create default values or issue a warning.

For bulk insertion rather than inserting record by record, use `Multiple Inserts` rather.

Selecting
`````````

The `select` method is used for selecting rows from the database. It returns a `web.iterbetter` object, which can be looped through.

To select `all` the rows from the `user` table, you would simply do

::

users = db.select('user')

For the real world use cases, `select` method takes `vars`, `what`, `where`, `order`, `group`, `limit`, `offset`, and `_test` optional parameters.

::

users = db.select('users', where="id>100")

To prevent SQL injection attacks, you can use `$key` in where clause and pass the `vars` which has { 'key': value }.

::

vars = dict(name="Bob")
results = db.select('users', where="name = $name", vars=vars, _test=True)
>>> results
<sql: "SELECT * FROM users WHERE name = 'Bob'">


Updating
````````
The `update` method accepts same kind of arguments as Select. It returns the number of rows updated.

::

num_updated = db.update('users', where="id = 10", firstname = "Foo")

Deleting
````````
The `delete` method returns the number of rows deleted. It also accepts "using" and "vars" parameters. See ``Selecting`` for more details on `vars`.

::

num_deleted = db.delete('users', where="id=10")

Multiple Inserts
````````````````
The `multiple_insert` method on the `db` object allows you to do that. All that's needed is to prepare a list of dictionaries, one for each row to be inserted, each with the same set of keys and pass it to `multiple_insert` along with the table name. It returns the list of ids of the inserted rows.

The value of `db.supports_multiple_insert` tells you if your database supports multiple inserts.
::

values = [{"name": "foo", "email": "[email protected]"}, {"name": "bar", "email": "[email protected]"}]
db.multiple_insert('person', values=values)


Advanced querying
`````````````````
Many a times, there is more to do with the database, rather than the simple operations which can be done by `insert`, `select`, `delete` and `update` - Things like your favorite (or scary) joins, counts etc. All these are possible with `query` method, which also takes `vars`.

::

results = db.query("SELECT COUNT(*) AS total_users FROM users")
print results[0].total_users # prints number of entries in 'users' table

Joining tables
::

results = db.query("SELECT * FROM entries JOIN users WHERE entries.author_id = users.id")


Transactions
````````````
The database object has a method `transaction` which starts a new transaction and returns the transaction object. The transaction object can be used to commit or rollback that transaction. It is also possible to have nested transactions.

From Python 2.5 onwards, which support `with` statements, you would do

::

with db.transaction():
userid = db.insert('users', name='foo')
authorid = db.insert('authors', userid=$userid, vars={'userid': userid})


For earlier versions of Python, you can do

::

t = db.transaction()
try:
userid = db.insert('users', name='foo')
authorid = db.insert('authors', userid=$userid, vars={'userid': userid})
except:
t.rollback()
raise
else:
t.commit()
27 changes: 3 additions & 24 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ Contents:
.. toctree::
:maxdepth: 2

input
db

Hello World
===========

Expand All @@ -21,30 +24,6 @@ urls = (...)

regular expressions and grouping

Taking Inputs
=============

web.input()
web.input(page=0)
reading GET and POST
reading files

Working with database
=====================

web.database()

db.query
db.select
db.insert
db.multiple_insert
db.delete

working with transactions

with db.transaction():
db.insert(..)

Indices and tables
==================

Expand Down
92 changes: 92 additions & 0 deletions docs/input.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
Accessing User Input
====================

While building web applications, one basic and important thing is to respond to the user input that is sent to the server.

Web.py makes it easy to access that whether it is parameters in the url (`GET` request) or the form data (`POST` or `PUT` request). The `web.input()` method returns a dictionary-like object (more specifically a `web.storage` object) that contains the user input, whatever the request method is.


To access the URL parameters (?key=value) from the `web.input` object, just use `web.input().key`.

GET
---

For a URL which looks like `/page?id=1&action=edit`, you do

::

class Page(object):
def GET(self):
data = web.input()
id = int(data.id) # all the inputs are now strings. Cast it to int, to get integer.
action = data.action
...

`KeyError` exception is thrown if `key` is not there in the URL parameters.
Web.py makes it easier to handle that with default values to web.input().

::

class Page(object):
def GET(self):
data = web.input(id=1, action='read')
id, action = int(data.id), data.action
...

POST
----

It works exactly the same way with POST method. If you have a form with `name` and `password` elements, you would do

::

class Login(object):
def POST(self):
data = web.input()
name, password = data.name, data.password
...


Multiple inputs with same name
------------------------------

What if you have a URL which looks like `/page?id=1&id=2&id=3` or you have a form with multiple selects? What would `web.input().id` give us? It simply swallows all but one value. But to let web.input() know that we're expecting more values with the same name is simple. Just pass `[]` as the default argument for that name.

::

class Page(object):
def GET(self):
data = web.input(id=[])
ids = data.id # now, `ids` is a list with all the `id`s.
...


File uploads
------------

Uploading files is easy with web.py. `web.input()` takes care of that too. Just make sure that the upload form has an attribute enctype="multipart/form-data". The `input()` gives you `filename` and `value`, which are the uploaded file name and the contents of it, respectively.
To make things simpler, it also gives you `file`, a file-like object if you pass `myfile={}` where `myfile` is the name of the input element in your form.
::

class Upload(object):
def GET(self):
return render.upload()

def POST(self):
data = web.input(myfile={})
fp = data.myfile
save(fp) # fp.filename, fp.read() gives name and contents of the file
...

or

::

class Upload(object):
...

def POST(self):
data = web.input() # notice that `myfile={}` is missing here.
fp = data.myfile
save(fp.filename, fp.value)
...

0 comments on commit 618466a

Please sign in to comment.