Beispiel #1
0
def render_cached_feed(events, format_type='atom'):
    last_modif_time = events[0].time_taken
    web.debug(last_modif_time)
    #http conditional get
    if not config.http_conditional_get or web.modified(last_modif_time):
        web.lastmodified(last_modif_time)
        web.header("Content-Type", "application/atom+xml")
        web.debug(len(events))
        print render.events_atom_feed(config, last_modif_time, events)
Beispiel #2
0
def cache_valid(cache_time):
    last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '')
    last_time = web.net.parsehttpdate(last_time_str)
    now = datetime.now()
    if last_time and last_time + timedelta(seconds=cache_time) > now:
        web.notmodified()
        return True
    else:
        web.lastmodified(now)
        return False
Beispiel #3
0
 def wrapped_f(*args):
     last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '')
     last_time = web.net.parsehttpdate(last_time_str)
     now = datetime.datetime.now()
     if last_time and last_time + datetime.timedelta(seconds = seconds) > now:
         web.notmodified()
     else:
         web.lastmodified(now)
         web.header('Cache-Control', 'max-age='+str(seconds))
     yield f(*args)
Beispiel #4
0
 def wrapped_f(*args):
     last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '')
     last_time = web.net.parsehttpdate(last_time_str)
     now = datetime.datetime.now()
     if last_time and\
             last_time + datetime.timedelta(seconds = seconds) > now:
         web.notmodified()
     else:
         web.lastmodified(now)
         web.header('Cache-Control', 'max-age='+str(seconds))
     yield f(*args)
Beispiel #5
0
    def cache_valid(path):
        return False
        last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '')
        last_time = web.net.parsehttpdate(last_time_str)

        if last_time:
            mtime = os.path.getmtime(path)
            if last_time < mtime:
                web.notmodified()
                return True
        web.lastmodified(datetime.datetime.now())
        return False
Beispiel #6
0
        def GET(self):
            i = web.input(v=None)
            v = doc.md5()
            if v != i.v:
                raise web.seeother(web.changequery(v=v))

            if web.modified(etag=v):
                oneyear = 365 * 24 * 3600
                web.header("Content-Type", content_type)
                web.header("Cache-Control", "Public, max-age=%d" % oneyear)
                web.lastmodified(doc.last_modified)
                web.expires(oneyear)
                return delegate.RawText(doc.get_text())
Beispiel #7
0
        def GET(self):
            i = web.input(v=None)
            v = doc.md5()
            if v != i.v:
                raise web.seeother(web.changequery(v=v))

            if web.modified(etag=v):
                oneyear = 365 * 24 * 3600
                web.header("Content-Type", content_type)
                web.header("Cache-Control", "Public, max-age=%d" % oneyear)
                web.lastmodified(doc.last_modified)
                web.expires(oneyear)
                return delegate.RawText(doc.get_text())
Beispiel #8
0
    def cache_valid(self):
        #return False
        last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '')
        last_time = web.net.parsehttpdate(last_time_str)

        if last_time:
            nowtick = int(time.time())
            tick = time.mktime(last_time.timetuple())
            nexttick = tick+(300-tick % 300)
            #print "weiwei"+datetime.datetime.fromtimestamp(nexttick).strftime("%m-%d %H %M %S")
            if nexttick > nowtick:
                web.notmodified()
                return True
        web.lastmodified(datetime.datetime.now())
        return False
Beispiel #9
0
def downloadStaticMediaFile(file_key, base_dir, mode="str"):
    path = normalize_path(file_key.rstrip("/"), base_dir)
    try:
        f = open(path, 'rb')
    except IOError:
        web.notfound()
        raise StopIteration

    ctype = guess_content_type(path)
    web.header("Content-type", ctype)
    fs = os.fstat(f.fileno())
    web.header("Content-Length", str(fs[6]))
    web.lastmodified(datetime.datetime.fromtimestamp(fs.st_mtime))
    if mode == "str":
        return f.read()
    elif mode == "file":  
        return f
