Python as a replacement for PHP inside HTML - python

Is it possible to use Python for web development in the same way that PHP is used?
In other words, can I add some python code among my HTML that gets run on the server and possibly adds to the HTML?
For example, some PHP code:
<p>Cheese:</p>
<ul>
<?php
$cheeses = ['brie', 'cheddar', 'death star'];
foreach ($cheeses as $c){
echo "<li>".$c."</li>";
}
?>
</ul>
<p>No more cheese :(</p>
Instead using python could be:
<p>Cheese:</p>
<ul>
<?py
cheeses = ['brie', 'cheddar', 'death star']
for c in cheeses:
print ("<li>" + c + "</li>")
?>
</ul>
<p>No more cheese :(</p>

Python alone is not a Web Development language. However you may use it with some Web Framework (like Django, Flask, etc.) in order to perform operations in templates using template tags and filters. For Django, refer Django's built-in tags document for the complete list of available operations.
Hence, your equivalent for loop in Django's template will be like:
{% for c in cheeses %}
<li> {{ c }} </li>
{% endfor %}
where you have to pass cheeses list with context object while rendering the template.

As most of the HTTP server are written in C /C++ they do not support python, ruby or php directly. There is special implementation for this specific languages. So your PHP web server will not support python unless python scripting is also implemented. However, you can use CGI (which is still supported) to implement your python scripting. But it is not recommended. Rather you should use existing python web farmeworks like Django, TurboGears, Zope, Bottle or Flasks

Python Web Framework is quite difference from PHP.
There are some template languages like Django's template language, Jinja2template engine. You use tags in HTML template, and even do some computing with django's "widthratio" tag. But it's really not recommended to do this, since template is basically string, python use template with some variables to render a final HTML to response to the browser.
So in python web framework, template is just used to manage the view display, you should separate the logic code with template.
If you want to use python in web development, you better think in python's way, There are many MVC frameworks in python, the best practice is write your python code in controller, leave the view rendering to template.

Related

What is the advantage of using a Django bootstrap module over linking to bootstrap files directly?

I see there are Django bootstrap modules (e.g. crispy_forms, django_bootstrap). I am trying to decide whether to use a module or link directly to bootstrap files in a base html file like the following:
<!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script
I have an understanding that with the modules I would do the styling in the code. With using bootstrap directly, I am thinking I have to style it in the template files.
I am trying to see reasons why I should be using a module. Also, with the bootstrap modules would I be able to use all bootstrap features?
Using modules for bootstrap is an awful idea. It creates tight coupling between ur app and the css framework. If you ever decide to move to a different framework you’ll need to refactor your forms in addition to the html templates. This also applies if you decide to upgrade from bootstrap3 to bootstrap4 in the future. Bootstrap4 has a ton of backward incompatible changes.
Create a form rendering template snippet and reuse that everywhere you need a form. If you want to change or upgrade cas later, all you have to do is update that one file.
The django-bootstrap modules provides a set of convenience template tags and integration with existing django features such as forms.
For instance, styling and rendering a django form in a template with bootstrap styling is as simple as
{% bootstrap_form form %}
As for upgrading to bootstrap4, django-boostrap4 is available.
Of course nothing is forcing you to use the django bootstrap module if you prefer to manually write your own bootstrap HTML tag class names and that might be better for your specific use case.

Extract translations from tornado template

I'm trying to use python-babel to extract translations from tornado templates.
I have tried some solutions, and none of them is perfect.
solution one
Use python as extractor:
# babel.cfg
[python: **/server/templates/**.html]
It works most of time, but won't work if there are some translations inside script blocks:
<script> var a = {{ _("won't be extracted") }} </script>
solution two
Just let tornado use jinja2 template engine, it works but not pretty.
solution three
Use tornado-babel, it is just an outdated library without python3 support.
Any suggestion?
Finally, I just use jinja2 template engine. Highly recommend tornado's team to use jinja2 template engine! Do not waste time any more.

Responsive web design with mobile detection interspersed for greater control

I have just finished building my first website with a mobile-first responsive design process in mind. The site looks and works great on mobile devices, but the desktop experience is quite lacking. There's no good way I can improve the desktop experience without compromising the mobile experience, and even then there are just some things I can't do using a pure client side approach.
I don't want to have to manage two separate websites (mobile, desktop). What I want to do is have mobile detection server side to have more control of when I load/display more data, etc.
I want to do something akin to:
// in view
...
if not request.mobile:
related_posts = post.get_related_posts()
...
// in template
...
{% if not request.mobile and related_posts %}
{{ related_post_stream(related_posts) }}
{% endif %}
...
Surprisingly, I don't see much online discussion about doing things this way. Most articles I've read either recommend pure (mobile-first) responsive design or a separate mobile website, although this seems like a decent idea. Is there a downside to doing this?
If you are using Django, there is django-mobile module which allows you to check the mobile usage in the template like this:
{% if flavour != "mobile" %}Desktop version{% endif %}
If you are not using Django, you can still analyze the source of that module and implement something similar for your website.

Does django have a user editable templating language that is secure like rails has liquid?

Does django have a user editable templating language that is secure like rails has liquid?
i.e. a end user can't hack template code to somehow output dangerous objects and hack the website.
If you're using the template language the right way: yes.
See Django template tags and filters:
http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#escape
http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#autoescape
http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#escapejs
An example:
{{ evil_userinput }}
This will print out the users input directly.
{{ evil_userinput|escape }}
This will escape all HTML entities an so it isn't possible to include dangerous code in your HTML page.
Liquid has originated from Django templating language, so the answer is yes. You can render user submitted templates and process them the way you want. Security however is something that developers should concern. Templating tools won't protect you if you want to let your users shoot you in the foot unless you sanitize and validate their input.
Here are a few good reads:
http://www.djangobook.com/en/2.0/chapter04/
http://www.djangobook.com/en/2.0/chapter09/
http://loopj.com/2009/05/23/a-django-developers-views-on-rails/

Rendering JSON objects using a Django template after an Ajax call

I've been trying to understand what's the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is:
formulate your Ajax call using some JavaScript library (e.g., jQuery), set up a URL pattern in Django that catches the call and passes it to a view function
in the Python view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or simplejson)
define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.
Now, what I still don't get is how are Django templates related to all of this? Apparently, we're not making use of the power of templates at all.
Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...
The only resource I found that goes in this direction is this snippet (769) but I haven't tried it yet.
Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.
Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?
Many thanks!
UPDATE: please use snippet 942 because it is an enhanced version of the one above! I found that the inheritance support works much better this way..
Hey thanks vikingosegundo!
I like using decorators too :-).
But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:
Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse:
........
<div id="results">
{% block results %}
{% for el in items %}
<li>{{el|capfirst}}</li>
{% endfor %}
{% endblock %}
</div><br />
........
By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this:
from django.template import loader
# downloaded from djangosnippets.com[942]
from my_project.snippets.template import render_block_to_string
def ajax_view(request):
# some random context
context = Context({'items': range(100)})
# passing the template_name + block_name + context
return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
return HttpResponse(return_str)
Here is how I use the same template for traditional rendering and Ajax-response rendering.
Template:
<div id="sortable">
{% include "admin/app/model/subtemplate.html" %}
</div>
Included template (aka: subtemplate):
<div id="results_listing">
{% if results %}
{% for c in results %}
.....
{% endfor %}
{% else %}
The Ajax-view:
#login_required
#render_to('admin/app/model/subtemplate.html')#annoying-decorator
def ajax_view(request):
.....
return {
"results":Model.objects.all(),
}
Of course you can use render_to_response. But I like those annoying decorators :D
There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.
When you are doing Ajax I don't think you have any use for templates.
Template is there so that you can generate dynamic HTML on the server side easily and hence it provides few programming hooks inside HTML.
In case of Ajax you are passing JSON data and you can format it as you want in Python.
and HTML/document elements will be generated on client side using the JSON by some JavaScript library e.g. jQuery on client side.
Maybe if you have a very specific case of replacing some inner HTML from server side HTML then maybe you can use templates but in that case why you would need JSON?
You can just query the HTML page via Ajax and change inner or outer or whatever HTML.
Templates are for the purpose of presentation. Responding with data in format X (JSON, JSONP, XML, YAML, *ml, etc.) is not presentation, so you don't need templates. Just serialize your data into format X and return it in an HttpResponse.
While templates are indeed just for presentation purposes, it shouldn't matter if you are doing it on the serverside or client side. It all comes down to separating the control logic that is performing an action, from the view logic that is just responsible for creating the markup. If your javascript control logic is having to handle how you are rendering or displaying the HTML, then you might be doing it wrong, but if you isolate that rendering logic to another object or function, and just passing it the data necessary for the render, then you should be fine; it mirrors how we separate our controllers, models and views on the server side.
Take a look at the github project: http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler
It compiles django templates into optimized javascript functions that will generate your presentation html with data that you pass it. The compiled functions are in pure javascript, so there are no dependencies on other libraries. Since the templates are compiled instead of being parsed at runtime, the strings and variables are all already placed into javascript strings that just need to be concatenated, so you get a huge speed increase compared to techniques that require you to do dom manipulation or script parsing to get the final presentation. Right now only the basic tags and filters are there, but should be enough for most things, and more tags will be added as people start making requests for them or start contributing to the project.
You can use jquery.load() or similar, generating the HTML on the server and loading it into the DOM with JavaScript. I think someone has called this AJAH.
Unfortunately, Django templates are designed to be executed server side only. There is at least one project to render Django templates using Javascript, but I haven't used it and so I don't know how fast, well supported or up to date it is. Other than this, you have to either use the Django templates on the server or generate dynamic elements on the client without using templates.

Categories