2015-07-22 46 views
1

我試圖使用Python的APNS發送推送通知(我知道有很多庫可以做到這一點,但這有教育學意圖)。Python 3 struct.pack():字符格式需要長度爲1的字節對象

,我開始使用這個腳本(source):

def send_push(token, payload): 
    # Your certificate file 
    cert = 'ck.pem' 

    # APNS development server 
    apns_address = ('gateway.sandbox.push.apple.com', 2195) 

    # Use a socket to connect to APNS over SSL 
    s = socket.socket() 
    sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, certfile=cert) 
    sock.connect(apns_address) 

    # Generate a notification packet 
    token = binascii.unhexlify(token) 
    fmt = '!cH32sH{0:d}s'.format(len(payload)) 
    cmd = '\x00' 
    message = struct.pack(fmt, cmd, len(token), token, len(payload), payload) 
    sock.write(message) 
    sock.close() 

其中一期工程,但是Python 2.x的只支持TSL直到第1版。所以,我想用Python 3運行它,我得到這個錯誤:

Traceback (most recent call last): 
    File "push_notificator.py", line 52, in <module> 
    send_notification(TOKEN, json.dumps(TEST_PAYLOAD)) 
    File "push_notificator.py", line 46, in send_push 
    payload 
struct.error: char format requires a bytes object of length 1 

所以看來我必須將有效載荷轉換爲二進制,但我真的失去了。這是我第一次使用Python處理二進制數據。

回答

0

在Python 3.x的用途:

bytes(payload, "utf-8") 

utf-8替換具有必要的編碼。

希望它有幫助。

+0

感謝您的答案@cdonts。不幸的是它不起作用,我得到了同樣的錯誤:struct.error:char格式需要長度爲1的字節對象。 – Tae

+0

@Tae也許對象長度大於1或問題與'token'而不是'payload'相關。 – cdonts

+1

如果是這種情況,那麼在Python 2下運行代碼也會發生錯誤。最後,我嘗試了另一種格式:'!BH32sH%ds',但我仍然對爲什麼另一個使用Python 2而不使用Python 3感到困惑。據我所知,語法是相同的。 – Tae

相關問題