`
crayster
  • 浏览: 50506 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

django上的静态文件

阅读更多
django里使用静态文件,貌似有这么几种办法:

1. 在setting.py里面:
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__), '../static').replace('\\','/'),
)

把静态文件所在目录设到STATICFILES_DIRS里。
静态文件就可以通过 /static/xxx这样的url访问了。不过缺点是STATIC_URL不可以设为空(一定要有个前缀)。所以像robots.txt这样的一定要放在根目录的文件就不行了(http://example.com/robots.txt)。

2. 将静态页面设置为模板,通过direct_to_template函数直接显示
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
    (r'^robots\.txt$', direct_to_template, {'template': 'robots\.txt', 'mimetype': 'text/plain'}),
)

direct_to_template的说明:https://docs.djangoproject.com/en/1.2/ref/generic-views/

3. 如果静态页面非常简单,也可以通过lambda表达式(匿名函数)直接写在urlpatterns里
urlpatterns = patterns('',
    (r'^robots\.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain"))
)

lambda后面的r,指view的参数request。
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics