3

Whenever I run the below code in Python 3 I get a syntax error invalid syntax. The reason for this I assume is because print in python 3 has different syntax.

import sys
from urllib.request import urlopen
from urllib.request import Request
import json

request = Request(
    "https://gcm-http.googleapis.com/gcm/send",
    dataAsJSON,
    { "Authorization" : "key="+MY_API_KEY,
      "Content-type" : "application/json"
    }
)

print urlopen(request).read()

however, when I change my last line to

result = urlopen(request).read()

I get the following error:

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

2
  • Python 3 print is a function so use it as print(). Try converting your string into bytearray using ba = urlopen(request).read().encode('latin1') Commented Sep 29, 2017 at 10:43
  • @Vinny still the same error Commented Sep 29, 2017 at 10:48

1 Answer 1

3

Convert your data to byte string before creating request object.

dataAsJSON = dataAsJSON.encode()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.