def main(): template = """ <!doctype html> <html> <head></head> <body> <div> Etag: {% if etag %} {{ etag }} {% else %} None? {% endif %} </div> </body> </html>""" # etag = request.if_none_match etag = request.headers.get('If-None-Match') # request.headers.get('If-Modified-Since') if etag: resp = Response(render_template_string(template, etag=etag)) resp.status_code = 304 resp.set_etag(etag) # resp.cache_control.public = True # resp.cache_control.max_age = 31536000 # 365 days resp.expires = time.strptime('Tue, 15 Nov 2020 12:45:26', "%a, %d %b %Y %H:%M:%S") resp.last_modified = time.strptime('Tue, 15 Nov 1994 12:45:26', "%a, %d %b %Y %H:%M:%S") for k, v in data.iteritems(): if k == etag: browser = Browser(request, etag) data[etag] = browser.__dict__ else: etag = hashlib.sha1(request.remote_addr).hexdigest() resp = Response(render_template_string(template, etag=etag)) resp.status_code = 200 resp.set_etag(etag) # resp.cache_control.public = True # resp.cache_control.max_age = 63072000 resp.expires = time.strptime('Tue, 15 Nov 2020 12:45:26', "%a, %d %b %Y %H:%M:%S") resp.last_modified = time.strptime('Tue, 15 Nov 1994 12:45:26', "%a, %d %b %Y %H:%M:%S") browser = Browser(request) data[etag] = browser.__dict__ with open('browsers.json', 'w') as browsers: json.dump(data, browsers, indent=4) browsers.close() return resp
def badge(title, value, ext='svg'): """Generate a badge response.""" if ext == 'svg': generator = generate_badge_svg mimetype = 'image/svg+xml' elif ext == 'png': generator = generate_badge_png mimetype = 'image/png' badge_title_mapping = \ current_app.config['FORMATTER_BADGES_TITLE_MAPPING'].get( title, title) response = Response(generator(badge_title_mapping, value), mimetype=mimetype) # Generate Etag from badge title and value. hashable_badge = "{0}.{1}".format(badge_title_mapping, value).encode('utf-8') response.set_etag(hashlib.sha1(hashable_badge).hexdigest()) # Add headers to prevent caching. response.headers["Pragma"] = "no-cache" response.cache_control.no_cache = True response.cache_control.max_age = \ current_app.config['FORMATTER_BADGES_MAX_CACHE_AGE'] response.last_modified = dt.utcnow() extra = timedelta( seconds=current_app.config['FORMATTER_BADGES_MAX_CACHE_AGE']) response.expires = response.last_modified + extra return response.make_conditional(request)
def prepare_response(resp: Response): last_modified = datetime.now() # ( # g.timestamp[:PYTHON_TIMESTAMP_LEN] + "Z", # "%Y-%m-%dT%H:%M:%S.%fZ" # ) resp.last_modified = last_modified resp.expires = datetime.now() + timedelta(minutes=1, seconds=30) resp.cache_control.max_age = 30 resp.cache_control.public = True resp.cache_control.s_maxage = 90 resp.cache_control.must_revalidate = True resp.headers['PHE-Server-Loc'] = SERVER_LOCATION try: minified = [ minifier.get_minified(item.decode(), 'html') for item in resp.response ] data = str.join("", minified).encode() resp.set_data(data) except UnicodeDecodeError as e: app.logger.warning(e) # g.log_handler.flush() return resp
def __call__(self, body=None, header=None, last_modified=None, valid_seconds=15, etag=None): rsp = None if body is None: rsp = Response(json.dumps(self.m), self.c, header, mimetype="application/json") else: rsp = Response(json.dumps(body), self.c, header, mimetype="application/json") if last_modified is not None: then = datetime.utcnow() + timedelta(seconds=valid_seconds) rsp.expires = then rsp.last_modified = last_modified if etag is not None: rsp.set_etag(etag, False) return rsp
def response_font_zip_from_cache(request_font_path): if not request.args.get('hash'): raise ValueError() if request.if_modified_since: if_modified_since = \ request.if_modified_since.replace(tzinfo=timezone.utc).timestamp() if (request.if_modified_since and int(app.config['server_updated_date']) <= int(if_modified_since)): response = Response() response.status_code = 304 else: font_file_path = \ japont.search_font_path(request_font_path, app.config['font_list']) hash_key = '{}_{}'.format(font_file_path, request.args.get('hash').lower()) if not cache.has(hash_key): raise IOError() response = send_file(BytesIO(cache.get(hash_key)), mimetype='application/zip', as_attachment=True, attachment_filename='font.zip') response.cache_control.must_revalidate = True response.cache_control.no_cache = True response.cache_control.max_age = 0 response.expires = time() response.last_modified = app.config['server_updated_date'] return response
def api_badge(): CHARWIDTH = 7 try: room_jid = request.args["address"] except KeyError: return abort(400, "missing address argument") room_info = db.session.query( model.MUC, model.PubliclyListedMUC, ).join(model.PubliclyListedMUC, ).filter( model.MUC.address == room_jid, ).one_or_none() if room_info is None or room_info[1] is None: return abort(404, "no such room") muc, public_info = room_info # check if the room may have changed since the last request last_update = None if muc.last_seen is not None: last_update = muc.last_seen if muc.moving_average_last_update is not None: if last_update is None: last_update = muc.moving_average_last_update else: last_update = min(muc.moving_average_last_update, last_update) # round up to the next second; this is not perfect, but good enough. last_update = last_update.replace(microsecond=0) + timedelta(seconds=1) if (request.if_modified_since is not None and last_update <= request.if_modified_since): return "", 304 label = " {} ".format(public_info.name or muc.address) nusers = " {:.0f} ".format(muc.nusers_moving_average) labelwidth = len(label) * CHARWIDTH countwidth = len(nusers) * CHARWIDTH width = labelwidth + countwidth rendered = render_template( "badge.svg", width=width, label=label, labelwidth=labelwidth, number=nusers, countwidth=countwidth, ) response = Response(rendered, mimetype="image/svg+xml") response.last_modified = last_update if last_update is not None: response.expires = last_update + CACHE_BADGE_TTL response.headers["Content-Security-Policy"] = \ "frame-ancestors 'none'; default-src 'none'; style-src 'unsafe-inline'" return response
def get_badge(): projects, job_names = get_args(request.args) if (not projects and not job_names) or not projects: return Response("Invaild Request") url = genarate_zuul_url(projects, job_names) success = check_the_result(url, projects, job_names) response = Response(RESP_TYPE[success], mimetype='image/svg+xml') response.cache_control.no_cache = True response.cache_control.no_store = True response.cache_control.private = True response.cache_control.max_age = 0 response.expires = datetime.datetime(1984, 1, 1) response.headers['X-Content-Type-Options'] = 'nosniff' response.add_etag() return response
def __send_file(musicFile, cachetimout, stream=True): headers = Headers() headers.add('Content-Disposition', 'attachment', filename=musicFile.filename) headers.add('Content-Transfer-Encoding', 'binary') status = 200 size = getsize(musicFile.path) begin = 0 end = size - 1 if request.headers.has_key("Range") and rangerequest: status = 206 headers.add('Accept-Ranges', 'bytes') ranges = findall(r"\d+", request.headers["Range"]) begin = int(ranges[0]) if len(ranges) > 1: end = int(ranges[1]) headers.add( 'Content-Range', 'bytes %s-%s/%s' % (str(begin), str(end), str(end - begin))) headers.add('Content-Length', str((end - begin) + 1)) #Add mimetype mimetypes = {u"mp3": "audio/mpeg", u"ogg": "audio/ogg"} if stream == True: mimetype = mimetypes[musicFile.filetype] else: mimetype = "application/octet-stream" response = Response(file(musicFile.path), status=status, mimetype=mimetype, headers=headers, direct_passthrough=True) #enable browser file caching with etags response.cache_control.public = True response.cache_control.max_age = int(cachetimout) response.last_modified = int(musicFile.changetime) response.expires = int(time() + int(cachetimout)) response.set_etag('%s%s' % (musicFile.id, musicFile.changetime)) response.make_conditional(request) return response
def avatar_v1(address): try: address = aioxmpp.JID.fromstr(address) except (ValueError, TypeError): return abort(400, "bad address") metadata = db.session.query( model.Avatar.hash_, model.Avatar.last_updated, model.Avatar.mime_type, ).filter(model.Avatar.address == address, ).one_or_none() if metadata is None: return abort(404, "no avatar stored") hash_, last_updated, mime_type = metadata response = Response(mimetype=mime_type) response.status_code = 500 response.add_etag(hash_) response.last_modified = last_updated response.expires = datetime.utcnow() + CACHE_AVATAR_TTL response.headers["Content-Security-Policy"] = \ "frame-ancestors 'none'; default-src 'none'; style-src 'unsafe-inline'" if (request.if_none_match.contains(hash_) or (request.if_modified_since is not None and last_updated <= request.if_modified_since)): response.status_code = 304 return response if request.method == "HEAD": # do not fetch the data, only its size length, = db.session.query(sqlalchemy.func.length( model.Avatar.data), ).filter( model.Avatar.address == address).one() response.status_code = 200 response.content_length = length return response data, = db.session.query( model.Avatar.data, ).filter(model.Avatar.address == address).one() response.data = data response.status_code = 200 return response
def js(): names = [ 'head.js', 'ut.js', 'notice.js', 'redo.js', 'stream.js', 'super_resolution.js', 'load_image.js', 'plus.js', 'detail.js', 'tag.js', 'thumbnail.js', 'fade.js', 'base.js', ] def gen(): for name in names: yield datetime.fromtimestamp(os.path.getmtime(os.path.join( current_app.root_path, current_app.template_folder, name ))) mtime = max(gen()) if has_timestamp() and not expired_request(mtime): return Response(status=304) content = '\n'.join(render_template(name) for name in names) resp = Response( content, mimetype='text/javascript', ) resp.content_md5 = calcmd5(content.encode('utf-8')) resp.last_modified = mtime if has_timestamp(): if cache_timeout() is not None: resp.cache_control.max_age = cache_timeout() resp.expires = int(time() + cache_timeout()) return resp
def __send_file( musicFile , cachetimout, stream=True): headers = Headers() headers.add('Content-Disposition', 'attachment',filename=musicFile.filename) headers.add('Content-Transfer-Encoding','binary') status = 200 size = getsize(musicFile.path) begin=0; end=size-1; if request.headers.has_key("Range") and rangerequest: status = 206 headers.add('Accept-Ranges','bytes') ranges=findall(r"\d+", request.headers["Range"]) begin = int( ranges[0] ) if len(ranges)>1: end=int( ranges[1] ) headers.add('Content-Range','bytes %s-%s/%s' % (str(begin),str(end),str(end-begin)) ) headers.add('Content-Length',str((end-begin)+1)) #Add mimetype mimetypes = {u"mp3":"audio/mpeg",u"ogg":"audio/ogg"} if stream==True: mimetype = mimetypes[musicFile.filetype] else: mimetype = "application/octet-stream" response = Response( file(musicFile.path), status=status, mimetype=mimetype, headers=headers, direct_passthrough=True) #enable browser file caching with etags response.cache_control.public = True response.cache_control.max_age = int(cachetimout) response.last_modified = int(musicFile.changetime) response.expires=int( time() + int(cachetimout) ) response.set_etag('%s%s' % ( musicFile.id,musicFile.changetime )) response.make_conditional(request) return response
def style(): root = os.path.join(app.static_folder, 'scss') sources = scss_sources(root) def gen(): for filename, _ in sources: yield datetime.fromtimestamp(os.path.getmtime(os.path.join( root, filename ))) mtime = max(gen()) if has_timestamp() and not expired_request(mtime): return Response(status=304) c = scss.Scss( scss_vars={}, scss_opts={ 'compress': True, 'debug_info': True, 'load_paths': [root] } ) c._scss_files = OrderedDict(sources) content = c.compile() resp = Response( content, mimetype='text/css', ) resp.content_md5 = calcmd5(content.encode('utf-8')) resp.last_modified = mtime if has_timestamp(): if cache_timeout() is not None: resp.cache_control.max_age = cache_timeout() resp.expires = int(time() + cache_timeout()) return resp
def thumbnail(md5): try: if ( has_timestamp() and not expired_request(core.thumbnail_mtime_bi_md5(md5)) ): return Response(status=304) except: pass width = int(request.args['width']) content = core.thumbnail_bi_md5(md5, width) resp = Response(content, mimetype='image/' + img.kind(data=content)) resp.content_md5 = calcmd5(content) resp.last_modified = core.thumbnail_mtime_bi_md5(md5) if has_timestamp(): cache_timeout = core.thumbnail_cache_timeout_bi_md5(md5) if cache_timeout is not None: resp.cache_control.max_age = cache_timeout resp.expires = int(time() + cache_timeout) return resp