Skip to content

Commit

Permalink
feat: cleaner python requests json snippets (Kong#189)
Browse files Browse the repository at this point in the history
Co-authored-by: Opender Singh <opender.singh@konghq.com>
  • Loading branch information
erunion and develohpanda authored Dec 1, 2020
1 parent 07d5ebf commit e81f30a
Show file tree
Hide file tree
Showing 14 changed files with 141 additions and 33 deletions.
79 changes: 79 additions & 0 deletions src/targets/python/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'use strict'

var util = require('util')

/**
* Create an string of given length filled with blank spaces
*
* @param {number} length Length of the array to return
* @param {string} str String to pad out with
*/
function buildString (length, str) {
return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('')
}

/**
* Create a string corresponding to a Dictionary or Array literal representation with pretty option
* and indentation.
*/
function concatValues (concatType, values, pretty, indentation, indentLevel) {
var currentIndent = buildString(indentLevel, indentation)
var closingBraceIndent = buildString(indentLevel - 1, indentation)
var join = pretty ? ',\n' + currentIndent : ', '
var openingBrace = concatType === 'object' ? '{' : '['
var closingBrace = concatType === 'object' ? '}' : ']'

if (pretty) {
return openingBrace + '\n' + currentIndent + values.join(join) + '\n' + closingBraceIndent + closingBrace
} else {
return openingBrace + values.join(join) + closingBrace
}
}

module.exports = {
/**
* Create a valid Python string of a literal value according to its type.
*
* @param {*} value Any JavaScript literal
* @param {Object} opts Target options
* @return {string}
*/
literalRepresentation: function (value, opts, indentLevel) {
indentLevel = indentLevel === undefined ? 1 : indentLevel + 1

switch (Object.prototype.toString.call(value)) {
case '[object Number]':
return value

case '[object Array]':
var pretty = false
var valuesRepresentation = value.map(function (v) {
// Switch to prettify if the value is a dictionary with multiple keys
if (Object.prototype.toString.call(v) === '[object Object]') {
pretty = Object.keys(v).length > 1
}
return this.literalRepresentation(v, opts, indentLevel)
}.bind(this))
return concatValues('array', valuesRepresentation, pretty, opts.indent, indentLevel)

case '[object Object]':
var keyValuePairs = []
for (var k in value) {
keyValuePairs.push(util.format('"%s": %s', k, this.literalRepresentation(value[k], opts, indentLevel)))
}
return concatValues('object', keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel)

case '[object Null]':
return 'None'

case '[object Boolean]':
return value ? 'True' : 'False'

default:
if (value === null || value === undefined) {
return ''
}
return '"' + value.toString().replace(/"/g, '\\"') + '"'
}
}
}
43 changes: 32 additions & 11 deletions src/targets/python/requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@

var util = require('util')
var CodeBuilder = require('../../helpers/code-builder')
var helpers = require('./helpers')

module.exports = function (source, options) {
var opts = Object.assign({
indent: ' ',
pretty: true
}, options)

// Start snippet
var code = new CodeBuilder(' ')

Expand All @@ -34,10 +40,23 @@ module.exports = function (source, options) {
}

// Construct payload
var payload = JSON.stringify(source.postData.text)
let hasPayload = false
let jsonPayload = false
switch (source.postData.mimeType) {
case 'application/json':
if (source.postData.jsonObj) {
code.push('payload = %s', helpers.literalRepresentation(source.postData.jsonObj, opts))
jsonPayload = true
hasPayload = true
}
break

if (payload) {
code.push('payload = %s', payload)
default:
var payload = JSON.stringify(source.postData.text)
if (payload) {
code.push('payload = %s', payload)
hasPayload = true
}
}

// Construct headers
Expand All @@ -47,7 +66,7 @@ module.exports = function (source, options) {

if (headerCount === 1) {
for (header in headers) {
code.push('headers = {\'%s\': \'%s\'}', header, headers[header])
code.push('headers = {"%s": "%s"}', header, headers[header])
.blank()
}
} else if (headerCount > 1) {
Expand All @@ -57,22 +76,26 @@ module.exports = function (source, options) {

for (header in headers) {
if (count++ !== headerCount) {
code.push(1, '\'%s\': "%s",', header, headers[header])
code.push(1, '"%s": "%s",', header, headers[header])
} else {
code.push(1, '\'%s\': "%s"', header, headers[header])
code.push(1, '"%s": "%s"', header, headers[header])
}
}

code.push(1, '}')
code.push('}')
.blank()
}

// Construct request
var method = source.method
var request = util.format('response = requests.request("%s", url', method)

if (payload) {
request += ', data=payload'
if (hasPayload) {
if (jsonPayload) {
request += ', json=payload'
} else {
request += ', data=payload'
}
}

if (headerCount > 0) {
Expand Down Expand Up @@ -100,5 +123,3 @@ module.exports.info = {
link: 'http://docs.python-requests.org/en/latest/api/#requests.request',
description: 'Requests HTTP library'
}

// response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
1 change: 1 addition & 0 deletions src/targets/swift/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var util = require('util')
* Create an string of given length filled with blank spaces
*
* @param {number} length Length of the array to return
* @param {string} str String to pad out with
* @return {string}
*/
function buildString (length, str) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
url = "http://mockbin.com/har"

payload = "foo=bar&hello=world"
headers = {'content-type': 'application/x-www-form-urlencoded'}
headers = {"content-type": "application/x-www-form-urlencoded"}

response = requests.request("POST", url, data=payload, headers=headers)

Expand Down
13 changes: 10 additions & 3 deletions test/fixtures/output/python/requests/application-json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@

url = "http://mockbin.com/har"

payload = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}"
headers = {'content-type': 'application/json'}
payload = {
"number": 1,
"string": "f\"oo",
"arr": [1, 2, 3],
"nested": {"a": "b"},
"arr_mix": [1, "a", {"arr_mix_nested": {}}],
"boolean": False
}
headers = {"content-type": "application/json"}

response = requests.request("POST", url, data=payload, headers=headers)
response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)
2 changes: 1 addition & 1 deletion test/fixtures/output/python/requests/cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

url = "http://mockbin.com/har"

headers = {'cookie': 'foo=bar; bar=baz'}
headers = {"cookie": "foo=bar; bar=baz"}

response = requests.request("POST", url, headers=headers)

Expand Down
8 changes: 4 additions & 4 deletions test/fixtures/output/python/requests/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@

payload = "foo=bar"
headers = {
'cookie': "foo=bar; bar=baz",
'accept': "application/json",
'content-type': "application/x-www-form-urlencoded"
}
"cookie": "foo=bar; bar=baz",
"accept": "application/json",
"content-type": "application/x-www-form-urlencoded"
}

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

Expand Down
6 changes: 3 additions & 3 deletions test/fixtures/output/python/requests/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
url = "http://mockbin.com/har"

headers = {
'accept': "application/json",
'x-foo': "Bar"
}
"accept": "application/json",
"x-foo": "Bar"
}

response = requests.request("GET", url, headers=headers)

Expand Down
6 changes: 3 additions & 3 deletions test/fixtures/output/python/requests/jsonObj-multiline.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

url = "http://mockbin.com/har"

payload = "{\n \"foo\": \"bar\"\n}"
headers = {'content-type': 'application/json'}
payload = {"foo": "bar"}
headers = {"content-type": "application/json"}

response = requests.request("POST", url, data=payload, headers=headers)
response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)
6 changes: 3 additions & 3 deletions test/fixtures/output/python/requests/jsonObj-null-value.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

url = "http://mockbin.com/har"

payload = "{\"foo\":null}"
headers = {'content-type': 'application/json'}
payload = {"foo": None}
headers = {"content-type": "application/json"}

response = requests.request("POST", url, data=payload, headers=headers)
response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)
2 changes: 1 addition & 1 deletion test/fixtures/output/python/requests/multipart-data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
url = "http://mockbin.com/har"

payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n"
headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}
headers = {"content-type": "multipart/form-data; boundary=---011000010111000001101001"}

response = requests.request("POST", url, data=payload, headers=headers)

Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/output/python/requests/multipart-file.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
url = "http://mockbin.com/har"

payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n"
headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}
headers = {"content-type": "multipart/form-data; boundary=---011000010111000001101001"}

response = requests.request("POST", url, data=payload, headers=headers)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
url = "http://mockbin.com/har"

payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n"
headers = {'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001'}
headers = {"Content-Type": "multipart/form-data; boundary=---011000010111000001101001"}

response = requests.request("POST", url, data=payload, headers=headers)

Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/output/python/requests/text-plain.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
url = "http://mockbin.com/har"

payload = "Hello World"
headers = {'content-type': 'text/plain'}
headers = {"content-type": "text/plain"}

response = requests.request("POST", url, data=payload, headers=headers)

Expand Down

0 comments on commit e81f30a

Please sign in to comment.