HTTP helpers (bottle_utils.http
)¶
This module provides decorators for working with HTTP headers and other aspects of HTTP.
Module contents¶
-
bottle_utils.http.
format_ts
(seconds=None)[source]¶ Given a timestamp in seconds since UNIX epoch, return a string representation suitable for use in HTTP headers according to RFC.
If
seconds
is omitted, the time is asumed to be current time.
-
bottle_utils.http.
iter_read_range
(fd, offset, length, chunksize=1048576)[source]¶ Return an iterator that allows reading files in chunks. The
fd
should be a file-like object that has aread()
method. Theoffset
value sets the start offset of the read. If thefd
object does not supportseek()
, the file will be simply read up until offset, and the read data discarded.length
argument specifies the amount of data to read. The read is not done in one go, but in chunks. The size of a chunk is specified usingchunksize
.This function is similar to
bottle._file_iter_range
but does not fail on missingseek()
attribute (e.g.,StringIO
objects).
-
bottle_utils.http.
no_cache
(func)[source]¶ Disable caching on a handler. The decorated handler will have
Cache-Control
header set toprivate, no-cache
.This is useful for responses that contain data that cannot be reused.
Simply deocrate a handler with it:
@app.get('/foo') @no_cache def not_cached(): return 'sensitive data'
-
bottle_utils.http.
send_file
(content, filename, size=None, timestamp=None)[source]¶ Convert file data into an HTTP response.
This method is used when the file data does not exist on disk, such as when it is dynamically generated.
Because the file does not exist on disk, the basic metadata which is usually read from the file itself must be supplied as arguments. The
filename
argument is the supposed filename of the file data. It is only used to set the Content-Type header, and you may safely pass in just the extension with leading period.The
size
argument is the payload size in bytes. For streaming files, this can be particularly important as the ranges are calculated baed on content length. Ifsize
is omitted, then support for ranges is not advertise and ranges are never returned.timestamp
is expected to be in seconds since UNIX epoch, and is used to calculate Last-Modified HTTP headers, as well as handle If-Modified-Since header. If omitted, current time is used, and If-Modified-Since is never checked.Note
The returned response is a completely new response object. Modifying the reponse object in the current request context is not going to affect the object returned by this function. You should modify the object returned by this function instead.
Example:
def some_handler(): import StringIO f = StringIO.StringIO('foo') return send_file(f, 'file.txt', 3, 1293281312)
The code is partly based on
bottle.static_file
, with the main difference being the use of file-like objects instead of files on disk.