HareTortoise HareTortoise - 2 years ago 86
Python Question

What's a simple way to build a python web service which will take arguments and return a value?

I want to write a simple python web service which will read the arguments provided in the called url and based on that return some basic string.

In order to get started and get a better understanding of the whole thing, I'd like to start by creating a "calculator" web service which will take two numbers and an operator and based on these inputs return the mathematical result.

For example if I call from my browser something like:

I'd like the python script to figure out (i guess most probably by some simple switch/case statement) that it should execute something like this: "return number1 + number2" and return the result 25 to the caller.

I am sure this shouldn't be a too big problem to implement this in python since it isn't anything too fancy, but, as a beginner, I wasn't able to find the right starting point.

Any help is appreciated.

Answer Source

Have a look at the WSGI specification.

You can also use a framework like bottle which make your work easier:

from bottle import route, run, request

def index():
    if request.GET.get('operation') == 'addition':
        return str(int(request.GET.get('number1')) + int(request.GET.get('number2')))
        return 'Unsupported operation'

if __name__ == '__main__':
    run(host='', port=12345)

Or even with flask:

from flask import Flask

app = Flask(__name__)

def calculate():
    if request.args.get('calculate') == 'addition'
        return int(request.args.get('number1')) + int(request.args.get('number2')) 
        return 'Unsupported operation'

if __name__ == '__main__':
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download