def test_custom_param(self): from diazo.wsgi import DiazoMiddleware from webob import Request def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) return [HTML] app = DiazoMiddleware(application, {}, testfile('custom_param.xml'), someparam='value1') request = Request.blank('/') response = request.get_response(app) self.assertTrue( '<div id="content">Content content</div>' in response.body) self.assertFalse( '<div id="content">Theme content</div>' in response.body) self.assertTrue('<title>Transformed</title>' in response.body) app = DiazoMiddleware(application, {}, testfile('custom_param.xml'), someparam='value2') request = Request.blank('/') response = request.get_response(app) self.assertFalse( '<div id="content">Content content</div>' in response.body) self.assertTrue( '<div id="content">Theme content</div>' in response.body) self.assertTrue('<title>Transformed</title>' in response.body)
def process_response(self, request, response): """ Transform the response with Diazo if transformable """ content = response if check_themes_enabled(request): theme = get_active_theme(request) if theme: rules_file = os.path.join(theme.theme_path(), 'rules.xml') if theme.id != self.theme_id or not os.path.exists( rules_file) or theme.debug: if not theme.builtin: if theme.rules: fp = open(rules_file, 'w') try: fp.write(theme.rules.serialize()) finally: fp.close() self.theme_id = theme.id self.diazo = DiazoMiddleware( app=self.app, global_conf=None, rules=rules_file, prefix=theme.theme_url(), doctype=DOCTYPE, ) compiled_theme = self.diazo.compile_theme() self.transform = etree.XSLT( compiled_theme, access_control=self.diazo.access_control) self.params = {} for key, value in self.diazo.environ_param_map.items(): if key in request.environ: if value in self.diazo.unquoted_params: self.params[value] = request.environ[key] else: self.params[value] = quote_param( request.environ[key]) try: if isinstance(response, etree._Element): response = HttpResponse() else: parser = etree.HTMLParser(remove_blank_text=True, remove_comments=True) content = etree.fromstring(response.content, parser) result = self.transform(content.decode('utf-8'), **self.params) response.content = XMLSerializer( result, doctype=DOCTYPE).serialize() except Exception, e: getLogger('django_diazo').error(e)
def test_esi(self): from diazo.wsgi import DiazoMiddleware from webob import Request def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) request = Request(environ) if request.path.endswith('/other.html'): return [HTML_ALTERNATIVE] else: return [HTML] app = DiazoMiddleware(application, {}, testfile('esi.xml'), filter_xpath=True) request = Request.blank('/') response = request.get_response(app) self.assertTrue('''<esi:include src="/other.html?;''' '''filter_xpath=//*[@id%20=%20'content']">''' '''</esi:include>''' in response.body) self.assertFalse( '<div id="content">Theme content</div>' in response.body) self.assertTrue('<title>Transformed</title>' in response.body) request = Request.blank( '''/other.html?;filter_xpath=//*[@id%20=%20'content']''') response = request.get_response(app) # Strip response body in this test due too # https://bugzilla.gnome.org/show_bug.cgi?id=652766 self.assertEqual('<div id="content">Alternative content</div>', response.body.strip())
def test_absolute_prefix(self): from diazo.wsgi import DiazoMiddleware from webob import Request def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) return [HTML] app = DiazoMiddleware( application, {}, _testfile('simple_transform.xml'), ) request = Request.blank('/') response = request.get_response(app) self.assertTrue( b'<div id="content">Content content</div>' in response.body, ) self.assertFalse( b'<div id="content">Theme content</div>' in response.body, ) self.assertTrue(b'<title>Transformed</title>' in response.body) self.assertTrue( b'<link rel="stylesheet" href="./theme.css" />' in response.body, ) app = DiazoMiddleware( application, {}, _testfile('simple_transform.xml'), prefix='/static', ) request = Request.blank('/') response = request.get_response(app) self.assertTrue( b'<div id="content">Content content</div>' in response.body, ) self.assertFalse( b'<div id="content">Theme content</div>' in response.body, ) self.assertTrue(b'<title>Transformed</title>' in response.body) self.assertTrue( b'<link rel="stylesheet" href="/static/theme.css" />' in response.body, )
def get_application(settings): try: settings = init(settings) app = Flask(__name__) app.wsgi_app = DiazoMiddleware(MyWSGIProxyApp(settings['content_url']),None,settings['rules_path'],prefix='/thememapper_static',read_network=True,update_content_length=True,debug=True) handlers = [ (r'/thememapper_static/(.*)', StaticFileHandler, {'path': settings['static_path']}), (r'/(.*)', FallbackHandler, {'fallback': WSGIContainer(app)}) ] return Application(handlers) except Exception as e: print e return False
def process_response(self, request, response): """ Transform the response with Diazo if transformable """ content = response if check_themes_enabled(request): theme = get_active_theme(request) if theme: rules_file = os.path.join(theme.theme_path(), 'rules.xml') if theme.id != self.theme_id or not os.path.exists(rules_file) or theme.debug: if not theme.builtin: if theme.rules: fp = open(rules_file, 'w') try: fp.write(theme.rules.serialize()) finally: fp.close() self.theme_id = theme.id self.diazo = DiazoMiddleware( app=self.app, global_conf=None, rules=rules_file, prefix=theme.theme_url(), doctype=DOCTYPE, ) compiled_theme = self.diazo.compile_theme() self.transform = etree.XSLT(compiled_theme, access_control=self.diazo.access_control) self.params = {} for key, value in self.diazo.environ_param_map.items(): if key in request.environ: if value in self.diazo.unquoted_params: self.params[value] = request.environ[key] else: self.params[value] = quote_param(request.environ[key]) try: if isinstance(response, etree._Element): response = HttpResponse() else: parser = etree.HTMLParser(remove_blank_text=True, remove_comments=True) content = etree.fromstring(response.content, parser) result = self.transform(content, **self.params) response.content = XMLSerializer(result, doctype=DOCTYPE).serialize() except Exception, e: getLogger('django_diazo').error(e)
def test_doctype_html5(self): from diazo.wsgi import DiazoMiddleware from webob import Request def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) return [HTML] app = DiazoMiddleware(application, {}, testfile('simple_transform.xml'), doctype="<!DOCTYPE html>") request = Request.blank('/') response = request.get_response(app) self.assertTrue(response.body.startswith("<!DOCTYPE html>\n<html"))
def test_with_theme(self): from diazo.wsgi import DiazoMiddleware from webob import Request def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) return [HTML] app = DiazoMiddleware(application, {}, testfile('explicit_theme.xml'), theme='file://' + testfile('theme.html')) request = Request.blank('/') response = request.get_response(app) self.assertTrue( '<div id="content">Content content</div>' in response.body) self.assertFalse( '<div id="content">Theme content</div>' in response.body) self.assertTrue('<title>Transformed</title>' in response.body)
def test_subrequest(self): from diazo.wsgi import DiazoMiddleware from webob import Request def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) request = Request(environ) if request.path.endswith('/other.html'): return [HTML_ALTERNATIVE] else: return [HTML] app = DiazoMiddleware(application, {}, _testfile('subrequest.xml')) request = Request.blank('/') response = request.get_response(app) self.assertTrue( b'<div id="content">Alternative content</div>' in response.body, ) self.assertFalse( b'<div id="content">Theme content</div>' in response.body, ) self.assertTrue(b'<title>Transformed</title>' in response.body)
Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "demosite.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demosite.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) from diazo.wsgi import DiazoMiddleware application = DiazoMiddleware(app=application, global_conf=None, rules='demosite/static/rules.xml', prefix='/static/example/')
DIAZO_DEFAULTS = dict( # app, global_conf={}, rules='%(THIS_DIR)s/default/rules.xml' % locals(), debug=settings.DEBUG, # theme=None, # prefix=None, # includemode='document', # debug=False, # read_network=False, # read_file=True, # update_content_length=False, # ignored_extensions=( # 'js', 'css', 'gif', 'jpg', 'jpeg', 'pdf', 'ps', 'doc', # 'png', 'ico', 'mov', 'mpg', 'mpeg', 'mp3', 'm4a', 'txt', # 'rtf', 'swf', 'wav', 'zip', 'wmv', 'ppt', 'gz', 'tgz', # 'jar', 'xls', 'bmp', 'tif', 'tga', 'hqx', 'avi', # ), # environ_param_map=None, # unquoted_params=None, # doctype=None, # content_type=None, # filter_xpath=False, ) config = DIAZO_DEFAULTS config.update(settings.DIAZO_CONFIG) application = DiazoMiddleware(get_wsgi_application(), **config)