Robert Phares
Robert Phares

Reputation: 5

Running flask and python with CGI

I registered a domain and it allows the use of CGI scripts. But I don't know how to run flask + python with the script. https://flask.palletsprojects.com/en/1.1.x/deploying/cgi/ gives a decent description of what to do but still was unable to get flask and python to run. My python file:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return '<h1>Hello World!</h1>'

Also the cgi file:

#!/usr/bin/python
from wsgiref.handlers import CGIHandler
from yourapplication import app

CGIHandler().run(app)

And the htaccess file:

DirectoryIndex Home.html

# Begin EnforceSSL double-numbersign-freelancer.com
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?double-numbersign-freelancer.com$
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L]
</IfModule>
# End EnforceSSL

Upvotes: 0

Views: 3637

Answers (1)

rzlvmp
rzlvmp

Reputation: 9364

Okay. I checked it

Answering for my configuration → CentOS 7 / httpd 2.4.6

  1. Open /etc/httpd/conf/httpd.conf and add python handler
# standard part
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
# add handler here
AddHandler cgi-script .py
</Directory>
  1. Put run.py inside /var/www/cgi-bin
#!/usr/bin/python3
from wsgiref.handlers import CGIHandler
from flask import Flask

app = Flask(__name__)
@app.route('/')
def index():
    return '<h1>Hello World!</h1>'

@app.route('/suburl')
def index2():
    return '<h1>Hello World 2!</h1>'

CGIHandler().run(app)
  1. Change script permissions to allow execution:
chmod +x /var/www/cgi-bin/run.py
  1. Now you can access:
http://your_server_url.com/cgi-bin/run.py → Hello World!
http://your_server_url.com/cgi-bin/run.py/suburl → Hello World 2!

Huh. That was my first experience with Flask CGI. Pretty simple and good for small or test projects.
Anyway I recommend to use gunicorn, uwsgi or mod_wsgi for apache in production.

  • EDIT1: Using CGI without flask

Actually you don't need flask for run CGI scripts. It can be written with any language that can read environment variables and output some data.

Bash example /var/www/cgi-bin/run.cgi:

#!/usr/bin/bash

echo "Content-type:text/plain"
echo
echo -e "HELLO WORLD\nYour URL path is $PATH_INFO"

Output will be:

http://example.com/cgi-bin/run.cgi/suburl
HELLO WORLD
Your URL path is /suburl

Upvotes: 1

Related Questions