Having Web Server Parse JSON file after POST request

Viewed 33

I'm working on a project for my job, and here's what we're trying to accomplish as of right now: we're working on developing a simple web server that collects information from a user, and we've developed code such that whoever is using the code inputs two pieces of information into the system, and then a JSON file gets updated with those pieces of information as they get collected. Then, we send the JSON file to a local web server with a POST request. What we would like to happen next is for the web server to parse the piece of the JSON file we want to analyze and have it check some made-up database to see if a certain condition is met, then send a response back to the user based on what that piece of information provides. The part I'm having trouble with is how to get the web server to parse that information inside so that it can check whatever it needs to check, and I'm also having trouble figuring out how to execute the rest of the tasks I'd like to execute.

Here's what I have for the web server code so far:

#! /usr/bin/python3 

# Python 3 web-server example
from http.server import BaseHTTPRequestHandler, HTTPServer
from time import sleep
from random import randint

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        sleep(randint(1,5)) # wait a random number of seconds before sending response
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>https://smart-scale-northbound-web- 
   server.us.lmco.com</title></head>", "utf-8"))
        self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("<body>", "utf-8"))
        self.wfile.write(bytes("<p>This is an example web-server.</p>", "utf-8"))
        self.wfile.write(bytes("</body></html>", "utf-8"))

    def do_POST(self):
        sleep(randint(1,5)) # wait a random number of seconds before sending response
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>https://smart-scale-northbound-web- 
   server.us.lmco.com/post</title></head>", "utf-8"))
        self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("<body>", "utf-8"))
        self.wfile.write(bytes("<p>You've got 
    data!_________________________________________Mixing-Scale Stuff\</p>", "utf-8"))
    self.wfile.write(bytes("</body></html>", "utf-8"))

if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

Here's an example of what I would have for the JSON file. Basically, what I'm trying to do is have the web server check the asset id portion of the JSON file to check with some database that we have hard-coded into the web server so that the web server can send a response back

{"Material": "Colored Liquid", "PO": 2, "Operation Number": 3, "Date": "8-22-22", "Asset ID": "2"}

Here is an example of the "database" that I'd like for the web service to check. Note: I'm not looking to create an actual database with SQL or anything; all I'm trying to do right now is simulate what would be happening if we were to connect it to a database. What I'd like to have happen is have the web server take the asset id portion of the JSON file and check it with this database so that it can send a response back to the user.

sample_database={
1: "In Calibration",
2: "Out of Calibration",
3: "Not Found"

}

Here is also some code that I have to test out the post request and get a response back

import requests as req
import time
from datetime import date
from bs4 import BeautifulSoup
import json
from database import db_ratios as db

material=input('Please enter the material: ')
asset_id=input('Please enter asset id: ')



dict={
    "Date":"8-22-22"
}

dict["Material"]=material
dict["Asset ID"]=asset_id

with open('sample.json','r+') as f:
    d=json.load(f)
    d.update(dict)
    f.seek(0)
    json.dump(d,f)

resp=req.post('http://localhost:8080/', data=d)
data=resp.json()

One thing to note about this code, though, is that I do get a JSONDecodeError, so perhaps there is some piece of information I don't know yet that is causing this error. I'm pretty new to web servers, so if you guys have input on how I can fix this, that would be much appreciated.

I know this is a lot, so here's what I'm asking in a nutshell:

  1. How do I get the web server to parse a JSON file that I've sent it via a post request?
  2. How can I hard-code some database into the web service so it can check the posted JSON file with?
  3. How can I perform that check?
  4. When that check is done, how can I send a response back to the user?

Once again, I'm very new at this, so whatever input you have is much appreciated.

0 Answers
Related