DJANGO_SETTINGS_MODULE 空值设置

本文介绍如何在不启动完整Django应用的情况下使用Django模板系统,包括配置环境变量DJANGO_SETTINGS_MODULE的方法,以及通过Python交互式解释器直接加载和渲染模板的具体步骤。

抛出了DJANGO_SETTINGS_MODULE is undefined,

 

1.

>>> from django . template import Template , Context
>>> from django . conf import settings
>>> settings . configure ()
>>> t = Template ( 'My name is {{ my_name }}.' )
>>> c = Context ({ 'my_name' : 'Daryl Spitzer' })
>>> t . render ( c )
参考:书http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django

 

2.

在系统环境变量中添加DJANGO_SETTINGS_MODULE变量,将其值设置为mysite.settings
添加PYTHONPATH:D:\\Program Files\\python25\\DLLs;F:\workforce\python
(F:\workforce\python为python project的工作目录,存放project, mysite是一个project目录,seetings为她的设置模块)
重新启动一个cmd,进入python。
import os import sys import json import logging import time from apscheduler.schedulers.background import BackgroundScheduler from multiprocessing import cpu_count, Pool BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, BASE_DIR) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "teachingReform.settings") import django django.setup() from data_platform_integration.tasks import fetch_and_save_data, init_global_token, load_config logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler("logs/sync.log"), logging.StreamHandler() ] ) logger = logging.getLogger(__name__) # def start_sync_process(table_info): # api_url = table_info.get('api_url') # model_class_name = table_info.get('model_class') # if not api_url or not model_class_name: # logger.warning(f"[-] 配置不完整,跳过表: {table_info}") # return # logger.info(f"[+] 开始处理表: {model_class_name}, API URL: {api_url}") # fetch_and_save_data(api_url, model_class_name, table_info) # logger.info(f"[+] 表 {model_class_name} 处理完成。") def start_sync_process(table_info): # 子进程中重新 setup Django 环境 import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "teachingReform.settings") django.setup() api_url = table_info.get('api_url') model_class_name = table_info.get('model_class') if not api_url or not model_class_name: logger.warning(f"[-] 配置不完整,跳过表: {table_info}") return logger.info(f"[+] 开始处理表: {model_class_name}, API URL: {api_url}") fetch_and_save_data(api_url, model_class_name, table_info) logger.info(f"[+] 表 {model_class_name} 处理完成。") def run_once_immediately(): config = load_config() logger.info("[+] 开始立即执行一次任务...") # 初始化全局 token cached_token = '' cached_expires_at = 0.0 init_global_token(cached_token, cached_expires_at) # 获取所有 enabled 表 tables = config.get('tables', []) filtered_tables = [t for t in tables if t.get('enabled', True)] # 按 last_page 降序排序,页数越大的排前面 sorted_tables = sorted( filtered_tables, key=lambda x: x.get("last_page", 1), reverse=True ) MAX_CONCURRENT_WORKERS = 3 # 固定最大并发数 max_workers = min(MAX_CONCURRENT_WORKERS, cpu_count(), len(sorted_tables)) logger.info(f"[+] 使用 {max_workers} 个工作进程来处理 {len(sorted_tables)} 个表。") with Pool(processes=max_workers) as pool: pool.map(start_sync_process, sorted_tables) # 使用排好序的列表 logger.info("[+] 立即执行任务已完成。") def main(): # 启动定时任务 config = load_config() scheduler = BackgroundScheduler() # 初始化全局 token cached_token = '' cached_expires_at = 0.0 init_global_token(cached_token, cached_expires_at) # 获取所有 enabled 表 tables = config.get('tables', []) filtered_tables = [t for t in tables if t.get('enabled', True)] # 按 last_page 降序排序,页数越大的排前面 sorted_tables = sorted( filtered_tables, key=lambda x: x.get("last_page", 1), reverse=True ) for table_info in sorted_tables: # ✅ 使用排序后的表列表 api_url = table_info.get('api_url') model_class = table_info.get('model_class') if not api_url or not model_class: logger.warning(f"[-] 配置不完整,跳过定时任务: {table_info}") continue job_id = f"sync_{model_class}" if scheduler.get_job(job_id): logger.warning(f"[!] 已存在任务 {job_id},跳过添加。") else: scheduler.add_job( fetch_and_save_data, 'interval', hours=48, args=[api_url, model_class, table_info], id=job_id, misfire_grace_time=30, coalesce=True, max_instances=1 ) logger.info(f"[+] 定时任务 {job_id} 已添加。") scheduler.start() logger.info("[+] 定时任务已启动,按 Ctrl+C 停止程序...") # 确保立即执行任务被调用 run_once_immediately() try: while True: time.sleep(1) except KeyboardInterrupt: scheduler.shutdown() logger.info("[-] 程序已终止。") if __name__ == "__main__": main()
最新发布
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值