There is a way to upload file with standard python libraries (urllib, httplib, ...) as explained at http://code.activestate.com/recipes/146306/. But that didn't worked for me for binary data. I didn't liked/tried solution explained at http://fabien.seisen.org/python/urllib2_multipart.html, so I tried with pycurl (http://pycurl.sourceforge.net/ wrapper for http://curl.haxx.se/libcurl/) because it is std. lib for php, and uploading the file is very simple (just add @<path-to-file> to post variable value). It was a little hard to find proper way because there is no such example or documentation. But I found it, and it is so simple ;)
I supply django test application which receives file that is uploaded.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # --------- upload_file.py ----------------
# upload binary file with pycurl by http post
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.URL, "http://127.0.0.1:8000/receive/")
c.setopt(c.HTTPPOST, [("file1", (c.FORM_FILE, "c:\\tmp\\download\\test.jpg"))])
#c.setopt(c.VERBOSE, 1)
c.perform()
c.close()
print "that's it ;)"
# --------------------------------
# DJANGO RECEIVE TEST APPLICATION
# --------------------------------
# --------- urls.py ----------------
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^receive/$', 'web.views.receive'),
)
# --------- web\views.py ----------------
def receive(request):
assert request.method=="POST"
print "receive.META.SERVER_PORT", request.META["SERVER_PORT"], request.POST
files = []
for multipart_name in request.FILES.keys():
multipart_obj = request.FILES[multipart_name]
content_type = multipart_obj['content-type']
filename = multipart_obj['filename']
content = multipart_obj['content']
files.append((filename, content_type, content))
import datetime
# write file to the system - add timestamp in the name
file("c:\\tmp\\%s_%s" % (datetime.datetime.now().isoformat().replace(":", "-"), filename), "wb").write(content)
fnames = ",".join([fname for fname, ct, c in files])
return HttpResponse("me-%s-RECEIVE-OK[POST=%s,files=%s]" % (request.META["SERVER_PORT"], request.POST.values(), fnames ))
|
Heh, it seems that there is documentation how to do it: http://pycurl.cvs.sourceforge.net/pycurl/pycurl/tests/test_post2.py?view=markup