python-http-client.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. const printHeaders = (headers) => {
  3. if (headers.length) {
  4. return [`headers = {\n`, ` ${headers.join(",\n ")}\n`, `}\n`]
  5. } else {
  6. return [`headers = {}\n`]
  7. }
  8. }
  9. export const PythonHttpClientCodegen = {
  10. id: "python-http-client",
  11. name: "Python http.client",
  12. generator: ({
  13. url,
  14. pathName,
  15. queryString,
  16. auth,
  17. httpUser,
  18. httpPassword,
  19. bearerToken,
  20. method,
  21. rawInput,
  22. rawParams,
  23. rawRequestBody,
  24. contentType,
  25. headers,
  26. }) => {
  27. const requestString = []
  28. let genHeaders = []
  29. requestString.push(`import http.client\n`)
  30. requestString.push(`import mimetypes\n`)
  31. const currentUrl = new URL(url)
  32. let hostname = currentUrl["hostname"]
  33. let port = currentUrl["port"]
  34. if (!port) {
  35. requestString.push(`conn = http.client.HTTPSConnection("${hostname}")\n`)
  36. } else {
  37. requestString.push(`conn = http.client.HTTPSConnection("${hostname}", ${port})\n`)
  38. }
  39. // auth headers
  40. if (auth === "Basic Auth") {
  41. const basic = `${httpUser}:${httpPassword}`
  42. genHeaders.push(
  43. `'Authorization': 'Basic ${window.btoa(unescape(encodeURIComponent(basic)))}'`
  44. )
  45. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  46. genHeaders.push(`'Authorization': 'Bearer ${bearerToken}'`)
  47. }
  48. // custom headers
  49. if (headers.length) {
  50. headers.forEach(({ key, value }) => {
  51. if (key) genHeaders.push(`'${key}': '${value}'`)
  52. })
  53. }
  54. // initial request setup
  55. let requestBody = rawInput ? rawParams : rawRequestBody
  56. if (method == "GET") {
  57. requestString.push(...printHeaders(genHeaders))
  58. requestString.push(`payload = ''\n`)
  59. }
  60. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  61. genHeaders.push(`'Content-Type': '${contentType}'`)
  62. requestString.push(...printHeaders(genHeaders))
  63. if (isJSONContentType(contentType)) {
  64. requestBody = JSON.stringify(requestBody)
  65. requestString.push(`payload = ${requestBody}\n`)
  66. } else if (contentType.includes("x-www-form-urlencoded")) {
  67. const formData = []
  68. if (requestBody.includes("=")) {
  69. requestBody.split("&").forEach((rq) => {
  70. const [key, val] = rq.split("=")
  71. formData.push(`('${key}', '${val}')`)
  72. })
  73. }
  74. if (formData.length) {
  75. requestString.push(`payload = [${formData.join(",\n ")}]\n`)
  76. }
  77. } else {
  78. requestString.push(`paylod = '''${requestBody}'''\n`)
  79. }
  80. }
  81. requestString.push(`conn.request("${method}", "${pathName}${queryString}", payload, headers)\n`)
  82. requestString.push(`res = conn.getresponse()\n`)
  83. requestString.push(`data = res.read()\n`)
  84. requestString.push(`print(data.decode("utf-8"))`)
  85. return requestString.join("")
  86. },
  87. }