I have used Python but not in a backend server scenario. I want to create a Python backend that when invoked with a URL will run a simple Python script that will return back an integer.
So far, I have been able to set up the HTTP Server by
python -m SimpleHTTPServer
and as you see I have a long way to go. I have read about CGI a bit but unable to get the hang of it.
I would appreciate if you can help me design the simple backend .py file and the corresponding URL, something like:
http://localhost:8000/my_prog.py
and on the client side when I invoke this URL I will need to get an integer value in my response.
I will take this forward to actually return a JSON response but first I need to know how to return a simple int.
Thanks much !
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
NUMBER = 5
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(str(NUMBER))
httpd = HTTPServer(('localhost', 5001), Handler)
httpd.serve_forever()
You could run this by calling python server.py
and it would return the number in text:
$ http GET :5001
HTTP/1.0 200 OK
Date: Mon, 12 Jun 2017 11:07:11 GMT
Server: BaseHTTP/0.3 Python/2.7.12
5
However, if you're planning to develop a larger application and you can include third-party modules via pip, I'd also suggest to use Flask or other small http server library.