使用 django-piston,如何在响应中写出 HTTP 标头?

发布于 2024-08-26 15:03:53 字数 75 浏览 6 评论 0原文

如何在 django-piston 调用的响应中包含 HTTP 标头,例如 Cache-Control 或 Last-Modified?

How can I include an HTTP header, such as Cache-Control or Last-Modified, in the response to a django-piston call?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋叶绚丽 2024-09-02 15:03:53

您可以按照 在 Django 文档中的 urlconf 指南中指定每个视图缓存。就我而言,我的 Piston API 位于单独的模块中,并且更喜欢使用 Varnish 而不是内置的 Django 缓存框架,因此我在我的 api/urls.py (我的主要< code>urls.pyincludes) 来设置我想要的缓存控制标头:

from django.views.decorators.cache import cache_control

cached_resource = cache_control(public=True, maxage=30, s_maxage=300)

urlpatterns = patterns('',
   url(r'^myresource/
, cached_resource(Resource(MyHandler))),
)

You can wrap it in your urls.py following the procedure in the specifying per view cache in urlconf guide in the Django documentation. In my case I had my Piston API in a separate module and prefer to use Varnish instead of the built-in Django caching framework so I used this approach in my api/urls.py (which my main urls.py includes) to set the cache control headers I wanted:

from django.views.decorators.cache import cache_control

cached_resource = cache_control(public=True, maxage=30, s_maxage=300)

urlpatterns = patterns('',
   url(r'^myresource/
, cached_resource(Resource(MyHandler))),
)
情仇皆在手 2024-09-02 15:03:53

不确定 django-piston,但在 django 中你可以这样:

from django.http import HttpResponse
response = HttpResponse('My content')
response['MyHttpHeader'] = 'MyHeaderValue'

所以,在你可以访问响应的地方这样做。如果您使用的是第三方应用程序,中间件通常是执行此操作的最佳场所。您的中间件可能类似于:

def process_response(self, request, response):
    response['MyHttpHeader'] = 'MyHeaderValue'
    return response

Not sure about django-piston, but in django you can just go:

from django.http import HttpResponse
response = HttpResponse('My content')
response['MyHttpHeader'] = 'MyHeaderValue'

So, do that where you can get access to the response. Middleware is often the perfect place to do this if you are using a 3rd party application. Your middleware could look something like:

def process_response(self, request, response):
    response['MyHttpHeader'] = 'MyHeaderValue'
    return response
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文