Skip to content

Commit e81f30a

Browse files
feat: cleaner python requests json snippets (#189)
Co-authored-by: Opender Singh <[email protected]>
1 parent 07d5ebf commit e81f30a

14 files changed

+141
-33
lines changed

src/targets/python/helpers.js

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
'use strict'
2+
3+
var util = require('util')
4+
5+
/**
6+
* Create an string of given length filled with blank spaces
7+
*
8+
* @param {number} length Length of the array to return
9+
* @param {string} str String to pad out with
10+
*/
11+
function buildString (length, str) {
12+
return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('')
13+
}
14+
15+
/**
16+
* Create a string corresponding to a Dictionary or Array literal representation with pretty option
17+
* and indentation.
18+
*/
19+
function concatValues (concatType, values, pretty, indentation, indentLevel) {
20+
var currentIndent = buildString(indentLevel, indentation)
21+
var closingBraceIndent = buildString(indentLevel - 1, indentation)
22+
var join = pretty ? ',\n' + currentIndent : ', '
23+
var openingBrace = concatType === 'object' ? '{' : '['
24+
var closingBrace = concatType === 'object' ? '}' : ']'
25+
26+
if (pretty) {
27+
return openingBrace + '\n' + currentIndent + values.join(join) + '\n' + closingBraceIndent + closingBrace
28+
} else {
29+
return openingBrace + values.join(join) + closingBrace
30+
}
31+
}
32+
33+
module.exports = {
34+
/**
35+
* Create a valid Python string of a literal value according to its type.
36+
*
37+
* @param {*} value Any JavaScript literal
38+
* @param {Object} opts Target options
39+
* @return {string}
40+
*/
41+
literalRepresentation: function (value, opts, indentLevel) {
42+
indentLevel = indentLevel === undefined ? 1 : indentLevel + 1
43+
44+
switch (Object.prototype.toString.call(value)) {
45+
case '[object Number]':
46+
return value
47+
48+
case '[object Array]':
49+
var pretty = false
50+
var valuesRepresentation = value.map(function (v) {
51+
// Switch to prettify if the value is a dictionary with multiple keys
52+
if (Object.prototype.toString.call(v) === '[object Object]') {
53+
pretty = Object.keys(v).length > 1
54+
}
55+
return this.literalRepresentation(v, opts, indentLevel)
56+
}.bind(this))
57+
return concatValues('array', valuesRepresentation, pretty, opts.indent, indentLevel)
58+
59+
case '[object Object]':
60+
var keyValuePairs = []
61+
for (var k in value) {
62+
keyValuePairs.push(util.format('"%s": %s', k, this.literalRepresentation(value[k], opts, indentLevel)))
63+
}
64+
return concatValues('object', keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel)
65+
66+
case '[object Null]':
67+
return 'None'
68+
69+
case '[object Boolean]':
70+
return value ? 'True' : 'False'
71+
72+
default:
73+
if (value === null || value === undefined) {
74+
return ''
75+
}
76+
return '"' + value.toString().replace(/"/g, '\\"') + '"'
77+
}
78+
}
79+
}

src/targets/python/requests.js

+32-11
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,14 @@
1212

1313
var util = require('util')
1414
var CodeBuilder = require('../../helpers/code-builder')
15+
var helpers = require('./helpers')
1516

1617
module.exports = function (source, options) {
18+
var opts = Object.assign({
19+
indent: ' ',
20+
pretty: true
21+
}, options)
22+
1723
// Start snippet
1824
var code = new CodeBuilder(' ')
1925

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

3642
// Construct payload
37-
var payload = JSON.stringify(source.postData.text)
43+
let hasPayload = false
44+
let jsonPayload = false
45+
switch (source.postData.mimeType) {
46+
case 'application/json':
47+
if (source.postData.jsonObj) {
48+
code.push('payload = %s', helpers.literalRepresentation(source.postData.jsonObj, opts))
49+
jsonPayload = true
50+
hasPayload = true
51+
}
52+
break
3853

39-
if (payload) {
40-
code.push('payload = %s', payload)
54+
default:
55+
var payload = JSON.stringify(source.postData.text)
56+
if (payload) {
57+
code.push('payload = %s', payload)
58+
hasPayload = true
59+
}
4160
}
4261

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

4867
if (headerCount === 1) {
4968
for (header in headers) {
50-
code.push('headers = {\'%s\': \'%s\'}', header, headers[header])
69+
code.push('headers = {"%s": "%s"}', header, headers[header])
5170
.blank()
5271
}
5372
} else if (headerCount > 1) {
@@ -57,22 +76,26 @@ module.exports = function (source, options) {
5776

5877
for (header in headers) {
5978
if (count++ !== headerCount) {
60-
code.push(1, '\'%s\': "%s",', header, headers[header])
79+
code.push(1, '"%s": "%s",', header, headers[header])
6180
} else {
62-
code.push(1, '\'%s\': "%s"', header, headers[header])
81+
code.push(1, '"%s": "%s"', header, headers[header])
6382
}
6483
}
6584

66-
code.push(1, '}')
85+
code.push('}')
6786
.blank()
6887
}
6988

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

74-
if (payload) {
75-
request += ', data=payload'
93+
if (hasPayload) {
94+
if (jsonPayload) {
95+
request += ', json=payload'
96+
} else {
97+
request += ', data=payload'
98+
}
7699
}
77100

78101
if (headerCount > 0) {
@@ -100,5 +123,3 @@ module.exports.info = {
100123
link: 'http://docs.python-requests.org/en/latest/api/#requests.request',
101124
description: 'Requests HTTP library'
102125
}
103-
104-
// response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

src/targets/swift/helpers.js

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ var util = require('util')
66
* Create an string of given length filled with blank spaces
77
*
88
* @param {number} length Length of the array to return
9+
* @param {string} str String to pad out with
910
* @return {string}
1011
*/
1112
function buildString (length, str) {

test/fixtures/output/python/requests/application-form-encoded.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
url = "http://mockbin.com/har"
44

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

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

test/fixtures/output/python/requests/application-json.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,16 @@
22

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

5-
payload = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}"
6-
headers = {'content-type': 'application/json'}
5+
payload = {
6+
"number": 1,
7+
"string": "f\"oo",
8+
"arr": [1, 2, 3],
9+
"nested": {"a": "b"},
10+
"arr_mix": [1, "a", {"arr_mix_nested": {}}],
11+
"boolean": False
12+
}
13+
headers = {"content-type": "application/json"}
714

8-
response = requests.request("POST", url, data=payload, headers=headers)
15+
response = requests.request("POST", url, json=payload, headers=headers)
916

1017
print(response.text)

test/fixtures/output/python/requests/cookies.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

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

5-
headers = {'cookie': 'foo=bar; bar=baz'}
5+
headers = {"cookie": "foo=bar; bar=baz"}
66

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

test/fixtures/output/python/requests/full.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
payload = "foo=bar"
88
headers = {
9-
'cookie': "foo=bar; bar=baz",
10-
'accept': "application/json",
11-
'content-type': "application/x-www-form-urlencoded"
12-
}
9+
"cookie": "foo=bar; bar=baz",
10+
"accept": "application/json",
11+
"content-type": "application/x-www-form-urlencoded"
12+
}
1313

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

test/fixtures/output/python/requests/headers.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
url = "http://mockbin.com/har"
44

55
headers = {
6-
'accept': "application/json",
7-
'x-foo': "Bar"
8-
}
6+
"accept": "application/json",
7+
"x-foo": "Bar"
8+
}
99

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

test/fixtures/output/python/requests/jsonObj-multiline.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

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

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

8-
response = requests.request("POST", url, data=payload, headers=headers)
8+
response = requests.request("POST", url, json=payload, headers=headers)
99

1010
print(response.text)

test/fixtures/output/python/requests/jsonObj-null-value.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

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

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

8-
response = requests.request("POST", url, data=payload, headers=headers)
8+
response = requests.request("POST", url, json=payload, headers=headers)
99

1010
print(response.text)

test/fixtures/output/python/requests/multipart-data.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
url = "http://mockbin.com/har"
44

55
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"
6-
headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}
6+
headers = {"content-type": "multipart/form-data; boundary=---011000010111000001101001"}
77

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

test/fixtures/output/python/requests/multipart-file.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
url = "http://mockbin.com/har"
44

55
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"
6-
headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}
6+
headers = {"content-type": "multipart/form-data; boundary=---011000010111000001101001"}
77

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

test/fixtures/output/python/requests/multipart-form-data.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
url = "http://mockbin.com/har"
44

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

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

test/fixtures/output/python/requests/text-plain.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
url = "http://mockbin.com/har"
44

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

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

0 commit comments

Comments
 (0)