"""An HTML file writer and reader.""" import webbrowser import motionless API_KEY = 'AIzaSyAjPH6t6Y2OnPDNHesGFvTaVzaaFWj_WCE' class HTMLFile: """An HTML file writer""" def __init__(self, path=''): """Instanciate the object. Parameters ---------- path : str path to the html file to write. If present it will be overwritten. """ self.path = path self._write_header() def _write_header(self): """Create the file and add the html header to it.""" with open(self.path, 'w') as file: file.write('\n') file.write('\n') file.write('\n') def _add_line_to_file(self, line, ending='\n'): """Add a line to the file.""" with open(self.path, 'a') as file: file.write(line + ending) def add_title(self, title, small=False): """Add a title to the file. Parameters ---------- title : str the title small : bool whether the title should be small or not """ h = 'h2' if small else 'h1' self._add_line_to_file('<{}>{}'.format(h, title, h)) def add_center_map(self, **kwargs): """Add a google map to the file. Parameters ---------- kwargs : dict or kwargs any argument to be passed to motionless.DecoratedMap """ cmap = motionless.CenterMap(**kwargs, key=API_KEY) base = 'no image' self._add_line_to_file(base.format(cmap.generate_url())) def display_html(self): """Opens the file in a browser""" webbrowser.get().open_new_tab(self.path) def end_file(self): """Add the html file ending strings""" self._add_line_to_file('') self._add_line_to_file('') @property def n_lines(self): with open(self.path, 'r') as file: n = len(file.readlines()) return n if __name__ == '__main__': file = HTMLFile('template.html') file.add_title('A map') # file.add_paragraph('This is the Great Pyramid of Giza:') ## this does not work yet file.add_center_map(lat=48.858278, lon=2.294489, maptype='satellite') file.end_file() file.display_html()