V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2015-07-10 13:22:01 +08:00 · 3310 次点击
    这是一个创建于 3184 天前的主题,其中的信息可能已经有所发展或是发生改变。

    先说下需求,我现在想实现动态页面静态化,但是又不想一开始就生成静态页,所以写了个代理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,而我又不想硬编码进去,有没有什么方案能解决这个问题的?

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

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

    这里只是我拿来试验用的,我只是考虑,比如详情页静态化,一次全部生成太多页面太浪费
    hwind
        4
    hwind  
       2015-07-10 15:21:52 +08:00
    esponse = related_view(request, *args, **kwargs)--》你把path生成缓存的时候就传进去就可以了吧。没记错但话path的值就是正则表达式里question_id的值
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   948 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:51 · PVG 05:51 · LAX 14:51 · JFK 17:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.