9

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 Python scripts on a web server? In my experience with PHP, I have been saving my files under /var/www folder in a Linux environment. Then I just call the file later with a URL of the path. Where do I save my Python scripts?

4

4 Answers 4

6

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'])
def samplefunction():
    #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.

Sign up to request clarification or add additional context in comments.

1 Comment

Does it have to be Flask? Could I eg. use nodejs?
1

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.

Comments

1

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.

Comments

1

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/python

import cgi
import cgitb
cgitb.enable()

# HEADERS
print "Content-Type:text/html; charset=UTF-8"
print  # blank line required at end of headers

# CONTENT
print "<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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.