使用Lua从python脚本复制HTTP POST

时间:2013-08-08 20:44:08

标签: php python http post lua

我有一个python脚本,它成功地将文件发布到我的localhost网络服务器上运行apache< 100ms。现在,我想和Lua完全一样。我想出了一个脚本,将相同的图像发布到我的网络服务器,但需要大约24秒才能完成。在服务器上运行的php正确地接收并存储文件用于Python脚本,文件来自$_FILES数组,而对于Lua脚本,我必须复制来自{的内容{1}}流 - 同样,通过wireshark查看两个POST请求,我可以从Python脚本中看到php://input但不能从Lua看到,而只能看到几个TCP SYN& ACK帧。知道为什么我的Lua脚本缺少实际的POST(包括url),但它似乎仍然有效(但确实很慢): 一些代码如下:

的Python

7667 POST

的Lua

#!/usr/bin/python


import urllib2
import time
from binascii import hexlify, unhexlify
import MultipartPostHandler


fname="test.gif"
host = "localhost"
#host = "semioslive.com"
URI="/test.php"
#URI="/api/gateway.php"
nodemac ="AABBCC"
timestamp = int(time.time())
func="post_img"

url = "http://{0}{1}?f={2}&nodemac={3}&time={4}".format(host, URI,func,nodemac,timestamp)
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)

data = {"data":open(fname,"rb")}

#r.get_method = lambda: 'PUT'
now = time.time()
response = opener.open(url, data, 120)
retval = response.read()

if "SUCCESS" in retval:
        print "SUCCESS"
else:
        print "RESPONSE sent at "+retval
        print "             Now "+str(time.time())


print "Request took "+str(time.time()-now)+"s to return"

PHP

#! /usr/bin/lua

http = require("socket.http")
ltn12 = require("ltn12")

local request_body = ltn12.source.file(io.open("test.gif"))

local response_body = {}


http.request{
    url = "`http://localohst/test.php`",  
    method = "POST",
    headers = {
        ["Content-Type"] =  "multipart/form-data",
        ["Content-Length"] = 7333
    },
    -- source = ltn12.source.file(io.open("test.gif")),
    source = request_body,
    sink = ltn12.sink.table(response_body)
}
print(response_body[1]) --response to request

1 个答案:

答案 0 :(得分:1)

确保您的Lua脚本正在发送相同的HTTP标头。 PHP的重要部分是带有附加文件上载的表单作为“multipart / form-data”发送,并且该文件必须作为multipart mime消息正确嵌入到HTTP请求的POST主体中。

我看不出你的Lua脚本是否真的这样做了,但我认为不是。否则PHP会很高兴。