Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Python server to process GET and POST requests with JSON

I'm trying to create a simple Python server in order to test my frontend. It should be able to handle GET and POST requests. The data should be always in JSON format until they are translated to HTTP request/response. A script with corresponding name should be called to handle each request.

server.py

#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import json
import urlparse
import subprocess

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        parsed_path = urlparse.urlparse(self.path)
        request_id = parsed_path.path
        response = subprocess.check_output(["python", request_id])
        self.wfile.write(json.dumps(response))

    def do_POST(self):
        self._set_headers()
        parsed_path = urlparse.urlparse(self.path)
        request_id = parsed_path.path
        response = subprocess.check_output(["python", request_id])
        self.wfile.write(json.dumps(response))

    def do_HEAD(self):
        self._set_headers()

def run(server_class=HTTPServer, handler_class=S, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

Example of testscript.py for handling requests, which in this case just returns a JSON object.

#!/usr/bin/env python
return {'4': 5, '6': 7}

The server should for example return {'4': 5, '6': 7} for a response in format http://www.domainname.com:8000/testscript.

My problem is that I can't figure out how to pass variables in between and I need help to make it work.

like image 560
Peter G. Avatar asked Nov 12 '15 01:11

Peter G.


People also ask

How do I send a JSON POST request in Python?

Use The json parameter: The requests module provides a json parameter that we can use to specify JSON data in the POST method. i.e., To send JSON data, we can also use the json parameter of the requests. post() method.

How do you make GET and post requests in python?

To create a POST request in Python, use the requests. post() method. The requests post() method accepts URL. data, json, and args as arguments and sends a POST request to a specified URL.

How do you send a POST request with a body in Python?

You'll want to adapt the data you send in the body of your request to the specified URL. Syntax: requests. post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)

How do I send a POST request with JSON payload?

To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.


1 Answers

Just one more option for those who prefer Flask. This framework is very popular and quite well documented.

Create file wsgi.py (name is important to not to have a deal with environment variables later) with the content like the following:

from flask import Flask, request

app = Flask(__name__)


@app.route('/object/<path_param>')
def get_object(path_param):
    return {
        'path_param': path_param,
        'query_param': request.args.get('q', "'q' not set"),
    }


if __name__ == '__main__':
    app.run()

Run server in terminal like: flask run --reload --host "127.0.0.1" --port 7777

Send queries like: curl -i http://localhost:7777/object/something?q=q

Also don't forget to do pip3 install flask to make this work.

like image 60
Konstantin Smolyanin Avatar answered Oct 01 '22 01:10

Konstantin Smolyanin