A lot of bugfix.

This commit is contained in:
retoor 2025-01-28 00:42:24 +01:00
parent 66147497a8
commit 6a6ba976b3
4 changed files with 48 additions and 85 deletions

View File

@ -1,16 +0,0 @@
<html>
<head>
<title>Dreamii</title>
<style>{{highlight_styles}}</style>
</head>
<body>
<main>
<header>
<h1>Dreamii</h1>
</header>
<article>
{% block content %}{% endblock %}
</article>
</main>
</body>
</html>

View File

@ -1,55 +1,6 @@
# Hallo
{% extends "base.html" %}
{% block content %}
{% markdown %}
Welcome to Dreamii, the fastest web framework for Python to build sites with! Dynamic and static! Use Python as template language like PHP. Normally this requires CGI but Dreamii is way faster! Your application is async by default. Also, you can use async await in the py3 block tags.
## Syntax highligthing
### Python
```python ```python
print("Hi, i'm syntax highlighted python") import numpy as np
``` ```
## C
```c
#include <stdio.h>
int main() {
printf("Hi, i'm syntax highlighted c");
return 0;
}
```
{% endmarkdown %}
{% markdown %}# Python database{% endmarkdown %}
{% py3 %}
counter = dreamii.db["counter"].find_one(counter_name="main_counter")
if not counter:
counter = {"count":0,"counter_name":"main_counter"}
counter["count"] += 1
dreamii.db["counter"].upsert(counter,["counter_name"])
print(f"<p>This page had been visited {counter['count']} times.</p>")
{% endpy3 %}
{% markdown %}## Python sub process execution{% endmarkdown %}
{% py3 %}
print("<h3>List first file of directory using `ls`</h3>")
print("<pre>First file: ",system("ls",output=False).split("\n")[0],"</pre>")
print("<h3>Memory information</h3>")
print("<pre>",system("free -h",output=False),"</pre>")
print("<h3>Disk information</h3>")
print("<pre>",system("df -h",output=False),"</pre>")
print("<h3>Process information</h3>")
print("<pre>",system("ps aux",output=False,stderr=True),"</pre>")
{% endpy3 %}
{% endblock content %}

View File

@ -50,7 +50,7 @@ These are instructions for USING Dreamii, not to modify it.
python3 -m venv .venv python3 -m venv .venv
source .venv/bin/activate source .venv/bin/activate
pip install git+https://molodetz.nl/retoor/dreamii.git pip install git+https://molodetz.nl/retoor/dreamii.git
echo > "# My first dreamii site" > index.md echo "# My first dreamii site" > index.md
dreamii serve 7331 dreamii serve 7331
``` ```
@ -93,6 +93,7 @@ print(
"</pre>" "</pre>"
) )
{% endpy3 %} {% endpy3 %}
```
### Example database usage ### Example database usage
See here an example of a visitor counter on your website. This is all you have to do. It's a persistent database. No configuration required! For more information how to use the database, visit the [dataset documentation](https://dataset.readthedocs.io/en/latest/). See here an example of a visitor counter on your website. This is all you have to do. It's a persistent database. No configuration required! For more information how to use the database, visit the [dataset documentation](https://dataset.readthedocs.io/en/latest/).
@ -108,6 +109,7 @@ def increment(counter_name="default")
print(f"<p>This page had been visited {counter()} times.</p>") print(f"<p>This page had been visited {counter()} times.</p>")
{% endpy3 %} {% endpy3 %}
```
## Hidden files ## Hidden files
Files prefixed with `_` or `.` will not be displayed or rendered by Dreamii. This is for security and it is a convenient way to mark base templates. Files prefixed with `_` or `.` will not be displayed or rendered by Dreamii. This is for security and it is a convenient way to mark base templates.

View File

@ -28,9 +28,10 @@
from app.app import Application as BaseApplication, BaseView from app.app import Application as BaseApplication, BaseView
import pathlib import pathlib
from aiohttp import web from aiohttp import web
from dreamii.markdown import MarkdownExtension, MarkdownRenderer from dreamii.markdown import MarkdownExtension, MarkdownRenderer, render_markdown_sync
from dreamii.python import PythonExtension from dreamii.python import PythonExtension
import aiohttp_jinja2 import aiohttp_jinja2
import html
class TemplateView(BaseView): class TemplateView(BaseView):
@ -38,34 +39,59 @@ class TemplateView(BaseView):
path = pathlib.Path(self.request.app.template_path).joinpath(str(path).lstrip('/')) path = pathlib.Path(self.request.app.template_path).joinpath(str(path).lstrip('/'))
if path.exists() and path.suffix in ['.html', '.md']: if path.exists() and path.suffix in ['.html', '.md']:
return str(path) return str(path)
if path.joinpath('.html').exists(): elif path.joinpath('.md').exists():
return str(path.joinpath('.html'))
if path.joinpath('.md').exists():
return str(path.joinpath('.md')) return str(path.joinpath('.md'))
if path.is_dir(): elif path.joinpath('.html').exists():
return str(path.joinpath('.html'))
elif path.is_dir():
if path.joinpath('index.html').exists(): if path.joinpath('index.html').exists():
return str(path.joinpath('index.html')) return str(path.joinpath('index.html'))
if path.joinpath('index.md').exists(): elif path.joinpath('index.md').exists():
return str(path.joinpath('index.md')) return str(path.joinpath('index.md'))
return None return None
async def render_template(self, path): async def render_template(self, path):
context = {'request': self.request, 'post': await self.request.post() or None} context = {}
context['request'] = self.request
context['post'] = await self.request.post()
if not context['post']:
context['post'] = None
try: try:
context['json'] = await self.request.json() context['json'] = await self.request.json()
except: except:
context['json'] = None context['json'] = None
pass
response = None if str(path).endswith(".md"):
if str(path.endswith('.md')):
renderer = MarkdownRenderer(self.request.app, path) renderer = MarkdownRenderer(self.request.app, path)
response = web.Response(text=renderer.render())
else:
response = await super().render_template(path, self.request, context)
response.headers['Content-Type'] = 'text/html' content = pathlib.Path(path).read_text()
if pathlib.Path(self.template_path).joinpath("_base.html").exists():
return response markdown_default_page = "{% extends \"_base.html\" %}<html>{% block content %}<style>{{ highlight_styles }}</style>{% markdown %}"+content+"{% endmarkdown %}{% endblock %}</body></html>"
else:
markdown_default_page = "\n".join([
"<html>",
"<head>",
"<meta charset=\"utf-8\">",
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">",
"<title>" + html.escape(path.split("/")[-1].rstrip(".md")) +"</title>",
"<style>{{ highlight_styles }}</style>",
"</head>",
"<body>{% markdown %}"+content+"{% endmarkdown %}</body>",
"</html>"
])
with open(".temp.html", "w+") as f:
f.write(markdown_default_page)
content = aiohttp_jinja2.render_string(".temp.html",self.request,context=context)
pathlib.Path(".temp.html").unlink()
response = web.Response(text=content, content_type="text/html")
return response
return await super().render_template(path)
async def get(self): async def get(self):
path = await self.resolve_template(self.request.match_info['tail']) path = await self.resolve_template(self.request.match_info['tail'])