Full Stack Python logo Full Stack Python

全部主题 | Blog | 时讯 | @fullstackpython | Facebook | 源码

SQLAlchemy

SQLAlchemy (source code) is a well-regarded database toolkit and object-relational mapper (ORM) implementation written in Python. SQLAlchemy provides a generalized interface for creating and executing database-agnostic code without needing to write SQL statements.

SQLAlchemy logo.

Why is SQLAlchemy a good ORM choice?

SQLAlchemy isn't just an ORM- it also provides SQLAlchemy Core for performing database work that is abstracted from the implementation differences between PostgreSQL, SQLite, etc. In some ways, the ORM is a bonus to Core that automates commonly-required create, read, update and delete operations.

SQLAlchemy can be used with or without the ORM features. Any given project can choose to just use SQLAlchemy Core or both Core and the ORM. The following diagram shows a few example configurations with various application software stacks and backend databases. Any of these configurations can be a valid option depending on what type of application you are coding.

Example SQLAlchemy configurations with different web frameworks.

A benefit many developers enjoy with SQLAlchemy is that it allows them to write Python code in their project to map from the database schema to the applications' Python objects. No SQL is required to create, maintain and query the database. The mapping allows SQLAlchemy to handle the underlying database so developers can work with their Python objects instead of writing bridge code to get data in and out of relational tables.

SQLAlchemy is an implementation of the object-relational mapping (ORM) concept. Learn more in the data chapter or view all topics.

How does SQLAlchemy code compare to raw SQL?

Below is an example of a SQLAlchemy model definition from the open source compare-python-web-frameworks project that uses SQLAlchemy with Flask and Flask-SQLAlchemy.

  1. class Contact(db.Model):
  2. __tablename__ = 'contacts'
  3. id = db.Column(db.Integer, primary_key=True)
  4. first_name = db.Column(db.String(100))
  5. last_name = db.Column(db.String(100))
  6. phone_number = db.Column(db.String(32))
  7.  
  8. def __repr__(self):
  9. return '<Contact {0} {1}: {2}>'.format(self.first_name,
  10. self.last_name,
  11. self.phone_number)

SQLAlchemy handles the table creation that otherwise we would have had to write a create table statement like this one to do the work:

  1. CREATE TABLE CONTACTS(
  2. ID INT PRIMARY KEY NOT NULL,
  3. FIRST_NAME CHAR(100) NOT NULL,
  4. LAST_NAME CHAR(100) NOT NULL,
  5. PHONE_NUMBER CHAR(32) NOT NULL,
  6. );

By using SQLAlchemy in our Python code, all records can be obtained with a line like contacts = Contact.query.all() instead of a plain SQL such as SELECT * FROM contacts. That may not look like much of a difference in syntax but writing the queries in Python is often faster and easier for many Python developers once multiple tables and specific filtering on fields for queries have to be written. In addition, SQLAlchemy abstracts away idiosyncratic differences between database implementations in SQLite, MySQL and PostgreSQL.

Using SQLAlchemy with Web Frameworks

There is no reason why you cannot use the SQLAlchemy library in any application that requires a database backend. However, if you are building a web app with Flask, Bottle or another web framework then take a look at the following extensions. They provide some glue code along with helper functions that can reduce the boilerplate code needed to connect your application's code with the SQLAlchemy library.

SQLAlchemy resources

