Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encode a string to bytes in the send method of a socket connection in one line?

In Python 3.5, using sockets, I have:

message = 'HTTP/1.1 200 OK\nContent-Type: text/html\n\n'
s.send(message.encode())

How can I do that in one line? I ask because I had:

s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')

but in Python 3.5 bytes are required, not a string, so this gives the error:

builtins.TypeError: a bytes-like object is required, not 'str'

Should I not be using send?

like image 948
johnny Avatar asked Jan 29 '16 19:01

johnny


People also ask

How do you convert strings to bytes?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.

Is the socket object we will use to send and receive data?

The pair (conn, address) is the return value pair of this method. Here, conn is a new socket object used to send and receive data on the connection and address is the address bound to the socket.


1 Answers

str, the type of text, is not the same as bytes, the type of sequences of eight-bit words. To concisely convert from one to the other, you could inline the call to encode (just as you could with any function call)...

s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode())

.. bearing in mind that it's often a good idea to specify the encoding you want to use...

s.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode('ascii'))

... but it's simpler to use a bytes literal. Prefix your string with a b:

s.send(b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')

But you know what's even simpler? Letting someone else do HTTP for you. Have you thought about using a server such as Flask, or even the standard library, to build your app?

like image 113
Benjamin Hodgson Avatar answered Sep 28 '22 03:09

Benjamin Hodgson