twisted-Uploading a File

本文介绍如何利用Twisted库中的client模块实现POST请求,验证HTML文件的正确性,并通过临时文件展示验证结果。
from twisted.web import client

import os, tempfile, webbrowser, random



def encodeForm(inputs):

    """

    Takes a dict of inputs and returns a multipart/form-data string

    containing the utf-8 encoded data. Keys must be strings, values

    can be either strings or file-like objects.

    """

    getRandomChar = lambda: chr(random.choice(range(97, 123)))

    randomChars = [getRandomChar( ) for x in range(20)]

    boundary = "---%s---" % ''.join(randomChars)

    lines = [boundary]

    for key, val in inputs.items( ):

        header = 'Content-Disposition: form-data; name="%s"' % key

        if hasattr(val, 'name'):

            header += '; filename="%s"' % os.path.split(val.name)[1]

        lines.append(header)

        if hasattr(val, 'read'):

            lines.append(val.read( ))

        else:

            lines.append(val.encode('utf-8'))

        lines.append('')

        lines.append(boundary)

    return "\r\n".join(lines)



def showPage(pageData):

    # write data to temp .html file, show file in browser

    tmpfd, tmp = tempfile.mkstemp('.html')

    os.close(tmpfd)

    file(tmp, 'w+b').write(pageData)

    webbrowser.open('file://' + tmp)

    reactor.stop( )



def handleError(failure):

    print "Error:", failure.getErrorMessage( )

    reactor.stop( )



if __name__ == "_ _main_ _":

    import sys

    from twisted.internet import reactor



    filename = sys.argv[1]

    fileToCheck = file(filename)

    form = encodeForm({'uploaded_file': fileToCheck})

    postRequest = client.getPage(

        'http://validator.w3.org/check',

        method='POST',

        headers={'Content-Type': 'multipart/form-data; charset=utf-8',

                 'Content-Length': str(len(form))},

        postdata=form)

    postRequest.addCallback(showPage).addErrback(handleError)

    reactor.run( )


Run validate.py with the name of an HTML file as the first argument:

    $ python validate.py test.html

使用client.getPage可以post表单数据
 关于file函数
file ( filename [, mode [, bufsize ] ] )

Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值