在 django 項目以外使用 django 項目的配置 settings 信息

簡介

最近在工做中使用 Djangodjango-rest-framework 來實現 API 開發功能,其中使用到 kafka 做爲broker。python

實現功能以下:mysql

  1. POST 方法將數據發送到服務器,經過kafka寫入指定的 topicsql

  2. 後臺單獨啓動進程產生 消費者broker 的數據寫入到 MySQLshell

此處的進程使用一個單獨的 python 文件實現,此時須要配置中使用 django orm 的配置信息,包括一些其餘的配置信息。django

方法一

其實這些信息也能夠使用包含上下文信息的工具:服務器

python manage.py shell

此處特別推薦神器 ipython 安裝以下:app

pip install ipython

若是在這個交互環境中,能夠享用一切 django 的配置,我通常經常使用於測試 djangomodel工具

凡是都有個可是,可是咱們還有 方法二。(都看到這裏了,就忍忍看完)測試

方法二

方法一 中很方便,可是使用起來只能在指定的交互環境中使用,不夠靈活。spa

【我想要實現的是】:我在任意位置的代碼、腳本中均可以很爽的使用 django 的配置

代碼以下:

import os,threading
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.extend([BASE_DIR,])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jrjidfa.settings")

import django

django.setup()
from idfacollect.kafka_utils import Utils as kfk
from idfacollect.kafka_utils import Config as cfg


class Consumer(threading.Thread):
    def run(self):
        kfk.consume_to_mysql(host=cfg.KFK_HOST,
                             port=cfg.KFK_PORT,
                             topic=cfg.KFK_TOPIC_IDFA_DEVICE_STARTUP,
                             group_id=cfg.KFK_GP_TO_MYSQL)

        kfk.consume_to_mysql(host=cfg.KFK_HOST,
                             port=cfg.KFK_PORT,
                             topic=cfg.KFK_TOPIC_IDFA_APP_CLICK,
                             group_id=cfg.KFK_GP_TO_MYSQL)


if __name__ == '__main__':
    try:
        for i in range(5): # create 5 thread  exectue Consumer
            t = Consumer()
            t.start()
    except Exception as e:
        print e

說明一下:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 這個是想要使用的 `django` 工程的根目錄;


sys.path.extend([BASE_DIR,])
# 將項目根目錄加入到 python 搜索的 path 中


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jrjidfa.settings")
# 設置環境變量中的 DJANGO_SETTINGS_MODULE 設置爲 django 配置


import django
django.setup()
# 啓動 django 配置、註冊 app 等等初始化操做

總結:接下來就能夠愉快的使用了,看上面代碼就知道真的很愉快。

以上です!ありがとうございました

相關文章
相關標籤/搜索