HTML encode key-value pairs for HTTP POST (script)


/ Published in: Python
Save to your folder(s)

URLencode key-value pairs for HTTP POST - useful from shell, make sure you chmod +x this script before using.


Copy this code and paste it in your HTML
  1. #!/usr/bin/env python
  2. __author__ = 'Sean Boyce'
  3. __license__ = 'PSF'
  4.  
  5. import sys, urllib
  6.  
  7. def usage():
  8. import os.path
  9. scriptname = os.path.basename(sys.argv[0])
  10. ret = """Usage: %s KEY=VALUE ...
  11. Returns a html encoded post string based on keys and values
  12.  
  13. Example:
  14. In: %s name="Fred" email="[email protected]"
  15. Out: name=Fred&email=fred%%40example.com
  16. """ % (scriptname, scriptname,)
  17. return ret
  18.  
  19.  
  20. def html_encode(args):
  21. try:
  22. import urllib
  23. ls = [ tuple(x.split('=', 1)) for x in args ]
  24. return urllib.urlencode(ls, True)
  25. except Exception, e:
  26. sys.stderr.write(" ".join( ["Error!", e.__str__(), "\n"] ) )
  27. return None
  28.  
  29.  
  30. if __name__ == '__main__':
  31. ret = 1
  32. if len(sys.argv) > 1:
  33. output = html_encode(sys.argv[1:])
  34. if output is not None:
  35. ret = 0
  36. print(output)
  37. else:
  38. print usage()
  39.  
  40. sys.exit(ret)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.