Ncast telepresenter reference manual – NCast Telepresenter M4 User Manual
Page 98
NCast Telepresenter Reference Manual
content_type, data = encode_multipart_formdata(fields)
# upload
print 'ncgo: uploading image(s)'
url = 'http://%s/api.cgi' % server
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='NCast Telepresenter', uri=url, user=username, pass-
wd=password)
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
request = urllib2.Request(url, data)
request.add_header('Content-Type', content_type)
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, msg:
print "ncgo: Urllib2 HTTP Error (%s)" % msg
sys.exit(1)
except socket.error, (errno, strerror):
print "ncgo: Socket error (%s) for host %s (%s)" % (errno, host, strerror)
sys.exit(1)
print 'ncgo: finished'
def encode_multipart_formdata(fields):
boundary = mimetools.choose_boundary()
lines = []
for key in fields:
if isinstance(fields[key], dict):
entry = fields[key]
else:
entry = {'value': fields[key]}
lines.append('--' + boundary)
if 'filename' in entry:
lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key,
entry['filename']))
else:
lines.append('Content-Disposition: form-data; name="%s"' % key)
if 'content-type' in entry:
lines.append('Content-Type: %s' % entry['content-type'])
lines.append('')
lines.append(entry['value'])
lines.append('--' + boundary + '--')
lines.append('')
body = '\r\n'.join(lines)
content_type = 'multipart/form-data; boundary=%s' % boundary
return (content_type, body)
def get_content_type(filename):
type = mimetypes.guess_type(filename)[0]
if type is None:
type = 'application/octet-stream'
return type
if __name__ == '__main__':
main()
NCast Corporation
Revision 2.2
Page 98