pythonRequestRenderer.jsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Fence } from '@/components/Fence';
  2. const PythonRequestRenderer = ({ url, headers, bodyMethod, rpcVersion, bodyParams, id }) => {
  3. const httpBody = bodyParams;
  4. // Handle default values for `rpcVersion` and `id`
  5. const rpcVersionValue = rpcVersion || '2.0';
  6. const idValue = id || 1;
  7. // Function to format params as Python-style dictionaries
  8. const formatParamsForPython = (params) => {
  9. if (Array.isArray(params)) {
  10. return `[${params.map(item => `'${item}'`).join(', ')}]`; // Correct array formatting for Python
  11. }
  12. if (typeof params === 'object') {
  13. return `{${Object.entries(params)
  14. .map(([key, value]) => `'${key}': '${value}'`)
  15. .join(', ')}}`; // Use Python dict syntax for key-value pairs
  16. }
  17. return `'${params}'`;
  18. };
  19. const formattedParams = formatParamsForPython(httpBody);
  20. // Convert headers to Python dict format
  21. const headersCode = Object.entries(headers)
  22. .map(([key, value]) => `'${key}': '${value}'`)
  23. .join(",\n ");
  24. const code = `
  25. import requests
  26. import json
  27. url = "${url}"
  28. headers = {
  29. "Content-Type": "application/json",
  30. }
  31. data = {
  32. "jsonrpc": "${rpcVersionValue}",
  33. "id": ${idValue},
  34. "method": "${bodyMethod}",
  35. "params": ${formattedParams}
  36. }
  37. response = requests.post(url, headers=headers, data=json.dumps(data))
  38. print(f"Response Code: {response.status_code}")
  39. print(f"Response Body: {response.text}")
  40. `;
  41. return (
  42. <Fence className="w-full" language="python">
  43. {code}
  44. </Fence>
  45. );
  46. };
  47. export default PythonRequestRenderer;