python发送文件_从Python脚本使用POST发送文件

是。您将使用该urllib2模块,并使用multipart/form-data内容类型进行编码。这里有一些示例代码可以帮助您入门 - 它不仅仅是文件上传,但您应该能够通读它并查看它是如何工作的:user_agent = "image uploader"default_message = "Image $current of $total"import loggingimport osfrom os.path import abspath, isabs, isdir, isfile, joinimport randomimport stringimport sysimport mimetypesimport urllib2import httplibimport timeimport redef random_string (length):

return ''.join (random.choice (string.letters) for ii in range (length + 1))def encode_multipart_data (data, files):

boundary = random_string (30)

def get_content_type (filename):

return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

def encode_field (field_name):

return ('--' + boundary,

'Content-Disposition: form-data; name="%s"' % field_name,

'', str (data [field_name]))

def encode_file (field_name):

filename = files [field_name]

return ('--' + boundary,

'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),

'Content-Type: %s' % get_content_type(filename),

'', open (filename, 'rb').read ())

lines = []

for name in data:

lines.extend (encode_field (name))

for name in files:

lines.extend (encode_file (name))

lines.extend (('--%s--' % boundary, ''))

body = '\r\n'.join (lines)

headers = {'content-type': 'multipart/form-data; boundary=' + boundary,

'content-length': str (len (body))}

return body, headersdef send_post (url, data, files):

req = urllib2.Request (url)

connection = httplib.HTTPConnection (req.get_host ())

connection.request ('POST', req.get_selector (),

*encode_multipart_data (data, files))

response = connection.getresponse ()

logging.debug ('response = %s', response.read ())

logging.debug ('Code: %s %s', response.status, response.reason)def make_upload_file (server, thread, delay = 15, message = None,

username = None, email = None, password = None):

delay = max (int (delay or '0'), 15)

def upload_file (path, current, total):

assert isabs (path)

assert isfile (path)

logging.debug ('Uploading %r to %r', path, server)

message_template = string.Template (message or default_message)

data = {'MAX_FILE_SIZE': '3145728',

'sub': '',

'mode': 'regist',

'com': message_template.safe_substitute (current = current, total = total),

'resto': thread,

'name': username or '',

'email': email or '',

'pwd': password or random_string (20),}

files = {'upfile': path}

send_post (server, data, files)

logging.info ('Uploaded %r', path)

rand_delay = random.randint (delay, delay + 5)

logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)

time.sleep (rand_delay)

return upload_filedef upload_directory (path, upload_file):

assert isabs (path)

assert isdir (path)

matching_filenames = []

file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

for dirpath, dirnames, filenames in os.walk (path):

for name in filenames:

file_path = join (dirpath, name)

logging.debug ('Testing file_path %r', file_path)

if file_matcher.search (file_path):

matching_filenames.append (file_path)

else:

logging.info ('Ignoring non-image file %r', path)

total_count = len (matching_filenames)

for index, file_path in enumerate (matching_filenames):

upload_file (file_path, index + 1, total_count)def run_upload (options, paths):

upload_file = make_upload_file (**options)

for arg in paths:

path = abspath (arg)

if isdir (path):

upload_directory (path, upload_file)

elif isfile (path):

upload_file (path)

else:

logging.error ('No such path: %r' % path)

logging.info ('Done!')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值