Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: http://123.45.67.89:12345/calculate?**number1=12**&**number2=13**&**operation=addition**

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.

like image 655
HareTortoise Avatar asked Jan 22 '26 06:01

HareTortoise


1 Answers

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

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

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

Or even with flask:

from flask import Flask

app = Flask(__name__)

@app.route('/calculate')
def calculate():
    if request.args.get('operation') == 'addition':
        return str(int(request.args.get('number1')) + int(request.args.get('number2')))
    else:
        return 'Unsupported operation'

if __name__ == '__main__':
    app.run()
like image 68
Pierre Barre Avatar answered Jan 23 '26 19:01

Pierre Barre