Job Search Engine


752 浏览 5 years, 1 month

2.11 多数据库

版权声明: 转载请注明出处 http://www.codingsoho.com/

多数据库

到目前为止,我们都是在当前数据库操作,但是我们项目的计划是数据分离,爬虫通过独立的数据库爬虫,所以需要将数据库分离,授权和其他非爬虫信息在本地完成,爬虫用独立的数据库。

这个独立数据库我们打算用mysql,mysql的安装参考MySQL

配置文件

添加两个数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },    
    'webscrap': {
        'ENGINE':   'django.db.backends.mysql',
        'NAME':     'bestjob',
        'USER':     'root',
        'PASSWORD': '123',
        'HOST':     '[127.0.0.1](127.0.0.1)',
        'PORT':     '3306',  
    },    
}

webscrap对应的是爬虫生成的数据库,下面添加两个数据库路由配置

DATABASE_ROUTERS = ['jse.database_router.DatabaseAppsRouter']

DATABASE_APPS_MAPPING = {
    # example:
    # 'app_name':'database_name',
    'job_entry': 'webscrap',
}

database_router中完成了数据库的路由。这是一个新添加的文件

from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING
class DatabaseAppsRouter(object):
    def db_for_read(self, model, **hints):
        if model._meta.app_label in DATABASE_MAPPING:
            return DATABASE_MAPPING[model._meta.app_label]
        return None
    def db_for_write(self, model, **hints):
        if model._meta.app_label in DATABASE_MAPPING:
            return DATABASE_MAPPING[model._meta.app_label]
        return None
    def allow_relation(self, obj1, obj2, **hints):
        db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
        db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
        if db_obj1 and db_obj2:
            if db_obj1 == db_obj2:
                return True
            else:
                return False
        return None
    def allow_syncdb(self, db, model):
        if db in DATABASE_MAPPING.values():
            return DATABASE_MAPPING.get(model._meta.app_label) == db
        elif model._meta.app_label in DATABASE_MAPPING:
            return False
        return None
    def allow_migrate(self, db, app_label, model=None, **hints):
        if db in DATABASE_MAPPING.values():
            return DATABASE_MAPPING.get(app_label) == db
        elif app_label in DATABASE_MAPPING:
            return False
        return None

DATABASE_APPS_MAPPING指定了各个app分别走哪个数据库,没列出来的默认走default.

修改模型

model会有一个默认生成的数据表名,我们一般不需要去管它,但是现在用的是外部数据表,所以需要手动指定它

class JobEntry(models.Model):
    class Meta:
        db_table  = 'job_entry'

db_table指定了对应的数据表的名称。

注意:不要去migrate数据库,因为我们并不打算去改表结构。

其他操作

一些其他数据库的操作:

使用指定的数据库来执行操作
# 查询
YourModel.objects.using('db1').all() 
# 或者 
YourModel.objects.using('db2').all()

# 保存 或 删除
user_obj.save(using='new_users')
user_obj.delete(using='legacy_users')
数据库迁移
# Django 1.6及以下版本
python manage.py syncdb #同步默认的数据库,和原来的没有区别

# 同步数据库 db1 (注意:不是数据库名是db1,是settings.py中的那个db1,不过你可以使这两个名称相同,容易使用)
python manage.py syncdb --database=db1

# Django 1.7 及以上版本
python manage.py migrate --database=db1

数据导出

python manage.py dumpdata app1 --database=db1 > app1_fixture.json
python manage.py dumpdata app2 --database=db2 > app2_fixture.json
python manage.py dumpdata auth > auth_fixture.json

数据库导入

python manage.py loaddata app1_fixture.json --database=db1
python manage.py loaddata app2_fixture.json --database=db2