MENU

走进科学

计算机科学与技术

Django如何为modals指定数据库

在开发中会遇到需要对数据模型(Modal)指定数据库的情况,去官方的文档看了看,然而并不可以在使用数据模型时指定数据库。并且只能使用默认的‘default’库。可是我的业务使用的表不在默认库中,并还要是用数据模型,这可咋整,继续看官方文档得到一些有用的信息:虽然不可以简单的设置,但可以使用数据库路由

数据库路由器是一个类,最多提供四种方法:
db_for_read(model, **hints)
db_for_write(model, **hints)
allow_relation(obj1, obj2, **hints)
allow_migrate(db, app_label, model_name=None, **hints)

首先在 app项目下创建与modals同级的py文件:名字任意,我这里使用dbrouter.py
定义一个类(这个类就是数据库路由类,同样名字任意,我这里还Dbrouter)

# app/dbrouters.py
from app.models import MyModel #这个就是需要指定数据库的数据模型

class Dbrouter(object):

    def db_for_read(self, model, **hints):    #从数据库中读取
        """ reading SomeModel from otherdb """
        if model == MyModel : # 关键点1
            return 'teacher'  # 关键点2在setting中设置的key
        return None

    def db_for_write(self, model, **hints):    #写入数据库时
        """ writing SomeModel to otherdb """
        if model == MyModel :   # 关键点1
            return 'teacher'     # 关键点2,在setting中设置的key
        return None

接下来在setting中设置要指定其他数据库的配置:在DATABASE字典中添加如下配置

'teacher': {   #库的别名
        'ENGINE': 'django.db.backends.mysql',
        'HOST':'',
        'PORT':3306,
        'NAME': '',  #mysql数据库的名字
        'USER':'teacher',
        'PASSWORD':'',
    }

然而并没有结束,还需要在设置一项:(在setting中添加如下)

DATABASE_ROUTERS = ('app.dbrouters.Dbrouter',)

至此大功告成,其实还算简单~!






Read More

记录selenium + chrome的一些配置

chrome_options = webdriver.ChromeOptions()
        if visible == 0:
            chrome_options.add_argument('--headless')  # 无头浏览器
        # option.add_argument("--auto-open-devtools-for-tabs") #打开devtools
        # chrome_options.add_argument('--disable-extensions')  # 禁用拓展
        # chrome_options.add_argument('--profile-directory=Default')  # 自定义配置文件
        # chrome_options.add_argument('--incognito')  # 让浏览器直接以隐身模式启动
        # chrome_options.add_argument('--disable-plugins-discovery')
        # chrome_options.add_argument('--disable-logging')  # 禁用日志生成
        # chrome_options.add_argument('--disable-gpu')  # 关闭GPU加速
        # chrome_options.add_argument('--no-sandbox')  # 取消沙盒模式
        # chrome_options.add_argument('--single-process')  # 单进程运行
        chrome_options.add_argument('--disable-dev-shm-usage')  # docker部署时分配空间
        chrome_options.add_argument('user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"')
        chrome_options.add_argument('blink-settings=imagesEnabled=False')  # 无图片加载

        chrome_options.add_experimental_option('useAutomationExtension', False)  # 解决软件正在收到自动化检测
        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        chrome_options.add_argument("--disable-blink-features=AutomationControlled")  # 去掉了webdriver痕迹
        if proxies:
            chrome_options.add_argument(f'--proxy-server=socks5://47.241.106.251:1080')
            # proxyauth_plugin_path = create_proxyauth_extension(
            #     proxy_host=proxies.split("@")[1].split(':')[0],
            #     proxy_port=proxies.split(':')[-1],
            #     proxy_username=proxies.split("//")[1].split(':')[0],
            #     proxy_password=proxies.split(":")[2].split('@')[0]
            # )
            # chrome_options.add_extension(proxyauth_plugin_path)

        filepath = get_root_path() + self._get_driver_path()
        self.driver = webdriver.Chrome(executable_path=filepath, chrome_options=chrome_options)
        self.driver.set_page_load_timeout(30)  # 浏览器页面加载超时时间
        self.driver.set_script_timeout(10)
        self.driver.implicitly_wait(10)

        injected_javascript = '''
            // overwrite the `languages` property to use a custom getter
            Object.defineProperty(navigator, "languages", {
              get: function() {
                return ["zh-CN","zh","zh-TW","en-US","en"];
              }
            });
            // Overwrite the `plugins` property to use a custom getter.
            Object.defineProperty(navigator, 'plugins', {
              get: () => [1, 2, 3, 4, 5],
            });
            // Pass the Webdriver test
            Object.defineProperty(navigator, 'webdriver', {
              get: () => false,
            });
            // Pass the Chrome Test.
            // We can mock this in as much depth as we need for the test.
            window.navigator.chrome = {
              runtime: {},
              // etc.
            };
            // Pass the Permissions Test.
            const originalQuery = window.navigator.permissions.query;
            window.navigator.permissions.query = (parameters) => (
              parameters.name === 'notifications' ?
                Promise.resolve({ state: Notification.permission }) :
                originalQuery(parameters)
            );

            '''
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": injected_javascript
        })
        self.driver.maximize_window()