Skip to content

Instantly share code, notes, and snippets.

@davidchambers
Created September 9, 2013 18:34
Show Gist options
  • Save davidchambers/6499651 to your computer and use it in GitHub Desktop.
Save davidchambers/6499651 to your computer and use it in GitHub Desktop.
FILES = (
'foo.txt',
'bar.txt',
'baz.txt',
)
def getmetadata(path):
return {'blah': True, 'quux': 42}
def getcontents(path):
with open(path, 'rb') as f:
return f.read()
import base64
import json
import urllib2
import common as _
def repr(path):
return dict(contents=base64.b64encode(_.getcontents(path)),
**_.getmetadata(path))
req = urllib2.Request('http://httpbin.org/post',
json.dumps({name: repr(name) for name in _.FILES}),
{'Content-Type': 'application/json'})
res = urllib2.urlopen(req)
print res.read()
import requests
import common as _
res = requests.post('http://httpbin.org/post',
data={name: _.getmetadata(name) for name in _.FILES},
files={name: _.getcontents(name) for name in _.FILES})
print res.text
@davidchambers
Copy link
Author

> python encoded.py
{
  "files": {},
  "json": {
    "bar.txt": {
      "blah": true,
      "contents": "YmFyCg==",
      "quux": 42
    },
    "baz.txt": {
      "blah": true,
      "contents": "YmF6Cg==",
      "quux": 42
    },
    "foo.txt": {
      "blah": true,
      "contents": "Zm9vCg==",
      "quux": 42
    }
  },
  "args": {},
  "origin": "23.24.210.193",
  "form": {},
  "data": "{\"baz.txt\": {\"blah\": true, \"contents\": \"YmF6Cg==\", \"quux\": 42}, \"foo.txt\": {\"blah\": true, \"contents\": \"Zm9vCg==\", \"quux\": 42}, \"bar.txt\": {\"blah\": true, \"contents\": \"YmFyCg==\", \"quux\": 42}}",
  "url": "http://httpbin.org/post",
  "headers": {
    "Connection": "close",
    "Content-Length": "189",
    "User-Agent": "Python-urllib/2.7",
    "Host": "httpbin.org",
    "Accept-Encoding": "identity",
    "Content-Type": "application/json"
  }
}

> python multipart.py
{
  "data": "",
  "url": "http://httpbin.org/post",
  "args": {},
  "origin": "23.24.210.193",
  "headers": {
    "User-Agent": "python-requests/1.2.3 CPython/2.7.2 Darwin/12.4.0",
    "Host": "httpbin.org",
    "Content-Length": "1004",
    "Content-Type": "multipart/form-data; boundary=35db1cc3830b4578ab16100038055833",
    "Accept": "*/*",
    "Connection": "close",
    "Accept-Encoding": "gzip, deflate, compress"
  },
  "files": {
    "bar.txt": "bar\n",
    "foo.txt": "foo\n",
    "baz.txt": "baz\n"
  },
  "form": {
    "bar.txt": [
      "blah",
      "quux"
    ],
    "foo.txt": [
      "blah",
      "quux"
    ],
    "baz.txt": [
      "blah",
      "quux"
    ]
  },
  "json": null
}

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