0

I have written a Python script which POSTs data to an apache webserver and the data arrives nicely in $_POST and $_FILES aray. Now I want to implement this same thing in Lua but I can't get it going yet.

My code in Python looks something like this:

    try:
        wakeup()
        socket.setdefaulttimeout(TIMEOUT)
        opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
        host = HOST
        func = "post_img"
        url = "http://{0}{1}?f={2}&nodemac={3}&time={4}".format(host, URI, func, nodemac, timestamp)
        if os.path.isfile(filename):
            data = {"data":open(filename,"rb")}
            print "POST time "+str(time.time())
            response = opener.open(url, data, timeout=TIMEOUT)
            retval = response.read()
            if "SUCCESS" in retval:
                return 0
            else:
                print "RETVAL: "+retval
                return 99
    except Exception as e:
        print "EXCEPTION time "+str(time.time())+" - "+str(e)
        return 99

The Lua code I have come up with thus far:

#! /usr/bin/lua

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

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

but this code keeps getting me this on execution:

$ ./post.lua
/usr/bin/lua: ./post.lua:17: attempt to index global 'response_body' (a nil value)
stack traceback:
        ./post.lua:17: in main chunk
        [C]: ?
reg@DesktopOffice:~$ 
stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • 1
    I'm confused, are you trying to write a client side Lua script that does the same as your Python script or are you trying to write a server side Lua script that will process the data sent by your Python script? – Paul Kulchenko Aug 06 '13 at 22:12
  • @Paul, I need to write a Lua script that does the same as the Python script, yes. – stdcerr Aug 07 '13 at 21:44

1 Answers1

1

There are several examples of sending POST data using Lua: from the author of luasocket and SO. This example works directly with files, which is very close to what you are using.

Your description of this question doesn't match the comment you provided.

Community
  • 1
  • 1
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56