Django integrates existing databases and applications

Source: Internet
Author: User
Tags ldap sqlite database
Django is best suited for so-called Green-field development, a project that starts from scratch, as you build a building from scratch on a piece of uncultivated land that has a grassy field. However, while Django prefers a project from scratch, it is still possible to integrate this framework with previously legacy databases and applications. This chapter will cover some of the techniques of integration.


Integration with Legacy databases

Django's database layer generates SQL from Python code
schemas-but for a legacy database, you already have SQL schemas, in which case you need to write a model for your existing database tables (for performance reasons, the Django database layer does not support non-working object-relational mappings through the run-time introspection database. In order to use the database API, you need to write the model code, fortunately, Django comes with a helper tool that generates model code by reading your database table plan, which is called manage.py
Inspectdb


Using Inspectdb

The Inspectdb tool introspection examines the database that your profile (setting file) points to, generating a django for each of your tables
Model, and then display the Python model's code in the standard output of the system.


Here is a starting from scratch the consolidation process for a typical legacy database


Build a Django project by running django-admin.py Startproject MySite (here MySite is the name of your project). OK, so we'll use this mysite as the name of the project in this example.


Edit the configuration file in the project,
mysite/settings.py, tell Django your database connection parameters and database name. Specifically, to provide database_name,database_engine,database_user,database_password,database_host, and database_port these configuration information.


Create a Django application by running Pythonmysite/manage.pystartappmyapp (where MyApp is the name of your app). So, we'll use MyApp as the name of the app.


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


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

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

Edit the mysite/myapp/models.py file to clean up the generated models and some of the necessary customizations. The next section has some good suggestions for this.


Clean up the generated models

As you might expect, database introspection is not perfect, and you need to clean up the generated model code a bit. Here is a reminder of the key points for dealing with generating models:


Each table in the database is converted to a model class (that is, a one-to-two mapping between the database's table and the model's Class). This means that you need to refactor the models to a Manytomanyfield object for many-to-many connected tables.


Each field in the generated model has its own properties, including the ID primary key field. Note, however, that if a model does not have a primary key, Django automatically adds an ID primary key field to it. In this way, you might want to use the following code to perform a delete operation on any row:

id = models. Integerfield (Primary_key=true)

This is not done simply because the rows are redundant, and if your application needs to add new records to these tables, these lines cause some problems. The INSPECTDB command does not detect whether a field is self-growing, so when necessary, you must change them to Autofield.


Each field type, such as Charfield, Datefield, is determined by locating the database column type, such as Varchar,date. If INSPECTDB cannot map a model field type based on the database column type, it uses the TextField field instead and adds a python comment "This field type is guessed" after the generated model field. Therefore, please pay particular attention to this and modify these field types as 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 that each field in your table be included.


If the name of a column in the database is a python reserved word, such as pass, class, or for, Inspectdb appends a _field to each property name and sets the Db_column property to the real field name, such as Pass, Class or for.


For example, if a table contains a column of type int whose column name is for, the resulting model will contain a field such as the one shown below:

For_field = models. Integerfield (db_column= ' for ')

Inspectdb will add a ' field rename after this field because it is a python reserved word '.


If a table in the database refers to other tables (as most database systems do), you need to modify the order of the generated model appropriately so that the references are mapped correctly. For example, the model book has a model
Author the foreign key, the latter should be defined before the former. If you need to create a relationship for a model that is not yet defined, you can use the model's name instead of the model object itself.


For Postgresql,mysql and SQLite database systems, INSPECTDB can automatically detect primary key relationships. That is, it inserts primary_key=true in the right place. For other database systems, you must insert such a statement for at least one field in each model, because the Django model requires that you have a primary_key=true field.


Foreign key detection takes effect only for PostgreSQL, and some specific types in the MySQL table. As with other databases, foreign key fields are automatically born as Integerfield if they are assumed to be an int column.


Integration with the certification system


It is possible to integrate Django with the username and password or authentication methods of other existing authentication systems.


For example, your company may already have LDAP installed, and the appropriate user name and password are stored for each employee. If users have separate accounts on both LDAP and Django-based applications, it can be a headache for both the network administrator and the user.


To solve this problem, the Django authentication system enables you to interact with other authentication resources in a plug-in manner. You can override the default database-based schema for Diangos, and you can also use the default system to interact with other systems.


Specify the authentication background


In the background, Django maintains a background list to check for authentication. When a person calls Django.contrib.auth.authenticate () (as described in Chapter 12), Django attempts to traverse the authentication background for its authentication. If the first authentication method fails, Django tries to authenticate the second, and so on, until it tries the full part.


The authentication background list is specified in the Authentication_backends settings, and it should be an array of names that point to the python path of the Python class that knows how to authenticate, and these classes can be placed anywhere on your Python path.


By default, Authentication_backends is set to the following:

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

That's the Basic authentication mode that detects the Django user database.


For multiple sequential combinations of authentication_backends, if their username and password are valid in more than one background, Django will stop further processing after the first one is properly authenticated.


How to write an authentication background


An authentication background is actually a class that implements the following two methods: Get_user (ID) and authenticate (**credentials).


Method Get_user requires a parameter ID, which can be a user name, a database ID, or any other value, and the method returns a User object.


Method authenticate uses a certificate as a key parameter. In most cases, the method looks like this:

Class Mybackend (object):D EF authenticate (self, Username=none, password=none): # Check The Username/password and return a U Ser.

But sometimes it can also authenticate a token, for example:

Class Mybackend (object):D EF authenticate (self, token=none): # Check The token and return a User.

In each method, authenticate should detect the certificate it obtains, and when the certificate is valid, returns a user object that matches that certificate, and returns none if the certificate is invalid.


As described in Django sessions, users, and registrations, the Django management system is tightly connected to the user object of its own background database. The best way to do this is to create a corresponding Django for each user in your backend database (such as LDAP directory, external SQL database, etc.)
The user object. You can write a script in advance to do this, or you can implement it in the Authenticate method when a user logs on for the first time.


The following is a sample daemon that authenticates the username and password variables defined in the setting.py file, and creates a corresponding Djangouser object when the user first authenticates.

From django.conf import settingsfrom django.contrib.auth.models import User, Check_passwordclass 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 = Trueus Er.is_superuser = Trueuser.save () return Userreturn nonedef get_user (self, user_id): Try:return User.objects.get (pk= user_id) except User.doesnotexist:

Return none and legacy Web application integration

As with other technology-driven applications, it is also possible to run a Django application on the same Web server. The simplest and most straightforward approach is to use the Apaches configuration file httpd.conf to broker different URL types to different technologies.


The key is that the driver for a particular URL type will be activated only if the relevant definition is made in your httpd.conf file. The default deployment scenario explained in chapter 20th assumes that you need Django to drive every page on a particular domain.

<location "/" >sethandler Python-programpythonhandler django.core.handlers.modpythonSetEnv Django_settings_ MODULE Mysite.settingspythondebug on</location>

Here, <location "/" > This line means using Django to process each URL that begins with the root.


The subtlety is that Django restricts the <location> instruction value to a specific directory tree. For example, you have a legacy PHP application that drives most pages in a domain, and you want to not interrupt the operation of the PHP code. /admin/location to install a Django domain. To do this, you only need to set the <location> value to/admin/.

<location "/admin/" >sethandler python-programpythonhandler django.core.handlers.modpythonSetEnv Django_ Settings_module Mysite.settingspythondebug on</location>

With this setting, only URLs that start with/admin/will trigger Django to process, and any other pages still work on those that already exist.


Please note that having Diango handle those URLs that are qualified (for example,/admin/in this chapter) does not affect its parsing of URLs. The absolute path is valid for Django (for example,/admin/people/person/add/), not the part of the URL after/admin/(for example, "/people/person/add/"). This means that your root urlconf must contain the pre-/admin/.

That's what Django integrates with existing databases and applications, and more about topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.