Skip to content Skip to sidebar Skip to footer

How To Run Python Scripts On A Web Server (e.g Localhost)

In my development of Android and Java applications I have been using PHP scripts to interact with an online MySQL database, but now I want to migrate to Python. How does one run Py

Solution 1:

You can use Flask to run webapps.

The simple Flask app below will help you get started.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/sampleurl' methods = ['GET'])defsamplefunction():
    #access your DB get your results here
    data = {"data":"Processed Data"}
    return jsonify(data)

if __name__ == '__main__':
    port = 8000#the custom port you want
    app.run(host='0.0.0.0', port=port)

Now when you hit http://your.systems.ip:8000/sampleurl you will get a json response for you mobile app to use.

From within the function you can either do DB reads or file reads, etc.

You can also add parameters like this:

@app.route('/sampleurl' methods = ['GET'])
def samplefunction():
    required_params = ['name', 'age']
    missing_params = [key for key in required_params if key not in request.args.keys()]

    if len(missing_params)==0:
        data = {
                "name": request.argv['name'],
                "age": request.argv['age']
               }

        return jsonify(data)
    else:
         resp = {
                 "status":"failure",
                 "error" : "missing parameters",
                 "message" : "Provide %s in request" %(missing_params)
                }
         return jsonify(resp)

To run this save the flask app in a file e.g. myapp.py

Then from terminal run python myapp.py

It will start the server on port 8000 (or as specified by you.)

Flask's inbuilt server is not recommended for production level use. After you are happy with the app, you might want to look into Nginx + Gunicorn + Flask system.

For detailed instruction on flask you can look at this answer. It is about setting up a webserver on Raspberry pi, but it should work on any linux distro.

Hope that helps.

Solution 2:

Use a web application framework like CherryPy, Django, Webapp2 or one of the many others. For a production setup, you will need to configure the web server to make them work.

Or write CGI programs with Python.

Solution 3:

On Apache the simplest way would be to write the python as CGI here is an example:

First create an .htaccess for the web folder that is serving your python:

AddHandler cgi-script .py
Options +ExecCGI

Then write python that includes some some cgi libraries and outputs headers as well as the content:

#!/usr/bin/pythonimport cgi
import cgitb
cgitb.enable()

# HEADERSprint"Content-Type:text/html; charset=UTF-8"print# blank line required at end of headers# CONTENTprint"<html><body>"print"Content"print"</body></html>"

Make sure the file is owned by Apache chown apache. filename and has the execute bit set chmod +x filename.

There are many significant benefits to actually using a web framework (mentioned in other answers) over this method, but in a localhost web server environment set up for other purposes where you just want to run one or two python scripts, this works well.

Notice I didn't actually utilize the imported cgi library in this script, but hopefully that will direct you to the proper resources.

Solution 4:

Most web development in python happens using a web framework. This is different than simply having scripts on the server, because the framework has a lot more functionality, such as handling URL routing, HTML templating, ORM, user session management, CSRF protection, and a lot of other features. This makes it easier to develop web sites, especially since it promotes component reuse, in a OOP fashion.

The most popular python web framework is Django. It's a fully-featured, tighly-coupled framework, with lots of documentation available. If you prefer something more modular and easier to customize, I personally recommend Flask. There's also lots of other choices available.

With that being said, if all you really want is to run a single, simple python script on a server, you can check this question for a simple example using apache+cgi.

Post a Comment for "How To Run Python Scripts On A Web Server (e.g Localhost)"