- 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.
- Monkey Game Development:Beginner's Guide
- 從程序員到架構師:大數據量、緩存、高并發、微服務、多團隊協同等核心場景實戰
- 深入淺出Windows API程序設計:編程基礎篇
- Building a Recommendation Engine with Scala
- Mastering AndEngine Game Development
- Learning ELK Stack
- Mastering Google App Engine
- Spring Boot Cookbook
- Visualforce Developer’s guide
- Visual C#.NET Web應用程序設計
- Odoo 10 Implementation Cookbook
- Backbone.js Testing
- Django Design Patterns and Best Practices
- Go語言從入門到精通
- MyBatis 3源碼深度解析