Home > Back-end >  Path based routing in Python
Path based routing in Python

Time:04-17

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()

CodePudding user response:

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'

CodePudding user response:

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

  • Related