def set_cookie(self, name, value, path="/", domain=None, max_age=None, expires=None, secure=False, httponly=False, comment=None): """Set a cookie to be sent with a Set-Cookie header in the response :param name: String name of the cookie :param value: String value of the cookie :param max_age: datetime.timedelta int representing the time (in seconds) until the cookie expires :param path: String path to which the cookie applies :param domain: String domain to which the cookie applies :param secure: Boolean indicating whether the cookie is marked as secure :param httponly: Boolean indicating whether the cookie is marked as HTTP Only :param comment: String comment :param expires: datetime.datetime or datetime.timedelta indicating a time or interval from now when the cookie expires """ days = dict((i+1, name) for i, name in enumerate(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])) if value is None: value = '' max_age = 0 expires = timedelta(days=-1) if isinstance(expires, timedelta): expires = datetime.utcnow() + expires if expires is not None: expires_str = expires.strftime("%d %%s %Y %H:%M:%S GMT") expires_str = expires_str % days[expires.month] expires = expires_str if max_age is not None: if hasattr(max_age, "total_seconds"): max_age = int(max_age.total_seconds()) max_age = "%.0d" % max_age m = Morsel() def maybe_set(key, value): if value is not None and value is not False: m[key] = value m.set(name, value, value) maybe_set("path", path) maybe_set("domain", domain) maybe_set("comment", comment) maybe_set("expires", expires) maybe_set("max-age", max_age) maybe_set("secure", secure) maybe_set("httponly", httponly) self.headers.append("Set-Cookie", m.OutputString())