|
| 1 | +'use strict' |
| 2 | + |
| 3 | +var util = require('util') |
| 4 | + |
| 5 | +module.exports = function (source, options) { |
| 6 | + // Start Request |
| 7 | + var code = [] |
| 8 | + code.push('import http.client\n') |
| 9 | + |
| 10 | + // Check which protocol to be used for the client connection |
| 11 | + var protocol = source.uriObj.protocol |
| 12 | + if (protocol === 'https:') { |
| 13 | + code.push(util.format('conn = http.client.HTTPSConnection("%s")\n', source.uriObj.host)) |
| 14 | + } else { |
| 15 | + code.push(util.format('conn = http.client.HTTPConnection("%s")\n', source.uriObj.host)) |
| 16 | + } |
| 17 | + |
| 18 | + // Create payload string if it exists |
| 19 | + var payload = JSON.stringify(source.postData.text) |
| 20 | + if (payload) { |
| 21 | + code.push(util.format('payload = %s\n', payload)) |
| 22 | + } |
| 23 | + |
| 24 | + // Create Headers |
| 25 | + var header |
| 26 | + var headers = source.allHeaders |
| 27 | + var headerCount = Object.keys(headers).length |
| 28 | + if (headerCount === 1) { |
| 29 | + for (header in headers) { |
| 30 | + code.push(util.format('headers = { \'%s\': "%s" }\n', header, headers[header])) |
| 31 | + } |
| 32 | + } else if (headerCount > 1) { |
| 33 | + var headerLine |
| 34 | + var count = 1 |
| 35 | + code.push('headers = {') |
| 36 | + for (header in headers) { |
| 37 | + if (count++ !== headerCount) { |
| 38 | + headerLine = util.format(' \'%s\': "%s",', header, headers[header]) |
| 39 | + } else { |
| 40 | + headerLine = util.format(' \'%s\': "%s"', header, headers[header]) |
| 41 | + } |
| 42 | + code.push(headerLine) |
| 43 | + } |
| 44 | + code.push(' }\n') |
| 45 | + } |
| 46 | + |
| 47 | + // Make Request |
| 48 | + var method = source.method |
| 49 | + var path = source.uriObj.path |
| 50 | + if (payload && headerCount) { |
| 51 | + code.push(util.format('conn.request("%s", "%s", payload, headers)', method, path)) |
| 52 | + } else if (payload && !headerCount) { |
| 53 | + code.push(util.format('conn.request("%s", "%s", payload)', method, path)) |
| 54 | + } else if (!payload && headerCount) { |
| 55 | + code.push(util.format('conn.request("%s", "%s", headers = headers)', method, path)) |
| 56 | + } else { |
| 57 | + code.push(util.format('conn.request("%s", "%s")', method, path)) |
| 58 | + } |
| 59 | + |
| 60 | + // Get Response |
| 61 | + code.push('\nres = conn.getresponse()') |
| 62 | + code.push('data = res.read()') |
| 63 | + code.push('\nprint(res.status)') |
| 64 | + code.push('print(data)') |
| 65 | + |
| 66 | + // console.log(code) |
| 67 | + return code.join('\n') |
| 68 | +} |
| 69 | + |
| 70 | +module.exports.info = { |
| 71 | + key: 'python3', |
| 72 | + title: 'http.client', |
| 73 | + link: 'https://docs.python.org/3/library/http.client.html', |
| 74 | + description: 'Python3 HTTP Client' |
| 75 | +} |
0 commit comments