-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Templates support #113
Comments
👍 |
+1 |
+1 |
1 similar comment
+1 |
What benefit does this add besides you not needing to import the jinja2 package? |
In case anyone is confused, you can use jinja2 currently with sanic: from jinja2 import Template
from sanic import Sanic
from sanic.response import text
template = Template('Hello {{ name }}!')
app = Sanic()
@app.route("/")
async def test(request):
data = request.json
return text(template.render(name=data["name"]))
app.run(host="0.0.0.0", port=8000) Then, to see it working:
|
@r0fls That would actually be a great thing to include in examples |
@r0fls It works but i think use html function replace text maybe better from sanic import Sanic
from sanic.response import html
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('app', 'templates'))
app = Sanic(__name__)
@app.route('/')
async def test(request):
data = {'name': 'name'}
template = env.get_template('index.html')
html_content = template.render(name=data["name"])
return html(html_content)
app.run(host="0.0.0.0", port=8000) |
@istommao and at that point for data you could just use I think this shows you can get the full effects of the template engine jinja2 without it having to be baked into sanic core. |
@seemethere I agree with you! |
I'm going to close this at the end of the week, unless someone has a really good idea why we should bake jinja2 into sonic core. Jinja2 example has been added as of #193. |
@seemethere @r0fls as I mention in the starting message it's very often you need context processors. So it will be much more code than you show. Of course it may be implemented as independent library. So question is why I propose to include it into framework. The answer is because many flask or django apps include templates. So they need some agreement where (in which folder) to locate it e.t.c. It may be implemented with independent template library too. But if there will be many such libs, it will cause problem to use apps that relied on different of these. In the one sentence: I think built-in templates will increase popularity of sanic as it was with flask and django. |
we also put that in blueprint,for example: /home/webapp 1).main.py from sanic import Sanic
from my_blueprint import bp
app = Sanic(__name__)
app.blueprint(bp)
app.run(host='0.0.0.0', port=8000, debug=True) 2).my_blueprint.py # more my_blueprint.py
from sanic.response import json, text, html
from sanic import Blueprint
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('my_blueprint', 'templates'))
bp = Blueprint('my_blueprint')
@bp.route('/')
async def bp_root(request):
template = env.get_template('index.html')
content=template.render(title='Sanic',people='David')
return html(content) 3).index.html <!doctype html>
<title>{{ title }}</title>
<div class=page>
<h1>hello, {{ people }}</h1>
</div> |
I think this is not necessary. It's trivial to As of right now, Sanic is perfectly simple, has minimal usage of other dependencies, and in many ways it's more of a microframework than Flask itself. You can perfectly use Jinja with Sanic right now, as well as whatever templating engine you desire, it's all one import away. The community can also create a Jinja2 integration module for Sanic if they so desire (and it's really easy to do so). The same holds true for any other templating system or format they want to use in the future. The alternative to people who don't want to use Jinja is not as pleasing. Adding Jinja as a dependency will have everyone who intends to use Sanic as a backend tool only installing Jinja. It will also have people who want to use other templating engines be forced into having Jinja in their dependencies even though they will never use it. From a development perspective, adding Jinja would only serve to enlarge a beautifully small core. It's also more surface to maintain, and a detraction from the idea of a microframework in my opinion. Just look at the Frankenstein that is Flask nowadays -- crossed imports from This project has everything going for it, and a growing community, at a rate that is impressive for such a new project. Personally what drove me to this is the small footprint, in all regards. I'd much rather see the community build on top of this and keep the core small, rather than just request the devs to build everything into the core. Especially something like this which is simple and probably wouldn't take more than 100 LOC to build. My vote is for keeping Sanic sane, slim, pluggable, and performant. And build a vibrant community of modules around it 👍 |
Templating will not be built into Sanic core to keep the core as lean and performant as possible. Thanks for everyone's input on the subject! |
This is very easy to implement, and +1 on not including it in the Sanic core. here is a basic function to use Jinja2 with Sanic.
Index.html
Easy as py :-) . |
I think Jinja2 is slow, not that is noticeable but wrk recons otherwise . Enviroment: index.html = SimpleTemplate
Jinja2 Template
''' wrk -c 100 -t 2 --latency -v http://localhost:8085/ Bottle SimpleTemplate wrk -c 100 -t 2 --latency -v http://localhost:8085/ |
@Benozo why are you creating jinja environment each request?
|
@imbolc Yes your correct after i moved the Jinja2 Environment into global space all was fast again, thanks for pointing that out. 👍 .
Bottle Stpl
Jinja2
|
Any progress regarding render_template ..? |
I'm thinking about using a template engine with Sanic. The template : exemple_jinja2_02.html
The python file :
I tested with wrk -c 100 -t 2 --latency -v http://0.0.0.0:8000/ in mode asynchronous :
in mode synchronous :
|
I forgot, for the people who read this issue, there is an example with Jinja2 in async mode here : https://github.com/channelcat/sanic/pull/641/files |
@patic-fr Those examples were moved to the wiki: https://github.com/channelcat/sanic/wiki/Examples#jinja |
@patic-fr Reading template files in async is just a bad idea, this should be done once during program startup and then they should be kept cached in memory. Reading them every time you serve a request is just wasteful. Spawning a coroutine for rendering is another bad idea, rendering your templates is inherently CPU bound and will put pressure on your event loop no matter where they are, there is nothing to be gained by rendering them asynchronously. In short: Stop reading the file every time, don't render in a separate async function. |
actually there is, imagine you have some handlers in a single process, answering different time, e.g. simple json responses (which renders milliseconds) and heavy inherited templates (which renders about a second), with async rendering json responses will become faster. Whole the system probably will become somehow slowly, but smoothly |
@luizberti And when I checked the code of Jinja2, I didn't find a async method to read the file. So, why the async mode in the exemple above with Jinja give bad result in benchmark ? |
If you don't mind complicating your stack a little, you can push all your template rendering client side and save it in localstorage with something like react. Then handle all the "work" rendering the template there. Only ask sanic when you need actual json data. I mean, if you gotta go fast. That said, the class based views and models in django while slower, are really convenient. |
What do you think about integrate templates (jinja2?) into sanic core? I think the popularity of django and flask largely depends on their ability to write and distribute independent apps, which contains its own routes, handlers, templates and static files. Sanic has all of this except of templates.
If you agree, I suggest the next api:
The text was updated successfully, but these errors were encountered: