Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python HTTP server send JSON response

What im doing

Im trying to get my hands dirty with python and im making a very simple http server so i can send commands to my arduino via serial. Im validating the commands as i sgould and everything works as it ahould be.

The concept

Im using the HTTP server in order to recieve POST requests from remote computers and smartphones and execute code with my arduino via Serial. It has few cool features like users and user permission levels.

The problem

I would like to give feedback when a request arrives. Specificaly JSON feedback with the outcome of the execution like error, notes and success. Im thinking to make a dictionary in python and add whatever i want to send back the the frontend then enclode it in json and send it as a response. (Something like php's json_encode() which takes an array and outputs json)

The code

import SimpleHTTPServer
import SocketServer
import logging
import cgi
import time
import sys

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

def do_GET(self):
    logging.warning("======= GET STARTED =======")
    logging.warning(self.headers)
    SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

def do_POST(self):
    form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={'REQUEST_METHOD':'POST',
                 'CONTENT_TYPE':self.headers['Content-Type'],
                 })

    if self.check_auth(username, passcode):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
    else:
        print cur_time + "failed to login " + form.list[0].name + form.list[0].value
        self.send_response(500)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()

SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = ServerHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
httpd.serve_forever()

I've tried to minimize the code so you can see the clear HTTP part.

As you can see im sending the headers and the response type (200 for successful login and 500 for unsuccessful login)

Objectives i need to accomplish

  • Pass inside a dictionary the stuff i want to encode

    • Exemple: out = {'status': 'ok', 'executed': 'yes'}
  • Respond with json
    • https://www.dropbox.com/s/uhxezdeqmvr0804/Screen%2018-33-01.png

The complet code as a gist: https://gist.github.com/FlevasGR/1170d2ea47d851bfe024

I know this might not be the best you you've ever seens in your life but its my first time writing in Python :)

like image 704
Zisakis Zavitsanakis Avatar asked Jan 30 '15 16:01

Zisakis Zavitsanakis


People also ask

What does Response JSON () do Python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.

What is Httpserver in Python?

Python HTTP server is a kind of web server that is used to access the files over the request. Users can request any data or file over the webserver using request, and the server returns the data or file in the form of a response.

Does Python support JSON natively?

Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.


1 Answers

The json module of Python's standard library offers exactly the functionality you're asking for. import json at the top of your module and json.dumps(whatever) to get the json string to send in the response.

As a side note, failing authorization is most definitely not a 500 error: 500 means "server error" and the server is making absolutely no error in rejecting unauthorized users!-) Use a 403 ("forbidden") or other security-related 400-code to reject unauthorized users -- see http://en.wikipedia.org/wiki/HTTP_403 and more generally http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error for more.

This latter bit isn't what you're asking about, but maintaining semantic integrity of HTTP status codes is important -- it's violated often enough on the web today to give headaches to maintainers of HTTP clients, servers, proxies, caches, &c... let's make their life easier, not harder, by sticking to the standards!_)

like image 181
Alex Martelli Avatar answered Sep 26 '22 02:09

Alex Martelli