20

I am trying to use Python instead of PHP (just for educational purposes). I am testing my webpages on XAMPP and I already added python and cgi to configs. I managed to make a very basic webpage with this code

#!/Python/python

print("Content-Type: text/plain;charset=utf-8")
print()

print("Hello World!")

Though, this is it. I can't find any info on how exactly do I serve webpages with Python 3+. Most of the info is outdated or controversial. Is there an up-to-date guide on how to use Python as a server-side language?

WEBjuju
  • 5,797
  • 4
  • 27
  • 36
Barsik the Cat
  • 363
  • 1
  • 2
  • 10
  • 1
    I'd recommend taking a look at Flask to start out (http://flask.pocoo.org/). Of course there are other popular frameworks like Django, etc. – Nick Dec 03 '16 at 00:58
  • 2
    Consider WSGI (https://www.fullstackpython.com/wsgi-servers.html) – DYZ Dec 03 '16 at 00:59
  • 2
    What you've got there is a basic CGI script. With CGI, you simply `print` the HTML you want displayed in the browser (and send a content type of `text/html` obviously). You can certainly use Python this way; it is an effective way to write simple scripts.The `cgi` module will help you parse data sent to your script. – kindall Dec 03 '16 at 01:05
  • 1
    @Nicarus I tried and did not understand how to use it - simply copy/pasting the code gives me error 500. – Barsik the Cat Dec 03 '16 at 01:25

3 Answers3

7

What Nicarus said was a valid sugestion but I also recommend some other things.

First, for your development environment you won't need to use xampp or wamp or such things, python has it's own HTTP server, although not the simplest thing to use, the libraries and frameworks I will explain next use that.

So, most python web developers don't use raw python to use python as their programming language for the web. Most developers use a framework or library of some kind. These frameworks range from being rather heavy and opinionated, like Django, to smaller ones like Flask. Most, if not all, of these frameworks provide some kind of easy and quick way to set up a development HTTP server for testing.

I would recommend looking up Django first since it has the most comprehensive tutorials and guides to get you started. Then, ones you're more comfortable in the Python language you can fairly easily use something else with less hand holding.

With django you can start here

Blanen
  • 682
  • 1
  • 8
  • 21
  • I'd gladly use Flask, but I don't know how to make it work - simply installing it and copy-pasting the code does not work, because I get error 500 whenever I try to open it through localhost. And what's described on Flask's website does not make much sense to me, because I don't know much about servers – Barsik the Cat Dec 03 '16 at 01:29
  • @BarsiktheCat did you try following the Flask tutorial? http://flask.pocoo.org/docs/0.11/tutorial/ You should really invest some time into learning about servers if you plan on setting one up. – Irmen de Jong Dec 03 '16 at 01:48
  • @IrmendeJong Like I said - before I do any of those steps I need to setup the server properly, and I did not find enough info. It's not the coding question, it's the setup question – Barsik the Cat Dec 03 '16 at 12:28
  • @BarsiktheCat it explains here http://flask.pocoo.org/docs/0.11/tutorial/setup/#tutorial-setup how to run the application. – Blanen Dec 03 '16 at 12:50
6

Python can be a great side server language, but not in the way PHP is. It is highly recommended to use a framework, like flask.

In PHP you have different .php files (like index.php) that do a basic routing, but in python (with Flask and also some others frameworks) you must define the URI path within the function.

You can see here an example, from its webpage Flask

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

And if you look for a API REST framework, take a look to Falcon

fernandezr
  • 660
  • 6
  • 19
  • 3
    Flask is not a web server. A web server would be something like Nginx or Apache. – Nick Dec 03 '16 at 01:02
  • Apache may be needed for full production serving, but there are plenty of small servers that are sufficient from development purposes. The `wsgi` module that comes with Python is a start. I'd check the `flask` docs for others. – hpaulj Dec 03 '16 at 01:21
  • 1
    Well, that's the problem - I couldn't make that example code work. It seems to be completely different from PHP both in the way it's written and in the way you setup local server – Barsik the Cat Dec 03 '16 at 01:28
6

For the purposes you mention, this current setup should work (at least for a while):

Apache Setup

Changes in httpd.conf

  1. Change denied to granted

<Directory /> AllowOverride none Require all granted </Directory>

  1. Look for Options +Indexes +FollowSynsLinks........ and add +ExecCGI to that line.

Options +Indexes +FollowSymLinks +Multiviews +ExecCGI

  1. Look for AddHandler cgi-script .cgi and add .py to it

AddHandler cgi-script .cgi .py

Changes in httpd-vhosts.conf

<Directory "{Your directory}"/> Options +Indexes +Includes +FollowSymLinks +MultiViews +ExecCGI AllowOverride All Require all granted </Directory>


example.py

First line of Python code #!C:\{somepath}\python

You need to find the right path and bar convention ( /, \, //...) for the first and commented line of code. In your example is: #!/Python/python

Run this script.py to find it

import sys print(sys.executable)

Paste the output next to #! and you should be able to test your test-code.py into your **www\ folder If happens to be the case that it does not work, try different combinations of python, python.exe with different bar conventions like "/" "//" "\" next to the #! line.

To display an HTML file add print ('Content-type: text/html\n\n') on to your .py code.**

Full code
Note f on html_content = f'''<html>...

#!C:\Program Files (x86)\Python37-32\python
#  -*- coding: utf-8 -*-
import cgi

stringvar = 'Hello variable'
intvar = 30
html_content = f'''<html>
<head><title>My first Python CGI app</title></head>
<body>
<p>Hello, 'world'!</p>
<p>This is a stringvar = {stringvar} </p>
<p>This is intvar = {intvar} </p>
</body>
</html>'''

print ('Content-type: text/html\n\n')
print (html_content)

"Most of the info is outdated or controversial"

Totally agree. I hope this works!

Bernard
  • 607
  • 7
  • 11
  • 1
    This answer assumes that we are configuring an Apache server ourselves. I'm interested in how to use Python server-side under WHM/cPanel. I haven't see Python mentioned in the cPanel documentation, only PHP. – David Spector Jan 12 '20 at 23:27
  • @DavidSpector I still do have the same concern about it. Sadly WHM/cPanel still isn't giving Python the attention I think it deserves. But still with shell access (even some shared hosting provides that) is possible in theory to use Python if it's installed; or maybe support will perform the installation due not root access. If you test it or get experience with that please let me know! – Bernard Feb 12 '20 at 09:00