推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
zenxds
V2EX  ›  Python

django url 中嵌套参数如何进行在模板层 reverse

  •  
  •   zenxds ·
    zenxds · Jul 10, 2015 · 4577 views
    This topic created in 3988 days ago, the information mentioned may be changed or developed.

    先说下需求,我现在想实现动态页面静态化,但是又不想一开始就生成静态页,所以写了个代理view,访问静态页的时候判断对应的静态页面是否生成了静态页,如果生成了就直接返回静态页,没有就访问对应的动态页并生成静态页

    url层的设置大致是这样的

    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail')
    url(r'^(detail/(?P<question_id>[0-9]+)\.html)$', views.page_proxy, {
        'related_view': views.detail
    }, name='detail_page')
    

    对应的中间页view

    from django.core.files.storage import default_storage
    from django.core.files.base import ContentFile
    
    def page_proxy(request, path, *args, **kwargs):
    
        file_path = '%s/%s' % (settings.PAGES_ROOT, path)
    
        related_view = kwargs.pop('related_view')
        if not default_storage.exists(file_path):
            response = related_view(request, *args, **kwargs)
            default_storage.save(file_path, ContentFile(response.content))
            return response
        else:
            response_body = default_storage.open(file_path).read()
    
        return HttpResponse(response_body)
    

    这些都没啥问题,只是在模板层如果我想通过{% url 'detail_page' question.id %}来输出静态化的url时,因为第一个参数是path,而我又不想硬编码进去,有没有什么方案能解决这个问题的?

    lyhapple
        1
    lyhapple  
       Jul 10, 2015
    你这样的做法, 即使生成了静态页, 也不是纯粹意义的静态页, 还是需要django作一次转换,仍然达不到高效,为什么不做成页面一发布就生成一个静态页, 让Nginx来处理静态页面请求。
    haofly
        2
    haofly  
       Jul 10, 2015
    把PATH弄成一个全局变量?
    zenxds
        3
    zenxds  
    OP
       Jul 10, 2015
    @lyhapple nginx那一层后面也会做的,比如

    if (!-e $request_filename) {
    proxy_pass http://127.0.0.1:9000;
    }

    这里只是我拿来试验用的,我只是考虑,比如详情页静态化,一次全部生成太多页面太浪费
    hwind
        4
    hwind  
       Jul 10, 2015
    esponse = related_view(request, *args, **kwargs)--》你把path生成缓存的时候就传进去就可以了吧。没记错但话path的值就是正则表达式里question_id的值
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5569 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 73ms · UTC 03:34 · PVG 11:34 · LAX 20:34 · JFK 23:34
    ♥ Do have faith in what you're doing.