0

I am trying to write the python code, that return the json output when I curl localhost:8000. I want to get the value only when I do curl localhost:8000/shakespear. As of the current code I am getting the value at curl localhost:8000 main.py

#!/usr/bin/env python

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import json

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed_path = urlparse(self.path)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(json.dumps({
            'myfavourite author name': 'shakespear',
        }).encode())
        return
if __name__ == '__main__':
    server = HTTPServer(('0.0.0.0', 8000), RequestHandler)
    print('Starting server at http://localhost:8000')
    server.serve_forever()
  • See this [approach](https://stackoverflow.com/a/18346685/11323371). I would suggest using [Flask](https://flask.palletsprojects.com/en/2.1.x/]) if possible as it offers a more robust routing. – InsertCheesyLine Apr 16 '22 at 10:38
  • I have tried using this but I am unable to route even then, can you tell me where shall I add the if condition? –  Apr 16 '22 at 10:44

2 Answers2

0

you are ignoring the path and sending a general purpose response to each request. as you can see in RequestHandler class, variable parsed_path is ignored and it doesn't matter whats the path, response is a const static thing. you should change the code and process parsed_path and make a appropriate response for each request and put it in self.wfile.write

Mohammad
  • 19
  • 3
  • Hi I am new to python, can you tell me how? Any code snippet would be a great help –  Apr 16 '22 at 10:49
0

Use an if condition to check if parsed.path is the same as your desired endpoint i.e shakespear

def do_GET(self):
  ...
  if self.path == '/shakespear':
    self.send_response(200)
    #do stuff
    ...

Keep in mind that / is part of the path string. With self.path using urlparse is unnecessary

It is meant to be used when you're working with a url that you need parsed.

Example:

As explained in the docs, urlparse returns a ParseResult with the path attribute.

Pass the url to urlparse:

from urllib.parse import urlparse
url = "http://127.0.0.1:8080/shakespear"
parsed = urlparse(url)

This returns a ParseResult whose path attribute you can access:

print(parsed)
ParseResult(scheme='http', netloc='127.0.0.1:8080', path='/shakespear', 
params='', query='', fragment='')

print(parsed.path)
'/shakespear'
InsertCheesyLine
  • 1,112
  • 2
  • 11
  • 19