Error sending request - get.

1

Considering the code below:

path = "/admin/"
host = "192.168.1.1"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 80))

req = ("GET /"+path+" HTTP/1.1\n Host: %s \r\n\r\n", host)

s.send(req)
print(s.recv())
s.close()

I'm trying to send a simple request get but I can not. By concatenating tupla with string I get the following error message:

  

TypeError: must be string or path, not tuple

What's wrong with this code?

    
asked by anonymous 22.05.2016 / 00:59

1 answer

1

The error should occur on line s.send(req) - the socket.send method expects a string (or a buffer, not a "path" - did you transcribe the message incorrectly?).

What happens is that in the line that you create the contents of req you are not formatting the string, but creating a "tuple" - a sequence of two elements separated by "," - formatting strings using "%" uses the "%" operator between the string and the parameters, not a function call (or something like that - that's what you do there) - where the parameters are separated by ",". >

That is, re-write your line that defines req to be:

req = "GET /%s HTTP/1.1\n Host: %s \r\n\r\n" % (path, host)

instead of how it is. The string formatting syntax with "%" has been deprecated in recent years by the new way of formatting strings with the "format" method: you type a bit more, but it's a bit less light to understand and read - besides having more flexibility in advanced cases - in that case, your line would look like this (and you probably would not have gotten confused with the syntax as it happened):

req = "GET /{} HTTP/1.1\n Host: {} \r\n\r\n".format(path, host)

Note that in both cases, just as the "host" or "path" can also be passed as a parameter for formatting - the possibility of a very flexible and feature-rich string formatting is one of Python's strengths - and quas and there is never any reason to use string concatenation with "+" just to interpolate values, as you did with path - it's worth checking out the format documentation: link

Another tip: in addition to the error message, also give an indication of the line where the error occurred - the interpreter tells you what it was.

    
22.05.2016 / 06:31