0

How to query id from the url? I want to get id from request so I tried this but it doesn't work.

My request url:http://localhost:8888/api/genshin?id=119480035 then it gives me 404.I expect it can query the id instead of 404

def do_GET(self):
        if self.path == "/api/genshin":
            # request url example: /api/genshin?id=119480035
            id = self.path.split("=")[1]
            data = asyncio.run(main(id))
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(bytes(json.dumps(data), "utf-8"))
        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(bytes("<h1>404 Not Found</h1>", "utf-8"))

2 Answers2

0

You are apparently using BaseHTTPRequestHandler, where the documentation says

path contains the request path. If query component of the URL is present, then path includes the query.

(emphasis mine), which is why the if statement doesn't match if it has a query.

You'd need to split self.path so you only get the path and the query to match them. It's easy to do with urlparse; you can also use parse_qsl to parse the query parameters:

from urllib.parse import urlparse, parse_qsl

# ...

def do_GET(self):
    parsed = urlparse(f"http://fake{self.path}")
    path = parsed.path
    query = dict(parse_qsl(parsed.query))
    if path == "/api/genshin":
        id = query.get("id")
    # ...

However, all in all you might want to look at a higher-level mini web framework such as Flask.

AKX
  • 152,115
  • 15
  • 115
  • 172
-1

?id=119480035 is query parameter, you need to pass it when making the request, and depends on it's a GET or POST request, it's different to pass.

For example: Python Request Post with param data

Q.W.
  • 122
  • 1
  • 10