Home  >  Article  >  Backend Development  >  Django integrates existing databases and applications

Django integrates existing databases and applications

黄舟
黄舟Original
2017-01-17 14:01:041293browse

Django is best suited for so-called green-field development, which is a project from scratch, just like you are building a building from scratch on an uncultivated land with green grass. However, despite Django's preference for projects from scratch, it is still possible to integrate the framework with previous legacy databases and applications. This chapter will introduce some integration techniques.


Integration with legacy databases

Django’s database layer generates SQL
schemas from Python code—but for legacy databases, you already have SQL schemas, in which case you need to write models for your already existing database tables (due to For performance reasons, Django's database layer doesn't support object-relational mapping via runtime introspection of the database (which doesn't work (in order to use the database API, you need to write model code)). Fortunately, Django comes with planning by reading your database tables. An auxiliary tool to generate model code. The auxiliary tool is called manage.py
inspectdb


Use inspectdb

The inspectdb tool introspectively checks the database pointed to by your configuration file (setting file), and generates it for each of your tables The performance of a Django
model, and then displays the code of these Python models in the standard output of the system.


The following is an integration process for a typical legacy database from scratch


Set up a Django project by running django-admin.py startproject mysite (where mysite is the name of your project). Okay, let's use mysite as the name of the project in this example.


Edit the configuration file in the project,
mysite/settings.py, and tell Django your database connection parameters and database name. Specifically, provide the configuration information DATABASE_NAME, DATABASE_ENGINE, DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, and DATABASE_PORT.


Create a Django application by running pythonmysite/manage.pystartappmyapp (where myapp is the name of your application). Then , we will use myapp as the name of this application.


Run the command pythonmysite/manage.pyinspectdb. This will check all tables in the DATABASE_NAME database and print out the model
class generated for each table. Take a look Look at the output and think about what inspectdb can do.


Redirect the output of the standard shell and save the output to the models.py file of your application:

python mysite/manage.py inspectdb > mysite/ myapp/models.py

Edit the mysite/myapp/models.py file to clean up the generated models and make any necessary customizations. The next chapter has some good advice on this.


Clean up generated Models

As you might expect, database introspection is not perfect and you will need to do some cleanup on the generated model code. Here is a reminder about the key points about processing generated models:


Every table in the database will be converted into a model class (that is, there is a one-to-one mapping between the database table and the model class). This means that you need to refactor the tables whose models are ManyToManyField objects for many-to-many joins.


Each field in each generated model has its own attributes, including the id primary key field. However, please note that if a model does not have a primary key, Django will automatically add an Id primary key field to it. In this case, you may want to use the following code to perform a delete operation on any row:

id = models.IntegerField(primary_key=True)

This is not just because these rows are redundant, but also if when your These rows can cause problems when an application needs to add new records to these tables. The inspectdb command cannot detect whether a field is auto-increasing, so when necessary, you must modify them to AutoField.


Each field type, such as CharField, DateField, is determined by looking for database column types such as VARCHAR , determined by DATE. If inspectdb cannot map a model field type according to the database column type, it will use the TextField field instead, and will add a Python comment "The field type is guessed" after the generated model field. Therefore, please pay special attention to this and modify these field types accordingly when necessary.


If a field in your database cannot find a suitable counterpart in Django, you can safely skip it, because the Django layer does not require it to contain every field in your table.


If the name of a column in the database is a reserved word of Python, such as pass, class or for, etc., inspectdb will append _field after each attribute name and set the db_column attribute to the real field name , such as pass, class or for, etc.


For example, if a table contains an INT type column with the column name for, then the generated model will contain a field as shown below:

for_field = models.IntegerField(db_column='for' )

inspectdb will add 'field rename because it is a Python reserved word' after the field.


如果数据库中某张表引用了其他表(正如大多数数据库系统所做的那样),你需要适当的修改所生成model的顺序,以使得这种引用能够正确映射。例如,model Book拥有一个针对于model
Author的外键,那么后者应该先于前者被定义。如果你需要为一个还没有被定义的model创建一个关系,那么你可以使用该model的名字,而不是model对象本身。


对于PostgreSQL,MySQL和SQLite数据库系统,inspectdb能够自动检测出主键关系。也就是说,它会在合适的位置插入primary_key=True。而对于其他数据库系统,你必须为每一个model中至少一个字段插入这样的语句,因为Django的model要求必须拥有一个primary_key=True的字段。


外键检测仅对PostgreSQL,还有MySQL表中的某些特定类型生效。至于其他数据库,外键字段都将在假定其为INT列的情况下被自动生成为IntegerField。


与认证系统的整合


将Django与其他现有认证系统的用户名和密码或者认证方法进行整合是可以办到的。


例如,你所在的公司也许已经安装了LDAP,并且为每一个员工都存储了相应的用户名和密码。如果用户在LDAP和基于Django的应用上拥有独立的账号,那么这时无论对于网络管理员还是用户自己来说,都是一件很令人头痛的事儿。


为了解决这样的问题,Django认证系统能让您以插件方式与其他认证资源进行交互。您可以覆盖Diangos的默认基于数据库模式,您还可以使用默认的系统与其他系统进行交互。


指定认证后台


在后台,Django维护了一个用于检查认证的后台列表。当某个人调用django.contrib.auth.authenticate()(如12章中所述)时,Django会尝试对其认证后台进行遍历认证。如果第一个认证方法失败,Django会尝试认证第二个,以此类推,一直到尝试完全部。


认证后台列表在AUTHENTICATION_BACKENDS设置中进行指定,它应该是指向知道如何认证的Python类的Python路径的名字数组,这些类可以放置在您的Python路径的任何位置上。


默认情况下,AUTHENTICATION_BACKENDS被设置为如下:

('django.contrib.auth.backends.ModelBackend',)

那就是检测Django用户数据库的基本认证模式。


对于多个顺序组合的AUTHENTICATION_BACKENDS,如果其用户名和密码在多个后台中都是有效的,那么Django将会在第一个正确通过认证后停止进一步的处理。


如何写一个认证后台


一个认证后台其实就是一个实现了如下两个方法的类:get_user(id)和authenticate(**credentials)。


方法get_user需要一个参数id,这个id可以是用户名,数据库ID或者其他任何数值,该方法会返回一个User对象。


方法authenticate使用证书作为关键参数。大多数情况下,该方法看起来如下:

class MyBackend(object):
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.

但是有时候它也可以认证某个令牌,例如:

class MyBackend(object):
def authenticate(self, token=None):
# Check the token and return a User.

每一个方法中,authenticate都应该检测它所获取的证书,并且当证书有效时,返回一个匹配于该证书的User对象,如果证书无效那么返回None。


如Django会话、用户和注册中所述,Django管理系统紧密连接于其自己后台数据库的User对象。实现这个功能的最好办法就是为您的后台数据库(如LDAP目录,外部SQL数据库等)中的每个用户都创建一个对应的Django
User对象。您可以提前写一个脚本来完成这个工作,也可以在某个用户第一次登陆的时候在authenticate方法中进行实现。


以下是一个示例后台程序,该后台用于认证定义在setting.py文件中的username和password变量,并且在该用户第一次认证的时候创建一个相应的DjangoUser对象。

from django.conf import settings
from django.contrib.auth.models import User, check_password
class SettingsBackend(object):
"""
Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
Use the login name, and a hash of the password. For example:
ADMIN_LOGIN = 'admin'
ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
"""
def authenticate(self, username=None, password=None):
login_valid = (settings.ADMIN_LOGIN == username)
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
if login_valid and pwd_valid:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. Note that we can set password
# to anything, because it won't be checked; the password
# from settings.py will.
user = User(username=username, password='get from settings.py')
user.is_staff = True
user.is_superuser = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:

return None和遗留Web应用集成

同由其他技术驱动的应用一样,在相同的Web服务器上运行Django应用也是可行的。最简单直接的办法就是利用Apaches配置文件httpd.conf,将不同的URL类型代理至不同的技术。


关键在于只有在您的httpd.conf文件中进行了相关定义,Django对某个特定的URL类型的驱动才会被激活。在第20章中解释的缺省部署方案假定您需要Django去驱动某个特定域上的每一个页面。

<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On
</Location>

这里, a18e6dc59b27f1dbd64eaa88f15b0c14这一行表示用Django处理每个以根开头的URL.


精妙之处在于Django将9d68f4d645dd62cd4e002580b75a8b85指令值限定于一个特定的目录树上。举个例子,比如说您有一个在某个域中驱动大多数页面的遗留PHP应用,并且您希望不中断PHP代码的运行而在../admin/位置安装一个Django域。要做到这一点,您只需将9d68f4d645dd62cd4e002580b75a8b85值设置为/admin/即可。

<Location "/admin/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On
</Location>

有了这样的设置,只有那些以/admin/开头的URL地址才会触发Django去进行处理,而任何其他页面依旧按之前已经存在的那些设置进行处理。


请注意,让Diango去处理那些合格的URL(比如在本章例子中的/admin/)并不会影响其对URL的解析。绝对路径对Django才是有效的(例如/admin/people/person/add/),而非去掉/admin/后的那部分URL(例如``/people/person/add/)。这意味着您的根URLconf必须包含居前的/admin/。

以上就是Django集成已有的数据库和应用的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn