Add HTTP headers to static pages

122 views
Skip to first unread message

Dan Shechter

unread,
Nov 4, 2012, 6:31:24 AM11/4/12
to we...@googlegroups.com
Hi All,

I am running web.py application using the built in web server.

Is there a way to manually add HTTP headers to /static pages? I want to control the cache for HTTPS static objects.

Thanks,
Dan

Pietro Bertera

unread,
Nov 4, 2012, 10:38:36 AM11/4/12
to we...@googlegroups.com
Hi,

2012/11/4 Dan Shechter <dan...@gmail.com>:
> Is there a way to manually add HTTP headers to /static pages? I want to
> control the cache for HTTPS static objects.

Here you can see a dummy example that add Content-type header to static files:

import web
import mimetypes

def mime_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

class Public:
def GET(self):
try:
file_name = web.ctx.path.split('/')[-1]
web.header('Content-type', mime_type(file_name))
return open('./' + web.ctx.path, 'rb').read()
except IOError:
raise web.notfound()

myApp = web.application(mapping=(), fvars=globals())
myApp.add_mapping("/.+", "Public")

myApp.run()


--
Bertera Pietro
http://www.bertera.it

Dan Shechter

unread,
Nov 5, 2012, 5:22:33 AM11/5/12
to we...@googlegroups.com
Hi Pietro,

Thanks for your reply.

I think that your answer is a bit over my head. I'll try to explain your answer in my own words, and please correct me if I am wrong:
  • There is no built in way to add HTTP headers to the built in feature of servicing static pages of the /static folder
  • The solution is to write my one code to serve static objects, and in that code I can do whatever I choose to do.
  • The example you wrote is an example of how to correctly and manually serve static objects, not using the automatic /static folder way.

Thanks,
Dan.

Pietro Bertera

unread,
Nov 5, 2012, 6:16:29 AM11/5/12
to we...@googlegroups.com
Hi Dan,

2012/11/5 Dan Shechter <dan...@gmail.com>:

> There is no built in way to add HTTP headers to the built in feature of
> servicing static pages of the /static folder

I'm not a web.py guru, but looking the code seems that in order to add
custom headers on /static/ files you need to rewrite the do_GET()
method in WSGIHandler class (in httpserver.py).

> The solution is to write my one code to serve static objects, and in that
> code I can do whatever I choose to do.

IMHO I think this is the convenient way.

> The example you wrote is an example of how to correctly and manually serve
> static objects, not using the automatic /static folder way.

Yes, true

Best regards,

Dan Shechter

unread,
Nov 5, 2012, 6:19:08 AM11/5/12
to we...@googlegroups.com
Thanks :)
Reply all
Reply to author
Forward
0 new messages