2012-02-10 2 views
1

Django 프로젝트에서 사용하지 않는 템플릿을 감지하는 방법이 있습니까?Django : 사용하지 않는 템플릿 감지

Django 1.3 이전 버전에서는 this one과 같은 간단한 문자열 일치 기능을 사용할 수있었습니다. 하지만 1.3 이후에는 오버라이드하지 않으면 (예 : DetailView) 자동으로 template_name을 생성하는 일반 클래스 기반보기가 있습니다.

타사 모듈 템플릿을 덮어 쓰면 해당 템플릿이 사용자의 뷰에서 직접적으로 사용되지 않습니다.

아마도 모든 URL 정의를 크롤링하고, 해당보기를로드하고 template_name을 가져와 수행 할 수 있습니까?

get_template(any_code_you_like()).render(context) 

그래서 이전에도 1.3 장고 사용되지 않는 템플릿을 장고 : 당신은 항상이 같은 코드를 작성할 수 있기 때문에

+0

당신이, 당신은 내가 –

+0

:-) 의견을 정리 것 중 하나 (당신이 오버 라이딩 잘하지 않는 한) 그 뷰를 사용하지 않는 클래스 기반 뷰에서 생성 된 템플릿을 사용하지 않는 걱정이 있다면 @ ArgsKwargs 나는 당신의 의견을 정말로 이해하지 못한다. 어쨌든, 나는이 문제에 대한 일반적인 접근 방식을 생각하고 있었다. 이는 레거시 프로젝트에 특히 유용합니다. –

+0

Django는 사용하지 않는 템플릿을로드하지 않습니다. 그들 모두에 대해 걱정할 필요가 없습니다. – ramusus

답변

0

그것은, 심지어 일반적인 전망의 부재, 특정 사용하지 템플릿을 감지 할 수는 없습니다 연결된 응용 프로그램은 템플릿 사용에 대한 일종의 규율을 존중하는 프로젝트에서만 작동했을 수 있습니다. 충분하지 않을 것

(. 예를 들어, 항상 get_templaterender_to_response 같은 기능 템플릿 인수로 문자열 리터럴을 가진) 모든 뷰를로드 중 하나

def my_view(request): 
    if request.user.is_authenticated(): 
     return render(request, 'template1.html') 
    else: 
     return render(request, 'template2.html') 
: 뷰는 서로 다른 상황에서 서로 다른 템플릿을 사용할 수 있습니다

물론 템플릿은보기에서 전혀 사용할 수 없지만 시스템의 다른 부분 (예 : 전자 메일 메시지)에서는 사용할 수 없습니다.

+0

고맙습니다. 나는 이미 그것을 기대했지만, 내가 생각지 않았을 가능성이 있는지를 알지 못했다. :) –

1

원숭이 패치/장식 get_template 대신이 작업을 수행 할 수 있다면 궁금합니다. 나는 당신이 할 수 있다고 생각하지만 모든 템플릿로드 함수를로드해야합니다 (나는 아래 예제에서 두 가지가 있음).

loader.get_template을 넘어서서 내가 알아 차 렸을 때 wrapt을 사용했지만 트릭을 잘하는 것 같습니다. 물론, 찌르다가 50000km 떨어진 곳에 두십시오.

이제, 다음과 같이하면 unittests와 nosetests로 운전하게됩니다. 파이썬 코드를 사용하면 대부분의 템플릿을 얻을 수 있어야합니다 (get_template-type 함수를 놓친 적이 없다고 가정).

settings.py

이것은 "두뇌"get_template & 협력을 패치하는 것입니다 있다.

import wrapt 
import django.template.loader 
import django.template.engine 

def wrapper(wrapped, instance, args, kwargs): 

    #concatenate the args vector into a string. 
    # print "\n\n\n\n%s\nI am a wrapper \nusage:%s\n%s\n\n\n\n\n" % ("*"*80, usage, "*"*80) 
    try: 
     return wrapped(*args, **kwargs) 
    finally: 
     usage = ",".join([unicode(arg) for arg in args if arg]) 
     track_usage(usage) 

#you have to wrap whatever is loading templates... 
#imported django module + class/method/function path of what needs to be 
#wrapped within that module. comment those 2 lines out and you are back to 
#normal 


wrapt.wrap_function_wrapper(django.template.loader, 'get_template', wrapper) 
wrapt.wrap_function_wrapper(django.template.engine, 'Engine.find_template', wrapper) 

포장에 대한 자세한 내용은 safely-applying-monkey-patches-in-python을 참조하십시오. 실제로는 문서를 이해하는 것보다 사용하기 쉽고, 데코레이터는 내 머리를 아프게합니다.

또한 실제로드를 수행하는 django 함수를 추적하기 위해 일부 템플릿 이름의 의도를 코드와 템플릿에서 잘못 입력하고 단위 테스트를 실행 한 후 누락 된 템플릿 예외에 대한 스택 트레이스를 조사했습니다.

이것은 내 잘못 작성된 기능으로 세트에 추가하여 json 출력에 넣습니다.

def track_usage(usage): 
    fnp_usage = "./usage.json" 

    try: 
     with open(fnp_usage, "r") as fi: 
      data = fi.read() 
      #read the set of used templates from the json file 
      j_data = json.loads(data) 
      s_used_file = set(j_data.get("li_used")) 

    except (IOError,),e: 
      s_used_file = set() 
      j_data = dict() 

    s_used_file.add(usage) 
    #convert the set back to a list for json compatibility 
    j_data["li_used"] = list(s_used_file) 

    with open(fnp_usage, "w") as fo: 
     json.dump(j_data, fo) 

과 OUPUT (스크립트와 포맷하기) :

import sys 
import json 
fnp_usage = sys.argv[1] 


with open(fnp_usage, "r") as fi: 
    data = fi.read() 
    #read the set of used templates from the json file 
    j_data = json.loads(data) 
    li_used_file = j_data.get("li_used") 
    li_used_file.sort() 

    print "\n\nused templates:" 
    for t in li_used_file: 
     print(t) 

을 위의 두 기능을 포장에서, 잡은 확장 보인다 %가 포함 똑바로 get_templates뿐만 아니라 목록 클래스 기반 뷰에 사용 된 템플릿. 심지어 파일 시스템에도 없지만 사용자 정의 로더가로드되는 동적으로 생성 된 템플릿을 발견했습니다.

used templates: 
bootstrap/display_form.html 
bootstrap/errors.html 
bootstrap/field.html 
bootstrap/layout/baseinput.html 
bootstrap/layout/checkboxselectmultiple.html 
bootstrap/layout/field_errors.html 
bootstrap/layout/field_errors_block.html 
bootstrap/layout/help_text.html 
bootstrap/layout/help_text_and_errors.html 
bootstrap/layout/radioselect.html 
bootstrap/whole_uni_form.html 
django_tables2/table.html 
dynamic_template:db:testdb:name:pssecurity/directive.PrimaryDetails.json 
uni_form/layout/div.html 
uni_form/layout/fieldset.html 
websec/__base.html 
websec/__full12.html 
websec/__l_right_sidebar.html 
websec/bootstrapped_home.html 
websec/changedb.html 
websec/login.html 
websec/requirejs_config.html 
websec/topnav.html 
websec/user_msg.html