Beispiel #10
0
 def GET(self, category, key, value, size):
     i = web.input(default="true")
     key = key.lower()
     
     d = _query(category, key, value)
     if d:
         if key == 'id':
             web.lastmodified(d.created)
             web.header('Cache-Control', 'public')
             web.expires(100 * 365 * 24 * 3600) # this image is not going to expire in next 100 years.
             
         web.header('Content-Type', 'image/jpeg')
         filename = _cache.get_image(d.id, size)
         if filename:
             return serve_file(filename)
     elif config.default_image and i.default.lower() != "false" and not i.default.startswith('http://'):
         return serve_file(config.default_image)
     elif i.default.startswith('http://'):
         raise web.seeother(i.default)
     else:
         raise web.notfound("")
Beispiel #11
0
    def _post(self, f):
        now = datetime.now()
        web.lastmodified(now)
        web.httpdate(now)

        web.header('Cache-Control', 'no-cache,private')
        web.header('Pragma', 'no-cache')

        if isinstance(f, web.HTTPError) is True:
            raise f

        if self.download.type == self.DOWNLOAD_TYPE_NORMAL:
            # nomal process
            if self.__template__.media == "json":
                try:
                    _r = simplejson.dumps(self.view)
                    return _r
                except:
                    raise web.internalerror()

            if f is True:
                path = '%s/%s.%s' % (
                    self.__template__.dir.replace("controller", ""),
                    self.__template__.file.replace("controller", ""),
                    self.__template__.media)

            try:
                _r = self.__mako_render(path,
                                 title='akiyoshi', view=self.view)
                return _r
            except:
                return exceptions.html_error_template().render(full=True)

        elif self.download.type == self.DOWNLOAD_TYPE_FILE:
            # file download
            if self.download.file is None or os.path.isfile(self.download.file) is False:
                self.log.error('Could not find files to download. - path=%s' % self.download.file)
                raise web.internalerror()

            web.header('Content-Type', 'Content-type: application/octet-stream', True)
            fp = open(self.download.file , "rb")
            try:
                _r = fp.read()
            finally:
                fp.close()

            if self.download.once is True and os.path.isfile(self.download.file) is True:
                os.unlink(self.download.file)
            return _r

        elif self.download.type == self.DOWNLOAD_TYPE_STREAM:
            # file stream download!!
            if self.download.stream is None:
                self.log.error("Data stream has not been set.")
                raise web.internalerror("Execution errors")

            return self.download.stream

        else:
            # Illegal Error.
            self.log.error('Was specified assuming no output type. - type=%d' % self.download.type)
            raise web.internalerror()
