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>
3 Answers 3
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.
Comments
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
Comments
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.
Flask,Bottle,Django, etc.