Created
November 24, 2014 22:55
-
-
Save daigotanaka/0975ef6b34b6405a284a to your computer and use it in GitHub Desktop.
rpy knit2.html example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import imp | |
| def rmarkdown_page(page_id, **kwargs): | |
| page = Page.objects.get(id=page_id) | |
| if not RPY2_INSTALLED: | |
| logger.info("rpy2 not found. I won't convert the raw text.") | |
| return page.body | |
| with open("/var/tmp/tmp.Rmd", "w") as f: | |
| f.write(page.body) | |
| ro.r("library('knitr');" | |
| "knit2html(input='/var/tmp/tmp.Rmd', output='/var/tmp/tmp.html');") | |
| with open("/var/tmp/tmp.html", "r") as f: | |
| content = f.read() | |
| content = re.sub(r"<[/]*body>", "", content) | |
| content = re.sub(r"<[/]*html>", "", content) | |
| content = content[content.find("</head>") + len("</head>"):] | |
| return content | |
| # Import only if rpy2 is available | |
| try: | |
| imp.find_module("rpy2") | |
| from rpy2 import robjects as ro | |
| RPY2_INSTALLED = True | |
| except ImportError: | |
| RPY2_INSTALLED = False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment