Forgot the attachment… twice. Yay for new email clients I'm not used to
import random
import StringIO

from twisted.internet import reactor
from twisted.web import client, http_headers


def _encodeForm(a, b, f):
    """
    Encodes two form values and a fake image file as multipart form encoding.
    """
    randomChars = [str(random.randrange(10)) for _ in xrange(28)]
    boundary = "-----------------------------" + "".join(randomChars)

    lines = []
    def add(name, content, isImage=False):
        header = "Content-Disposition: form-data; name={}".format(name)
        if isImage:
            header += "; filename=img.jpeg"
            header += "\r\nContent-Type: image/jpeg"
        lines.extend(["--" + boundary, header, "", content, ""])

    add("a", a)
    add("b", b)
    add("f", f.read(), isImage=True)

    lines.extend(["--" + boundary + "--", ""])
    return boundary, "\r\n".join(lines)


def send():
    f = open("1x1.jpg")
    boundary, body = _encodeForm("1", "2", f)
    producer = client.FileBodyProducer(StringIO.StringIO(body))

    headers = http_headers.Headers()
    contentType = "multipart/form-data; boundary={}".format(boundary)
    headers.setRawHeaders("Content-Type", [contentType])

    agent = client.Agent(reactor)
    d = agent.request("POST", "http://localhost:8080";, headers, producer)
    return d

if __name__ == "__main__":
    d = send()
    d.addCallback(lambda _result: reactor.stop())
    reactor.run()




cheers
lvh



On 07 Jul 2012, at 16:57, Laurens Van Houtven wrote:

> With a lot of help from idnar, the issue is resolved!
> 
> There were a few red herrings that ended up cleaning my code a lot, but 
> eventually it ended up boiling down to my MIME generating code simply being 
> busted. Fixed version attached.
> 
> Apparently this also highlighted a minor issue in twisted.web with the wrong 
> header being preferred, but I'll leave that up to the expert :)
> 
> 
> cheers
> lvh
> 

_______________________________________________
Twisted-Python mailing list
Twisted-Python@twistedmatrix.com
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

Reply via email to