Beispiel #12
0
    def _post(self, f):
        """<comment-ja>
        HTTP Method別処理を実行した後の処理を行います。
          1. HTTP Responseコード 4xx or 5xx についての処理
          2. テンプレート処理
          3. HTTP Headerをセット
        @param f: 実行結果
        @type f: bool or web.HTTPError
        @return: HTTP Response
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        try:  # default view set.
            self.view.me = self.me
            if self.is_standalone() is True:
                self.view.standalone = self.input.standalone
        except AttributeError:
            pass

        # Content-Type
        # TODO
        # "Resource interpreted as script but transferred with MIME type text/plain."
        # if self.__template__.media == 'part':
        #    web.header('Content-Type', 'text/html; charset=utf-8', True)
        # elif self.__template__.media == 'input':
        #    web.header('Content-Type', 'text/html; charset=utf-8', True)
        # elif self.__template__.media == 'html':
        #    web.header('Content-Type', 'text/html; charset=utf-8', True)
        # elif self.__template__.media == 'json':
        #    web.header('Content-Type', 'application/json; charset=utf-8', True)
        # elif self.__template__.media == 'xml':`
        #    web.header('Content-Type', 'text/xml; charset=utf-8', True)
        # elif self.__template__.media == 'gif':
        #    web.header('Content-Type', 'Content-type: image/gif', True)
        # elif self.__template__.media == 'png':
        #    web.header('Content-Type', 'Content-type: image/png', True)
        # elif self.__template__.media == 'jpg':
        #    web.header('Content-Type', 'Content-type: image/jpeg', True)
        # elif self.__template__.media == 'jpeg':
        #    web.header('Content-Type', 'Content-type: image/jpeg', True)
        # elif self.__template__.media == 'ico':
        #    web.header('Content-Type', 'Content-type: image/x-icon', True)
        # elif self.__template__.media == 'css':
        #    web.header('Content-Type', 'Content-type: text/css; charset=utf-8', True)
        # elif self.__template__.media == 'js':
        #    web.header('Content-Type', 'Content-type: text/javascript; charset=utf-8', True)
        # elif self.__template__.media == 'jar':
        #    web.header('Content-Type', 'Content-type: application/java-archiver', True)
        # else:
        #    web.header('Content-Type', 'text/plain; charset=utf-8', True)

        # HTTP Header - No Cache
        now = datetime.now()
        web.lastmodified(now)
        web.httpdate(now)
        # TODO
        # web.expire(0)
        # web.header('Expires', web.httpdate(datetime(1970,1,1)))
        # web.header('Last-Modified',  web.httpdate(datetime(1970,1,1)))
        # web.header('ETag', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
        web.header("Cache-Control", "no-cache,private")
        web.header("Pragma", "no-cache")

        ##
        if self.download.type == OUTPUT_TYPE_NORMAL:  # Nomal
            if self.me is None:
                self.view.USER_DATE_FORMAT = DEFAULT_LANGS[self.languages[0]]["DATE_FORMAT"]
            else:
                self.view.USER_DATE_FORMAT = DEFAULT_LANGS[self.me.languages]["DATE_FORMAT"]

            if isinstance(f, web.HTTPError) is True:
                self.logger.info("HTTP Response - %s Headers-->%s" % (f.__class__.__name__, web.ctx.headers))
                raise f

            if f is True:
                path = "%s/%s.%s" % (self.__template__.dir, self.__template__.file, self.__template__.media)
            else:
                # if self.__template__.media in ERROR_MEDIA:
                #    path = 'error/error.%s' % self.__template__.media
                # else:
                #    path = 'error/error.%s' % DEFAULT_MEDIA
                self.logger.info('"gadget" execution error - %s' % str(self.__class__))
                raise web.internalerror("Execution errors")

            self.logger.debug("lang=%s %s : template=%s" % (",".join(self.languages), str(self), path))

            try:
                _r = mako_render(self._, path, title=self._("Karesansui"), view=self.view)
                return _r
            except:
                if web.wsgi._is_dev_mode() is True and os.environ.has_key("FCGI") is False:
                    return exceptions.html_error_template().render(full=True)
                else:
                    self.logger.error('"mako render" execution error - path=%s' % path)
                    self.logger_trace.error(traceback.format_exc())
                    raise web.internalerror("Execution errors")

        elif self.download.type == OUTPUT_TYPE_FILE:  # file download
            if self.download.file is None or os.path.isfile(self.download.file) is False:
                self.logger.error("Could not find files to download. - path=%s" % self.download.file)
                return web.internalerror()
            web.header("Content-Type", "Content-type: image/png", True)
            fp = open(self.download.file, "rb")
            try:
                _r = fp.read()
            finally:
                fp.close()

            if self.download.once is True and os.path.isfile(self.download.file) is True:
                os.unlink(self.download.file)

            return _r

        elif self.download.type == OUTPUT_TYPE_STREAM:  # io stream download
            if self.download.stream is None:
                self.logger.error("Data stream has not been set.")
            return self.download.stream

        else:
            self.logger.error("Was specified assuming no output type. - type=%d" % self.download.type)
            raise web.internalerror()
Beispiel #13
0
    def _post(self, f):
        """<comment-ja>
        HTTP Method別処理を実行した後の処理を行います。
          1. HTTP Responseコード 4xx or 5xx についての処理
          2. テンプレート処理
          3. HTTP Headerをセット
        @param f: 実行結果
        @type f: bool or web.HTTPError
        @return: HTTP Response
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        try:  # default view set.
            self.view.me = self.me
            if self.is_standalone() is True:
                self.view.standalone = self.input.standalone
        except AttributeError:
            pass

        # Content-Type
        # TODO
        # "Resource interpreted as script but transferred with MIME type text/plain."
        #if self.__template__.media == 'part':
        #    web.header('Content-Type', 'text/html; charset=utf-8', True)
        #elif self.__template__.media == 'input':
        #    web.header('Content-Type', 'text/html; charset=utf-8', True)
        #elif self.__template__.media == 'html':
        #    web.header('Content-Type', 'text/html; charset=utf-8', True)
        #elif self.__template__.media == 'json':
        #    web.header('Content-Type', 'application/json; charset=utf-8', True)
        #elif self.__template__.media == 'xml':`
        #    web.header('Content-Type', 'text/xml; charset=utf-8', True)
        #elif self.__template__.media == 'gif':
        #    web.header('Content-Type', 'Content-type: image/gif', True)
        #elif self.__template__.media == 'png':
        #    web.header('Content-Type', 'Content-type: image/png', True)
        #elif self.__template__.media == 'jpg':
        #    web.header('Content-Type', 'Content-type: image/jpeg', True)
        #elif self.__template__.media == 'jpeg':
        #    web.header('Content-Type', 'Content-type: image/jpeg', True)
        #elif self.__template__.media == 'ico':
        #    web.header('Content-Type', 'Content-type: image/x-icon', True)
        #elif self.__template__.media == 'css':
        #    web.header('Content-Type', 'Content-type: text/css; charset=utf-8', True)
        #elif self.__template__.media == 'js':
        #    web.header('Content-Type', 'Content-type: text/javascript; charset=utf-8', True)
        #elif self.__template__.media == 'jar':
        #    web.header('Content-Type', 'Content-type: application/java-archiver', True)
        #else:
        #    web.header('Content-Type', 'text/plain; charset=utf-8', True)

        # HTTP Header - No Cache
        now = datetime.now()
        web.lastmodified(now)
        web.httpdate(now)
        # TODO
        #web.expire(0)
        #web.header('Expires', web.httpdate(datetime(1970,1,1)))
        #web.header('Last-Modified',  web.httpdate(datetime(1970,1,1)))
        #web.header('ETag', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
        web.header('Cache-Control', 'no-cache,private')
        web.header('Pragma', 'no-cache')

        ##
        if self.download.type == OUTPUT_TYPE_NORMAL:  # Nomal
            if self.me is None:
                self.view.USER_DATE_FORMAT = DEFAULT_LANGS[
                    self.languages[0]]['DATE_FORMAT']
            else:
                self.view.USER_DATE_FORMAT = DEFAULT_LANGS[
                    self.me.languages]['DATE_FORMAT']

            if isinstance(f, web.HTTPError) is True:
                self.logger.info('HTTP Response - %s Headers-->%s' %
                                 (f.__class__.__name__, web.ctx.headers))
                raise f

            if f is True:
                path = '%s/%s.%s' % (
                    self.__template__.dir,
                    self.__template__.file,
                    self.__template__.media,
                )
            else:
                #if self.__template__.media in ERROR_MEDIA:
                #    path = 'error/error.%s' % self.__template__.media
                #else:
                #    path = 'error/error.%s' % DEFAULT_MEDIA
                self.logger.info('"gadget" execution error - %s' %
                                 str(self.__class__))
                raise web.internalerror("Execution errors")

            self.logger.debug('lang=%s %s : template=%s' \
                              % (','.join(self.languages), str(self), path))

            try:
                _r = mako_render(self._,
                                 path,
                                 title=self._('Karesansui'),
                                 view=self.view)
                return _r
            except:
                if web.wsgi._is_dev_mode() is True and os.environ.has_key(
                        'FCGI') is False:
                    return exceptions.html_error_template().render(full=True)
                else:
                    self.logger.error(
                        '"mako render" execution error - path=%s' % path)
                    self.logger_trace.error(traceback.format_exc())
                    raise web.internalerror("Execution errors")

        elif self.download.type == OUTPUT_TYPE_FILE:  # file download
            if self.download.file is None or os.path.isfile(
                    self.download.file) is False:
                self.logger.error(
                    'Could not find files to download. - path=%s' %
                    self.download.file)
                return web.internalerror()
            web.header('Content-Type', 'Content-type: image/png', True)
            fp = open(self.download.file, "rb")
            try:
                _r = fp.read()
            finally:
                fp.close()

            if self.download.once is True and os.path.isfile(
                    self.download.file) is True:
                os.unlink(self.download.file)

            return _r

        elif self.download.type == OUTPUT_TYPE_STREAM:  # io stream download
            if self.download.stream is None:
                self.logger.error("Data stream has not been set.")
            return self.download.stream

        else:
            self.logger.error(
                'Was specified assuming no output type. - type=%d' %
                self.download.type)
            raise web.internalerror()