Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import uuid, mimetypes, os
- CRLF = b'\r\n'
- TWO_HYPHENS = b'--'
- DEFAULT_FILE_CONTENT_TYPE = 'application/octeat-stream'
- class MultipartBuilder(object):
- def __init__(self, encoding='utf-8'):
- self._encoding = encoding
- self._boundary = uuid.uuid4().hex
- self._contentType = \
- "multipart/form-data; boundary={}".format(self.boundary)
- self._boundaryBytes = self.boundary.encode("utf-8")
- self._dashBoundary = TWO_HYPHENS + self._boundaryBytes
- self._separatorLine = self._dashBoundary + CRLF
- self._endBody = self._dashBoundary + TWO_HYPHENS + CRLF + CRLF
- self._body = b''
- @property
- def encoding(self):
- return self._encoding
- @property
- def boundary(self):
- return self._boundary
- @property
- def contentType(self):
- return self._contentType
- @property
- def data(self):
- return self.build()
- def _quoteEncode(self, s):
- return '"{}"'.format(s.replace('\n', '%0A').replace('\r', '%0D')\
- .replace('"', '%22')).encode(self.encoding, 'replace')
- def _addBodyPart(self, name, content, filename, contentType):
- assert isinstance(content, bytes), "must be bytes"
- self._body += self._separatorLine
- self._body += b'Content-Disposition: form-data; name=' + \
- self._quoteEncode(name)
- if filename:
- self._body += b'; filename=' + self._quoteEncode(filename)
- self._body += CRLF
- if contentType:
- self._body += \
- bytes('Content-Type: {0}'.format(contentType), 'utf-8') + CRLF
- self._body += CRLF + content + CRLF
- def addField(self, name, content):
- if isinstance(content, str):
- content = bytes(content, self.encoding, 'replace')
- self._addBodyPart(name, content, None, None)
- def addFile(self, name, filename, content=None,
- contentType=None):
- if content is None:
- fp = open(filename, 'rb')
- content = fp.read()
- fp.close()
- elif hasattr(content, 'read'):
- content = content.read()
- filename = os.path.basename(filename)
- if contentType is None:
- contentType = mimetypes.guess_type(filename)[0]
- self._addBodyPart(name, content, filename,
- contentType or DEFAULT_FILE_CONTENT_TYPE)
- def getBody(self):
- return self._body + self._endBody
- if __name__ == '__main__':
- builder = MultipartBuilder('windows-1251')
- builder.addFile("wmphoto", "Текстовый файл.txt",
- "Какой-то текст.".encode("utf-8"))
- builder.addField("Submit", "Отправить")
- requestBody = builder.getBody()
- url = "http://chilehead.us/waymarking/test_upload.php"
- from urllib.request import Request, urlopen
- req = Request(url, requestBody, {'Content-Type': builder.contentType})
- resp = urlopen(req)
- html = str(resp.read(), 'windows-1251')
- print( html )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement