Replacing Django's ORM with SQLAlchemy
django (72)In the first example of Django's loose coupling我们看着用Jinja2取代模板系统。在本文中,我们将仔细查看替换标准的Django OrmSqlalchemy.。这是一个非常大的飞跃,并且在我们跳过太深时,我们会看看如何切换到Sqlalchemy将影响我们的应用程序。 p>
在本系列的介绍中,我表示,Django的实施遵循松散的耦合理念,但我们可能需要在那种陈述中添加几粒盐,因为我们考虑从Django的ORM转换为Sqlalchemy造成的变化。首先,我们将不再能够使用Django模特.py.
files to describe our models. Instead, we'll be using SQLAlchemy's ORM for defining tables and fields (which will look pretty similar). p>
在此之后,我们将无法使用简单python manage.py syncdb.
to create the tables for our project. We won't be able to usepython manage.py loadata.
或者python manage.py dumpdata
创建用作Django测试框架的初始数据或脚手架的夹具。如果我们只是使用SQLALCHEMY严格,我们甚至无法使用Django Admin,Sessions中间件或身份验证中间件等贡献资源。 p>
这里带走的消息是,虽然Django松散耦合,但它是松散耦合并不意味着去耦没有后果。改变一些系统,如模板渲染,后果很少,但其他人 - 就像Django Orm一样 - 是远离插头和播放的。这是不可避免的,因为完美的去耦额额外的Onus对各个开发人员来说,并将使其更慢地(更复杂),以使Django项目启动和运行。当你第一次使用django开始时,很难衡量子系统对解耦的那么昂贵,这就是为什么它高度推荐使用默认的django堆栈开始,然后在获得更多体验时偏离负责任的原因。 p>
(全面披露:it is possible to use the Django ORM and SQLAlchemy together. This means you could still take advantage of the Django sessions middleware (and most other stuff), while using SQLAlchemy for some parts of your app. This tutorial won't build that Frankenstein, since it's only interested in exploring the loose coupling aspect, but it wouldn't be prohibitively difficult to do so. Although, it would be awkward in some regards.) p>
现在让我们开始将银变成金色1。 p>
使用sqlalchemy与django
首先,我们需要下载Sqlalchemy。最简单的方法是使用
Easy_install.
。 p>Easy_install.Sqlalchemy.
但你也可以grab a copy of the 0.5 release at their download page.。本教程正在使用0.5beta2,但只要您不抓取0.4释放,应正常工作。 p>
如果您选择手动下载文件,则需要安装它们: p>
tar zxvf SQLAlchemy-0.5.0beta2.tar.gz光盘sqlalchemy-0.5.0beta2 python setup.py安装
If you are using a Python before 2.5 you'll need to installpysqlite.和sqlite.也是。 p>
现在让我们确保安装正常工作。 p>
>>>进口Sqlalchemy.>>>Sqlalchemy.。__版本__'0.5.0beta2'
If SQLAlchemy doesn't import correctly, or if the version isn't some derivative of 0.5, then you'll need to revisit steps one and two. p>
创建Django项目和应用程序。 p>
django_admin.py startproject loose_coupling光盘lock_cuoupling python manage.py startapp with_sqlalchemy
创建几个模板目录。 p>
mkdir模板光盘with_sqlalchemy mkdir模板模板/ with_sqlalchemy
接下来,我们需要在我们的情况下提出一些简单的变化
settings.py
文件。我们将变化INSTALLED_APPS
那template_dirs.
那和middleware_classes.
。 p>middleware_classes.=('django.middleware.common.commonmiddleware'那)INSTALLED_APPS=('loose_coupling.with_sqlalchemy'那)进口OS.ROOT_PATH=OS.。小路。dirname(__文件__)template_dirs.=(OS.。小路。join(ROOT_PATH那'模板')那)
由于我们不使用Django Orm,因此我们不会使用任何数据库依赖的中间件或应用程序。 p>
现在我们将编辑
loosely_coupled / urls.py.
文件。 p>fromdjango.conf.urls.defaults.进口*
urlpatterns=图案('loost_coupling'那(r'^$'那'with_sqlalchemy.views.index')那)
Normally we'd use include a
Urls.py.
来自档案的文件with_sqlalchemy.
app into the project'sUrls.py.
文件,但我们试图保持简单的事情。 p>现在我们将使用SQLALCHEMY ORM来创建一个简单的表来播放。因为文件已经存在,我们将把表定义扔进
模特.py.
那so go ahead and open upwith_sqlalchemy / models.py.py.
。 p>fromSqlalchemy.进口Table那柱子那Integer那细绳那MetaData那ForeignKeyfromSqlalchemy.。ext.declarative进口declarative_base
Base=declarative_base()班级语(Base):Tablename.='语言'id=柱子(Integer那primary_key=True)名称=柱子(细绳)extension=柱子(细绳)
def __init__(self, name, extension): self.name = name self.extension = extension def __repr__(self): return u"Language(%s, %s)" % (self.name, self.extension)
我们可以看到Sqlalchemy可以定义与我们为Django定义的模型非常相似。我们不会在这里浏览它,但是通过定义数据库表然后,Sqlalchemy也可以更低级别。mapping them onto a Python class。你甚至可以完全使用ORM跳过并利用他们的构造SQL的界面。 p>
现在我们会写我们的
观点
文件。第一的,we have some imports to begin our file with. p>fromdjango.shortcuts进口render_to_response.进口Sqlalchemy.那Sqlalchemy.。或者mfrom楷模进口Base那语
然后我们需要设置sqlalchemy以使我们的
语
班级available. p>引擎=Sqlalchemy.。create_engine.('sqlite:///loose.sqlite')会议=Sqlalchemy.。或者m。会议制造者(捆绑=引擎)会议=会议()Base。元数据。create_all.(引擎)
这
sqlite:///loose.sqlite
指令在相对路径上创建一个SQLite数据库松散
那i.e. within thewith_sqlalchemy.
目录。Sqlalchemy使它同样容易指定绝对路径,或在内存中创建数据库。如果我们想让这个更加愚蠢,我们可以指定数据库名称
setting insettings.py
,然后加载这样的值: p>fromdjango.conf.进口settings引擎=Sqlalchemy.。create_engine.(settings。database_engine.)
Also, the
Base.metadata.create_all(engine)
only really needs to be done once when SQLAlchemy first creates the table (although doing it multiple times doesn't hurt anything), but that would involve creating a counter-part to thepython manage.py syncdb.
脚本中的功能,并使示例更复杂,因此我们现在正在跳过这一点。 p>接下来,我们将创建两个真正简单的实用程序功能,我们将用于填充我们的数据: p>
defis_empty():returnLen.(会议。询问(语)。all())<=0.
defpopulate():纽约=[语('Python'那'py')那语('红宝石'那'rb')那语('常见的lisp'那'lisp')那语('Objective-C'那'M')]会议。都加进去(纽约)会议。犯罪()
这些简单的功能是用于流行ulate our database with some data. It also provides a minimal example of the SQLAlchemy querying and object creation syntaxes, which are very similar to those in the Django ORM. p>
最后,我们需要写下
index
功能。 p>defindex(要求):ifis_empty():populate()郎=会议。询问(语)。all()returnrender_to_response.('with_sqlalchemy / index.html',{'langs':郎})
In a better designed application we wouldn't need to make sure we'd created the test data each time we call the
index
查看,然后视图看起来像这样: p>defindex(要求):郎=会议。询问(语)。all()returnrender_to_response.('with_sqlalchemy / index.html',{'langs':郎})
这看起来几乎与之与Django ORM写作(仅对检索数据的略微语法差异)相同。 p>
现在我们需要创造
with_sqlalchemy./index.html
template that we are rendering. First we'll create a base template, located inloose_coupling/templates
那和名称dbase.html.
。It will look like this: p>Loosely Coupled Django title> head>{%block内容%}{%endblock%} body> html> And next we'll create the
index.html.
template. Open upwith_sqlalchemy / templates / with_sqlalchemy / index.html
,并填写: p>{%延伸'base.html'%}{%block内容%}{%为了郎in郎%}{{郎}} p>{%终止%}{%endblock%}
关于这些模板的最重要的是,我们通过SQLALCHEMY ORM生成的实例,但它看起来与模板如何处理Django ORM的方式相同:模板语言是无知的细节Django Orm,并且可以用于从正常的Django模型实例到普通Python Dicts的任何内容。 p>
现在一切都结束了,只是等着我们测试。 p>
python manage.py runserver
这n navigate over thehttp://127.0.0.1:8000/。您将看到四种编程语言及其扩展的简单显示。 p>
您可以在这里抓取项目的副本。它恰好是一个git存储库,但你可以在没有/使用git的情况下使用它。 p>
现在,这个例子比与jinja2一起合作的前一个透明有用,但它仍然演示了关于django的两个重要点。第一的,django是python.那so you can do anything in Django that you could do outside of Django. Second, Django is loosely coupled, but sometimes it isloosely coupled with consequences,并解耦了一些子系统 - 尤其是orm - 不是无痛的。 p>
As a final point, I'd like to apologize for the disservice that is done to SQLAlchemy in this entry. SQLAlchemy is an extremely full-featured and versatile system, and the usage here makes it look like a mirror image of the Django ORM. It isn't. Not by a long shot. SQLAlchemy can abstract things similarly to the Django ORM, but makes it much easier to get dirty, and also exposes more advanced functionality like connection pools. p>
好的,最后的最后一点:我认为本教程本身就讲话,但我不建议从Django Orm上解耦而没有一个极其令人信服的原因。它是Django的所有子部分最耦合的,并且肯定不会替换。 p>
对于那些令人失望的人来说,通过没有看着Django不公平地看着Django Orm和Sqlalchemy Orm一起,有心脏,这个系列中的下一个例子将看一下这些线的东西(但其中包括一个稍微逼真的情况)。 p>
I felt like I was obligated to make at least one lame alchemy related joke and/or pun. Consider the itch scratched.↩