Sections:
|
SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... An example of loading a database entry in a controller method, performing a sex change, and saving it:
SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... Working with joined objectsRecall that my_addresses property is a list of Address objects
To add an existing address to 'Mr Jones' we do the following:
To add an entirely new address to 'Mr Jones' we do the following:
After making changes you must call Session.commit() to store them permanently in the database; otherwise they'll be discarded at the end of the web request. You can also call Session.rollback() at any time to undo any changes that haven't been committed. To search on a joined object we can pass an entire object as a query:
Or we can can search on a joined objects' property,
A shortcut for the above is to use any():
To disassociate an address from Mr Jones we do the following:
To delete the address itself in the address table, normally we'd have to issue a separate delete() for the Address object itself:
However, SQLAlchemy supports a shortcut for the above operation. Configure the mapper relation using cascade = "all, delete-orphan" instead:
Then, any items removed from mr_jones.my_addresses is automatically deleted from the database:
For any relationship, you can add cascade = "all, delete-orphan" as an extra argument to relation() in your mappers to ensure that when a join is deleted the joined object is deleted as well, so that the above delete() operation is not needed - only the removal from the my_addresses list. Beware though that despite its name, delete-orphan removes joined objects even if another object is joined to it. SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... To delete the address itself in the address table, normally we'd have to issue a separate delete() for the Address object itself:
Pylons
SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... The config fileIn development.ini enter the following in the [app:main] section, depending on your database, For SQLite
Where mydatabasefilename.db is the path to your SQLite database file. "%(here)s" represents the directory containing the development.ini file. For MySQL
Enter your username, password, host (localhost if it is on your machine), port number (usually 3306) and the name of your database. The second two lines are optional; they're examples of setting engine options The "pool_recycle" line is important for MySQL; it makes SQLAlchemy close and reopen database connections after one hour (3600 seconds) of use; this prevents MySQL from unilaterally closing them after a few hours idle time, which avoids "MySQL server has gone away" errors. For PostgreSQL
Enter your username, password, host (localhost if it is on your machine), port number (usually 5432) and the name of your database. Note: Some people prefer "sqlalchemy.default.url" instead of "sqlalchemy.url", to make things easier if they add a second database later (described in "Multiple Engines" below). SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... ModelReplace the content of myapp/model/__init__.py in your application with something like this:
This provides access to one engine. Using multiple engines is described below. Relation exampleHere's an example of a Person and an Address class with a many:many relationship on people.my_addresses. See Relational databases for people in a hurry and the SQLAlchemy manual for details.
SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... ControllerAdd the following code to your base controller's .__call__ method in myapp/lib/base.py:
The .remove() method is very important! It discards any leftover ORM data in the current web request. Otherwise the stray data will leak into the next request handled by this thread, potentially causing errors or data corruption. Any per-request behaviors can be configured at this stage. For example, to use just a single database connection per request, which removes all connection pool checkin/checkout overhead, the per-request Session can be configured with a Connection:
Note that when using a session with transactional=True, the session holds onto a single connection through the lifespan of each transaction so the above optimization is not as significant. SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... Data queries and modificationsImportant: this section assumes you're putting the code in a high-level model function. If you're putting it directly into a controller method, you'll have to put a model. prefix in front of every object defined in the model, or import the objects individually. Also note that the Session object here (capital s) is not the same as the Beaker session object (lowercase s) in controllers. Here's how to enter new data into the database:
mr_jones here is an instance of Person. Its properties correspond to the column titles of people_table and contain the data from the selected row. A more sophisticated application would have a Person.__init__ method that automatically sets attributes based on its arguments. An example of loading a database entry in a controller method, performing a sex change, and saving it:
To return a list of entries use:
To get all list of all the people in the table use:
To retrieve by id:
You can iterate over every person even more simply:
To delete an entry use the following:
SQLAlchemy 0.4 for people in a hurry - Pylons Cookbook - PythonWeb
wiki.pylonshq.com/display/pylonscookbook/SQLAlchem... Building the databaseTo actually create the tables in the database, customize myapp/websetup.py. After the load_environment() call put:
Then run the following on the command line: paster setup-app development.ini The line we added connects to the database and creates all the tables we've defined. SqlAlchemy
|