官术网_书友最值得收藏!

  • Learning Flask Framework
  • Matt Copperwaite Charles Leifer
  • 948字
  • 2021-07-30 10:18:34

Introducing SQLAlchemy

SQLAlchemy is an extremely powerful library for working with relational databases in Python. Instead of writing SQL queries by hand, we can use normal Python objects to represent database tables and execute queries. There are a number of benefits to this approach, as follows:

  • Your application can be developed entirely in Python.
  • Subtle differences between database engines are abstracted away. This allows you to do things just like a lightweight database, for instance, use SQLite for local development and testing, then switch to the databases designed for high loads (such as PostgreSQL) in production.
  • Database errors are less common because there are now two layers between your application and the database server: the Python interpreter itself (this will catch the obvious syntax errors), and SQLAlchemy, which has well-defined APIs and its own layer of error-checking.
  • Your database code may become more efficient, thanks to SQLAlchemy's unit-of-work model that helps reduce unnecessary round-trips to the database. SQLAlchemy also has facilities for efficiently pre-fetching related objects known as eager loading.
  • Object Relational Mapping (ORM) makes your code more maintainable, an aspiration known as don't repeat yourself, (DRY). Suppose you add a column to a model. With SQLAlchemy it will be available whenever you use that model. If, on the other hand, you had hand-written SQL queries strewn throughout your app, you would need to update each query, one at a time, to ensure that you were including the new column.
  • SQLAlchemy can help you avoid SQL injection vulnerabilities.
  • Excellent library support: As you will see in later chapters, there are a multitude of useful libraries that can work directly with your SQLAlchemy models to provide things such as maintenance interfaces and RESTful APIs.

I hope you're excited after reading this list. If all the items in this list don't make sense to you right now, don't worry. As you work through this chapter and the subsequent ones, these benefits will become more apparent and meaningful.

Now that we have discussed some of the benefits of using SQLAlchemy, let's install it and start coding.

Note

If you'd like to learn more about SQLAlchemy, there is a chapter devoted entirely to its design in The Architecture of Open-Source Applications, available online for free at http://aosabook.org/en/sqlalchemy.html.

Installing SQLAlchemy

We will use pip to install SQLAlchemy into the blog app's virtualenv. As you will recall from the previous chapter, to activate your virtualenv, change directories to source the activate script as follows:

$ cd ~/projects/blog
$ source blog/bin/activate
(blog) $ pip install sqlalchemy
Downloading/unpacking sqlalchemy

Successfully installed sqlalchemy
Cleaning up...

You can check if your installation succeeded by opening a Python interpreter and checking the SQLAlchemy version; note that your exact version number is likely to differ.

$ python
>>> import sqlalchemy
>>> sqlalchemy.__version__
'0.9.0b2'

Using SQLAlchemy in our Flask app

SQLAlchemy works very well with Flask on its own, but the author of Flask has released a special Flask extension named Flask-SQLAlchemy that provides helpers with many common tasks, and can save us from having to re-invent the wheel later on. Let's use pip to install this extension:

(blog) $ pip install flask-sqlalchemy

Successfully installed flask-sqlalchemy

Flask provides a standard interface for the developers who are interested in building extensions. As the framework has grown in popularity, the number of high-quality extensions has increased. If you'd like to take a look at some of the more popular extensions, there is a curated list available on the Flask project website at http://flask.pocoo.org/extensions/.

Choosing a database engine

SQLAlchemy supports a multitude of popular database dialects, including SQLite, MySQL, and PostgreSQL. Depending on the database you would like to use, you may need to install an additional Python package containing a database driver. Listed next are several popular databases supported by SQLAlchemy and the corresponding pip-installable driver. Some databases have multiple driver options, so I have listed the most popular one first.

SQLite comes as standard with Python and does not require a separate server process, so it is perfect for getting up-and-running quickly. For simplicity in the examples that follow, I will demonstrate how to configure the blog app for use with SQLite. If you have a different database in mind that you would like to use for the blog project, feel free to use pip to install the necessary driver package at this time.

Connecting to the database

Using your favorite text editor, open the config.py module for our blog project (~/projects/blog/app/config.py). We are going to add a SQLAlchemy-specific setting to instruct Flask-SQLAlchemy how to connect to our database. The new lines are highlighted in the following:

import os
class Configuration(object):
 APPLICATION_DIR = os.path.dirname(os.path.realpath(__file__))
    DEBUG = True
 SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/blog.db' % APPLICATION_DIR

The SQLALCHEMY_DATABASE_URI comprises the following parts:

dialect+driver://username:password@host:port/database

Because SQLite databases are stored in local files, the only information we need to provide is the path to the database file. On the other hand, if you wanted to connect to PostgreSQL running locally, your URI might look something like this:

postgresql://postgres:secretpassword@localhost:5432/blog_db

Note

If you're having trouble connecting to your database, try consulting the SQLAlchemy documentation on database URIs: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html.

Now that we've specified how to connect to the database, let's create the object responsible for actually managing our database connections. This object is provided by the Flask-SQLAlchemy extension and is conveniently named SQLAlchemy. Open app.py and make the following additions:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

from config import Configuration

app = Flask(__name__)
app.config.from_object(Configuration)
db = SQLAlchemy(app)

These changes instruct our Flask app, and in turn SQLAlchemy, how to communicate with our application's database. The next step will be to create a table for storing blog entries and, to do so, we will create our first model.

主站蜘蛛池模板: 东阳市| 密山市| 朝阳市| 阿勒泰市| 巢湖市| 安化县| 南岸区| 丰宁| 仪征市| 浠水县| 沅江市| 微山县| 漯河市| 通河县| 大名县| 镇江市| 博兴县| 白山市| 体育| 米林县| 营山县| 马鞍山市| 敦煌市| 清涧县| 开平市| 如皋市| 香港 | 汽车| 西贡区| 馆陶县| 重庆市| 衡东县| 隆德县| 苏尼特左旗| 辉县市| 吉隆县| 阿克苏市| 东阳市| 清远市| 武定县| 军事|