Commit 56db8d6a authored by Joseph Walton-Rivers's avatar Joseph Walton-Rivers 🐦

write generation routine

parent 700e9bbf
Pipeline #1284 failed with stages
in 52 seconds
#! /usr/bin/env python3
import argparse
from j2static.main import generate
from j2static.webserver import serve
_options = {
'generate': lambda: print("generate"),
'generate': generate,
'serve': serve
}
......
#! /usr/bin/env python3
from jinja2 import Environment, PackageLoader, select_autoescape
import json
import os
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, select_autoescape
TEMPLATE_DIR = "templates"
DATA_DIR = "data"
SITE_DIR = "site"
ESCAPE = ('html', 'xml')
class TemplateEngine(object):
def __init__(self):
loader = FileSystemLoader(TEMPLATE_DIR)
self.env = Environment(
loader=loader,
autoescape=select_autoescape(ESCAPE)
)
def load_data(self, name):
"""Attempt to load a json encoded datafile"""
try:
template_name, ext = os.path.splitext(name)
path = os.path.join(DATA_DIR, template_name+".json")
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {}
def load_data_dir(self, data_dir):
"""Load all data files in a given directory"""
print("--data dir--")
for f in glob.iglob(data_dir + "*.json", recursive=True):
print(f)
def render(self, name):
template = self.env.get_template(name)
data = self.load_data(name)
return template.render(data)
env = Environment(
loader=PackageLoader('test', TEMPLATE_DIR),
autoescape=select_autoescape(['html', 'xml'])
)
def get_templates(self):
return self.env.list_templates(["html", "htm", "xml"])
def generate():
def render(name):
template = env.get_template(name)
return template.render()
engine = TemplateEngine()
for template in engine.get_templates():
gen_path = os.path.join(SITE_DIR, template)
with open(gen_path, 'w') as f:
template_data = engine.render(template)
f.write(template_data)
......@@ -8,25 +8,35 @@
import j2static.main
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
PORT = 8082
_jinja = j2static.main.TemplateEngine()
class TemplateHTTPServer(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
super().__init__(request, client_address, server)
print("constructor called")
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
data = j2static.main.render('index.html')
file_path = self.path
if file_path == "/":
file_path = "index.html"
_jinja.load_data_dir("data/")
data = _jinja.render(file_path)
self.wfile.write(data.encode())
def serve():
Handler = TemplateHTTPServer
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd = HTTPServer(('', PORT), Handler)
httpd.serve_forever()
httpd.close()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment