Skip to content

Instantly share code, notes, and snippets.

@odony
Forked from ctolsen/curl_to_ab.py
Last active May 15, 2022 16:19
Show Gist options
  • Save odony/93086f5c917e777cb2f4d0c04d477545 to your computer and use it in GitHub Desktop.
Save odony/93086f5c917e777cb2f4d0c04d477545 to your computer and use it in GitHub Desktop.
"Copy to cURL" in Chrome to Apache Bench command
#!/usr/bin/env python
import sys
import tempfile
import os
def curl_to_ab(curl_cmd, num=200, cur=4):
"""
Translate a cURL command created by Chrome's developer tools into a
command for ``ab``, the ApacheBench HTTP benchmarking tool.
Parameters
----------
curl_cmd
The string given to you by the "Copy to cURL" context action in
Chrome's developer tools.
num : int
The number of requests ApacheBench should make in total
cur : int
The number of concurrent requests ApacheBench should make
Note
----
Not all headers play nice with ApacheBench, so ``headers_to_copy`` has
been set to a reasonable default. Tweak this if you need something
else in there.
"""
url = curl_cmd[1]
headers_to_copy = [
'Origin',
'Authorization',
'Accept',
'Accept-Encoding',
'Cookie',
# 'Content-Type' handled separately
]
headers = []
tf, ct = None, None
for i, part in enumerate(curl_cmd):
if part == '-H':
header = curl_cmd[i+1]
if any([h in header for h in headers_to_copy]):
headers.append("'{}'".format(header))
elif 'Content-Type:' in header:
ct = header.split(':')[1].strip()
elif part == '--data-binary' or part == '--data-raw':
tf = tempfile.NamedTemporaryFile(prefix="curl2ab", suffix=".post", delete=False)
tf.write(curl_cmd[i+1].encode('utf-8'))
tf.close()
cmd = ['ab -n {} -c {}'.format(num, cur)]
if ct:
cmd += ["-T '{}'".format(ct)]
cmd += ['-H {}'.format(part) for part in headers]
if tf:
cmd.append('-p {}'.format(tf.name))
cmd.append("'{}'".format(url))
return ' '.join(cmd)
if __name__ == '__main__':
"""Usage: python curl_to_ab.py <cURL command from Chrome>
"""
print('\n\n\n\n'+curl_to_ab(sys.argv[1:])+'\n\n\n')
@spencerwilson
Copy link

Thank you! Consider changing line 1 to

#!/usr/bin/env python2

as tf.write(curl_cmd[i+1]) fails under Python 3.

@odony
Copy link
Author

odony commented May 21, 2021

Thank you! Consider changing line 1 to

Thanks, I've updated that line to work in both Python2 and Python3, I tend to avoid breaking compatibility when I don't really need to :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment