rakkapy/books/views.py

62 lines
2.0 KiB
Python

from django.shortcuts import render
from . import models
from django.template import loader
import functools
def rerender(funky):
@functools.wraps(funky)
def wrap(req,*args,**kwargs):
with open('main/utils/navs') as b:
navs=parsecat(b,4)
namednavs=[{'id':blah[0], 'link':blah[1], 'text':blah[2], 'align':int(blah[3])} for blah in navs['']]
out=funky(*args,**kwargs)
temp=loader.get_template('main/nav.html')
out['nav']=temp.render({"navs":namednavs},None)
return render(req, 'main/temp.html', out)
return wrap
def parsecat(file,n):
if not isinstance(file,str):
# Assume open handle
stuff=file.read()
else:
with open(f'main/pages/{file}') as b:
stuff=b.read()
cats=stuff.split('\n\n')
out={}
head=''
out['']=[]
for cat in cats:
if ':' in cat[:cat.index('\n')]:
# We have a category name
head,cat=cat.split('\n',1)
head=head[:-1]
out[head]=[]
else: head=''
for line in cat.split('\n'):
lin=line.split(',',n-1)
pad=n-len(lin)
lin.extend(['']*pad)
out[head].append(lin)
if out['']==[]: del(out[''])
return out
@rerender
def index():
books=models.Book.objects.all()
#Make table I guess, for now just get data up there
contents='<br/>\n'.join([f'<a href="/books/{book.url}">{book}</a> - {book.last_updated}' for book in books])
return {'title':'Booklist','content':contents+"<br/>\nYou should be able to read books now.",'date':'2021/10/24'}
@rerender
def book(bookurl):
book=models.Book.objects.filter(url=bookurl)[0]
chapters=models.Chapter.objects.filter(book=book).order_by('added')
return {'title':book.title,'content':'<a href="/books/">Top</a><br/>\n'+'<br/>\n'.join([f'<a href="/books/{book.url}/{chap.number}">{chap}</a> - {chap.added}' for chap in chapters]),'date':book.last_updated}
@rerender
def chapter(bookurl,chapnum):
book=models.Book.objects.filter(url=bookurl)[0]
chapter=models.Chapter.objects.filter(book=book,number=int(chapnum))[0]
return {'title':chapter,'content':'<p>Navigation buttons will come later...</p>\n'+chapter.contents,'date':chapter.added}