The best way to get comfortable with SQLAlchemy is to dig in and write a database-driven application. The following resources can be helpful if you are having trouble getting started or are starting to run into some edge cases.

  • There is an entire chapter in the Architecture of Open Source Applications book on SQLAlchemy. The content is detailed and well worth reading to understand what is executing under the covers.

  • The SQLAlchemy cheatsheet has many examples for querying, generating database metadata and many other common (and not so common) operations when working with Core and the ORM.

  • 10 reasons to love SQLAlchemy is a bit of a non-critical lovefest for the code library. However, the post makes some good points about the quality of SQLAlchemy's documentation and what a pleasure it can be to use it in a Python project.

  • Large web apps in Python: A good architecture goes into issues that expanding codebases face, such as where to put business logic and how to automate database testing. Each of the topics in the article are discussed in the context of a recent project the author worked on that heavily relied on SQLAlchemy.

  • SQLAlchemy and Django explains how one development team uses the Django ORM for most of their standard queries but relies on SQLAlchemy for really advanced queries.

  • SQLAlchemy and data access in Python is a podcast interview with the creator of SQLAlchemy that covers the project's history and how it has evolved over the past decade.

  • Most Flask developers use SQLAlchemy as an ORM to relational databases. If you're unfamiliar with SQLAlchemy questions will often come up such as what's the difference between flush and commit? that are important to understand as you build out your app.

  • SQLAlchemy in batches shows the code that a popular iOS application runs in background batch scripts which uses SQLAlchemy to generate playlists. They provide some context and advice for using SQLAlchemy in batch scripts.

SQLAlchemy compared to other ORMs

SQLAlchemy is one of many Python object-relational mapper (ORM) implementations. Several open source projects and articles are listed here to make it a bit easier to understand the differences between these implementations.

  • SQLAlchemy vs Other ORMs provides a detailed comparison of SQLAlchemy against alternatives.

  • If you're interested in the differences between SQLAlchemy and the Django ORM I recommend reading SQLAlchemy and You by Armin Ronacher.

  • This GitHub project named PythonORMSleepy implements the same Flask application with several different ORMs: SQLAlchemy, Peewee, MongoEngine, stdnet and PonyORM. Looking through the code is helpful for understanding the varying approaches each library takes to accomplish a similar objective.

  • Quora has several answers to the question of which is better and why: Django ORM or SQLALchemy based on various developers' experiences.

What would you like to learn about building Python web apps?

告诉我有关标准关系型数据库的知识。

那些时髦的开发者一直谈论的 NoSQL 数据存储到底是什么?

我想知道在 Python 中如何处理数据。

#### 在这里注册以便每月能收到一份邮件资料,内容包含本站的主要更新、教程和 Python 书籍的打折码等。

The Full Stack Python Guide to Deployments 想找到一个完整的,一步一步的部署方案吗?请看《The Full Stack Python Guide to Deployments》.

邮件获取更新

##### 注册以便每月能收到一份邮件资料,内容包含本站的主要更新和 Python 教程。

目录

1. 简介学习编程为什么用 Python?Python 2 还是 3?企业 PythonPython CommunityBest Python Podcasts最佳 Python 资源最佳 Python 视频2. 开发环境VimEmacs3. 核心语言生成器推导式4. Web 开发Web 框架DjangoFlaskBottlePyramidMorepath其它 Web 框架Web 设计级联样式表 (CSS)JavaScriptWebSockets模板引擎Web 应用安全静态网站生成器Jinja25. 数据关系型数据库NoSQL 数据存储对象关系映射器PostgreSQLMySQLSQLite6. Web APIsAPI 集成API 的创建Twilio7. 部署服务器平台即服务(PaaS)操作系统Web 服务器WSGI 服务器源码控制应用程序依赖静态内容任务队列配置管理持续集成日志监控Web 分析Docker缓存微服务DevOpsNginxApache HTTP 服务器CaddyGreen Unicorn (Gunicorn)UbuntuPelicanLektorMkDocs8. 测试单元测试集成测试代码度量调试9. MetaBotsChange LogFuture DirectionsAbout the AuthorSQLAlchemyPeewee …或者显示全部目录内容.

SQLAlchemy

重要的更新内容会通过 Twitter 账号@fullstackpython发布。


需要更加详细的教程吗?请看 《The Full Stack Python Guide to Deployments》。

Chapters

1. 简介2. 开发环境3. 核心语言4. Web 开发5. 数据6. Web APIs7. 部署8. 测试9. Meta » SQLAlchemy …or view the full table of contents.


This site is based on Matt Makai's project Full Stack Python, thanks for his excellent work!

此网站由 @haiiiiiyun开源爱好者们 共同维护。 若发现错误或想贡献,请访问: Github fullstackpython.cn 项目