Database

This isn’t really something flask comes with, but it’s a good demonstration of using parts of flask to manage database connections.

This code is specific to the blueprint, you can potentially mix completely different databases and transaction semantics in one application.

Code

Example of using signals to manage a database connection

pythonie.blueprints.database.add()[source]

Add a new book via POST

To see in action go to http://building-webapps-with-flask.herokuapp.com/database/add/

Note the use of methods in the decorator to only accept POST.

Parameters:
  • title – The book’s title
  • description – The book’s description
pythonie.blueprints.database.connect()[source]

Creates a per request connection and transaction

pythonie.blueprints.database.disconnect(exception)[source]

Commits or rolls back the transaction and disconnects

pythonie.blueprints.database.index()[source]

List all the books in JSON

To see in action go to http://building-webapps-with-flask.herokuapp.com/database/

pythonie.blueprints.database.init_db()[source]

Creates the initial database connection

Fired before the first HTTP request (to any part of the site).

tests.test_pythonie.test_database(app)[source]

URLs

POST /database/add/

Add a new book via POST

To see in action go to http://building-webapps-with-flask.herokuapp.com/database/add/

Note the use of methods in the decorator to only accept POST.

Parameters:
  • title – The book’s title
  • description – The book’s description
GET /database/

List all the books in JSON

To see in action go to http://building-webapps-with-flask.herokuapp.com/database/

GET /

To see this in action go to http://building-webapps-with-flask.herokuapp.com/