def test_cache_expires_set_zero(): res = Response() res.cache_expires(seconds=0) eq_(res.cache_control.no_store, True) eq_(res.cache_control.no_cache, '*') eq_(res.cache_control.must_revalidate, True) eq_(res.cache_control.max_age, 0) eq_(res.cache_control.post_check, 0)
def serve_file(self, req): stream, ct, enc = self.get_stream_type_encoding(req) if stream: resp = Response(request=req, app_iter=stream, content_type=ct) if enc: resp.content_type_params['charset'] = enc expires = int(req.environ.get('toscawidgets.resources_expire', 0)) resp.cache_expires(expires) return resp else: return Response(status="404 Not Found")
def edit_file(self, req, filename): f = open(filename, 'rb') content = f.read() f.close() title = self.title or filename syntax = self.syntax_for_filename(filename) body = self.edit_template.substitute( content=content, filename=filename, title=title, req=req, edit_url=self.edit_url(req, filename), syntax=syntax) resp = Response(body=body) resp.cache_expires() return resp
def application(environ, start_response): request = Request(environ) data = [] db = psycopg2.connect(config.DB_GIS_CONNECTION_DSN) cursor = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cursor.execute('''SELECT * FROM trekarta_stats''') for row in cursor: del row['at'] data.append(row) cursor.close() response = Response(json=data) response.cache_expires(0) response.cache_control.private = True return response(environ, start_response)
def asset_view_factory(body, content_type, last_modified, http_cache=None): """ Returns an asset_view function that returns a SimpleResponse object""" response = Response() response.body = body response.content_type = content_type response.last_modified = last_modified response.cache_expires = http_cache def asset_view(context, request): return response return asset_view
def index(request): if request.path != "/": raise exc.HTTPNotFound() # Fetch data fml_endpoint = 'http://graph.facebook.com/search?q="so%20starving&type=post' fb_response = urllib.urlopen(fml_endpoint).read() fb_data = simplejson.loads(fb_response)["data"] # Render the content env = Environment(loader=FileSystemLoader('templates')) template = env.get_template("index.html") body = template.render(data=fb_data) # Set the body and the cache expiration response = Response(body=body) response.cache_expires(seconds=30 * 60) # Return it the response; we can now put a proper web cache in front of # our service. Even if we don't, every HTTP client with a cache becomes # a replicated node for this resource. How's that for horizontal scaling? return response
def view_dir(self, req, dir): dir = os.path.normpath(dir) show_parent = dir != self.base_dir children = [os.path.join(dir, name) for name in os.listdir(dir) if name not in self.skip_files] def edit_url(filename): return self.edit_url(req, filename) title = self.title or dir body = self.view_dir_template.substitute( req=req, dir=dir, show_parent=show_parent, title=title, basename=os.path.basename, dirname=os.path.dirname, isdir=os.path.isdir, children=children, edit_url=edit_url, ) resp = Response(body=body) resp.cache_expires() return resp
class HTTPResponse(object): """ Wrap WebOb's Response class. """ body = property(lambda self: self._res.body) text = property(lambda self: self._res.text) content_type = property(lambda self: self._res.content_type) status = property(lambda self: self._res.status) charset = property(lambda self: self._res.charset) headerlist = property(lambda self: self._res.headerlist) def __init__(self, body='', status=200, content_type='text/html', charset='UTF-8', headerlist=None): """ body -- str or bytes that specifies the body. Empty str by default. status -- int that specifies the status code. 200 by default. content_type -- str that specifies the content_type. 'text/html' by default. charset -- str that specifies the charset. 'UTF-8' by default. headerlist -- list of tuples that specifies the header values. None by default. """ self._res = Response(body, status, headerlist, content_type=content_type, charset=charset) def cache_expires(self, seconds): """ Set the response to expire in the specified seconds. seconds -- int that specifies the time for the response to expire in seconds. """ self._res.cache_expires(seconds) def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=False, httponly=False, comment=None, overwrite=False): """ Set cookie. key -- str that specifies the cookie name. value -- str that specifies the cookie value. None unsets cookie. Empty str by default. max_age -- int that specifies the 'Max-Age' attribute in seconds. None sets a session cookie. None by default. path -- str that specifies the 'Path' attribute. '/' by default. domain -- str that specifies the 'Domain' attribute. None does not set 'Domain' attribute. None by default. secure -- bool that specifies wheter it is a secure cookie. If it is True, 'secure' flag is set. If it is False, 'secure' flag is not set. False by default. httponly -- bool that specifies wheter it is an http only cookie. If it is True, 'HttpOnly' flag is set. If it is False, 'HttpOnly' flag is not set. False by default. comment -- str that specifies the 'Comment' attribute. None does not set 'Comment' attribute. None by default. overwrite -- bool that specifies if any existing cookie with the same key should be unset before setting this cookie. False by default. """ self._res.set_cookie(key, value, max_age, path, domain, secure, httponly, comment, overwrite=overwrite) def unset_cookie(self, key): """ Unset cookie with the specified key. key -- str that specifies the cookie name. """ self._res.unset_cookie(key, False) def delete_cookie(self, key, path='/', domain=None): """ Set cookie value to an empty str and 'Max-Age' to 0. key -- str that specifies the cookie name. path -- str that specifies the 'Path' attribute. '/' by default. domain -- str that specifies the 'Domain' attribute. None by default. """ self._res.delete_cookie(key, path, domain) def __call__(self, environ, start_response): """ WSGI application interface. environ and start_response -- objects provided by the WSGI server. """ return self._res(environ, start_response)
def application(environ, start_response): request = Request(environ) response = Response(content_type='text/plain', charset='utf-8') response.cache_expires(0) response.cache_control.private = True session = request.params.get('session', None) user = request.params.get('user', None) debug = request.params.get('debug', None) silent = request.params.get('silent', None) data = {} if session is not None: db = psycopg2.connect(config.DB_CONNECTION_DSN) cursor = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) session = unquote_plus(unquote_plus(session)) if user is not None: params = toDict(request.params.items()) params['session'] = unquote_plus(unquote_plus(session)) params['user'] = unquote_plus(unquote_plus(user)) # initialize optional parameters params.setdefault('elevation', None) params.setdefault('accuracy', None) params['track'] = int(float(params['track'])) params['speed'] = int(float(params['speed'])) cursor.execute('''INSERT INTO location(session, "user", lat, lon, speed, track, elevation, accuracy, ftime) VALUES (%(session)s, %(user)s, %(lat)s, %(lon)s, %(speed)s, %(track)s, %(elevation)s, %(accuracy)s, %(ftime)s)''', params) db.commit() if silent is not None: cursor.close() response.text = '' return response(environ, start_response) data['session-key'] = session data['users'] = [] cursor.execute('''SELECT location.id, "user", lat, lon, speed, track, elevation, accuracy, ftime FROM location INNER JOIN (SELECT MAX(id) AS id FROM location WHERE session = %s GROUP BY user) last ON location.id = last.id''', [session]) for user in cursor: # remove optional unset parameters if user['elevation'] == None: del user['elevation'] if user['accuracy'] == None: del user['accuracy'] data['users'].append(user) cursor.close() if session == 'test': ftime = time.time() distance = 50000 # 50 km plane = fakerotator('Ярославль', 57.61667, 39.85000, distance, ftime, 0) data['users'].append(plane) plane = fakerotator('Melbourne', -37.7833, 144.9667, distance, ftime, 720) data['users'].append(plane) plane = fakerotator('Montréal', 45.5081, -73.5550, distance, ftime, 1440) data['users'].append(plane) plane = fakerotator('横浜市', 35.444167, 139.638056, distance, ftime, 2160) data['users'].append(plane) plane = fakerotator('کندهار', 31.616667, 65.716667, distance, ftime, 2880) data['users'].append(plane) params = {'ensure_ascii': False} if debug is not None: params['indent'] = 4; response.text = json.dumps(data, **params) return response(environ, start_response)
def test_cache_expires_set_None(): res = Response() res.cache_expires(seconds=None, a=1) eq_(res.cache_control.a, 1)
def test_cache_expires_set_int(): res = Response() res.cache_expires(seconds=60) eq_(res.cache_control.max_age, 60)
def test_cache_expires_set_timedelta(): res = Response() from datetime import timedelta delta = timedelta(seconds=60) res.cache_expires(seconds=delta) eq_(res.cache_control.max_age, 60)
def test_cache_expires_set(): res = Response() res.cache_expires = True eq_(repr(res.cache_control), "<CacheControl 'max-age=0, must-revalidate, no-cache, no-store'>")