This is from a homework question but I'm not too familiar with Python and couldn't find any information on what is going on in the statements below.
message = connectionSocket.recvfrom(1024)
filename = message.split()[1]
f = open(filename[1:])
So, message is just taking the data from the client connected to connectionSocket and putting it in message. From there I can tell that the message is split which means its taking the string in message and returning a list of words (which I'm guessing the delimiter is just a space). But what is that [1]?
It's supposed to be a webserver so I'm thinking of a scenario such as if I go to serverAddress:serverPort/HelloWorld.html the message is the 'HelloWorld.html" part, right? and then I am opening the file. But I'm lost on the purpose of [1] and [1:].
filename = message.split()[1]
You guessed (correctly) that the string in message
is split and returned as a list of words.
If this is a HTTP request, then the first 1024 bytes of message
will be something like:
"GET /file.html cruft..."
or "GET /path/file.html cruft..."
.
By split
ting this string you generate a list beginning:
["GET", "/file.html", "cruft..."]
.
The [1] denotes the element indexed [1] within the list, ie the second element, the first index position being [0]. So filename
= "/file.html"
or = "/directory/subdirectory/file.html"
f = open(filename[1:])
This slices whatever is in filename
, again using the indices. [1:] returns every element of filename
from [1] to the end. If the assumptions above are right, then it'll discard the leading /
and allow the file to be opened.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.