Python发送form-data请求提交表单数据

最近在处理服务器接口的时候,需要使用`Python`模拟发送表单数据到服务器,搜索了一下,找到如下例子:

# encoding=utf8
import urllib
import urllib2
import httplib
import os

HOST = 'xx.xx.xx.xx'
PORT = 8000
P_ID = xx
U_NAME = 'xxx'
API_KEY = 'xxx'
API_SEC = 'xxx'
UP_APK = xx

def sign(src, key):
  HEX_CHARS = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ]
  from hashlib import sha1
  import hmac
  hashed = hmac.new(key, src, sha1)
  sv = str(hashed.digest())
  ret = ''
  for b in bytearray(sv):
    bite = b & 0xff
    ret += HEX_CHARS[ bite >> 4 ]
    ret += HEX_CHARS[ bite & 0xf ]
  return ret

def encode_multipart_formdata(fields, files):
  """
  fields is a sequence of (name, value) elements for regular form fields.
  files is a sequence of (name, filename, value) elements for data to be uploaded as files
  Return (content_type, body) ready for httplib.HTTP instance
  """
  import random
  BOUNDARY = '----------%s' % ''.join(random.sample('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ', 62))
  CRLF = '\r\n'
  L = []
  for (key, value) in fields:
    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; name="%s"' % key)
    L.append('')
    L.append(value)
  for (key, filename, value) in files:
    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
    L.append('Content-Type: %s' % get_content_type(filename))
    L.append('')
    L.append(value)
  L.append('--' + BOUNDARY + '--')
  L.append('')
  body = CRLF.join(L)
  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  return content_type, body, BOUNDARY

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

def post_apk_sign(apk_file):
  filename = os.path.basename(apk_file)
  url = 'http://' + HOST + ':' + str(PORT) + 'xxx'
  fields = [('un', U_NAME), ('p_id', str(P_ID)), ('up_type', str(UP_APK))]
  with open(apk_file, 'r') as f:
    files = [('apk_file', filename, f.read())]
  content_type, body, boundary = encode_multipart_formdata(fields, files)
  si = sign(API_KEY + str(P_ID) + str(UP_APK) + U_NAME, API_SEC)
  # print si
  req = urllib2.Request(url)
  req.add_header('api_key', API_KEY)
  req.add_header('sign', si)
  req.add_header('Content-Type', 'multipart/form-data; boundary='+boundary)
  resp = urllib2.urlopen(req, body)
  res = resp.read()
  print res

if __name__=='__main__':
  # b38d73bb278800dd3c0c3cf11ad20c106d17944c
  # print(sign(b'123test123456', b'456'))

  apk_file = 'xxx.apk'
  post_apk_sign(apk_file)

参考链接


发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注