Python HTTP API improvement: add req.headers()

Calling req.headers() will return all the request headers in
a dictionary to the caller.
This commit is contained in:
Joris Vink 2022-12-29 12:58:43 +01:00
parent 7a6753ca33
commit 7b48959c32
2 changed files with 42 additions and 0 deletions

View File

@ -750,6 +750,7 @@ static void pyhttp_dealloc(struct pyhttp_request *);
static void pyhttp_file_dealloc(struct pyhttp_file *);
static PyObject *pyhttp_cookie(struct pyhttp_request *, PyObject *);
static PyObject *pyhttp_headers(struct pyhttp_request *, PyObject *);
static PyObject *pyhttp_response(struct pyhttp_request *, PyObject *);
static PyObject *pyhttp_argument(struct pyhttp_request *, PyObject *);
static PyObject *pyhttp_body_read(struct pyhttp_request *, PyObject *);
@ -765,6 +766,7 @@ static PyObject *pyhttp_websocket_handshake(struct pyhttp_request *,
static PyMethodDef pyhttp_request_methods[] = {
METHOD("cookie", pyhttp_cookie, METH_VARARGS),
METHOD("headers", pyhttp_headers, METH_NOARGS),
METHOD("response", pyhttp_response, METH_VARARGS),
METHOD("argument", pyhttp_argument, METH_VARARGS),
METHOD("body_read", pyhttp_body_read, METH_VARARGS),

View File

@ -5093,6 +5093,46 @@ pyhttp_cookie(struct pyhttp_request *pyreq, PyObject *args)
return (value);
}
static PyObject *
pyhttp_headers(struct pyhttp_request *pyreq, PyObject *args)
{
struct http_header *hdr;
struct http_request *req;
PyObject *obj, *dict, *ret;
ret = NULL;
obj = NULL;
dict = NULL;
req = pyreq->req;
if ((dict = PyDict_New()) == NULL)
goto cleanup;
if ((obj = PyUnicode_FromString(req->host)) == NULL)
goto cleanup;
if (PyDict_SetItemString(dict, "host", obj) == -1)
goto cleanup;
TAILQ_FOREACH(hdr, &req->req_headers, list) {
if ((obj = PyUnicode_FromString(hdr->value)) == NULL)
goto cleanup;
if (PyDict_SetItemString(dict, hdr->header, obj) == -1)
goto cleanup;
}
ret = dict;
obj = NULL;
dict = NULL;
cleanup:
Py_XDECREF(obj);
Py_XDECREF(dict);
return (ret);
}
static PyObject *
pyhttp_file_lookup(struct pyhttp_request *pyreq, PyObject *args)
{