Problems with utf8 encoding in python

0

Error getting script:

Igetthiserrorbythenamethathas~thatreturnsfromthemysqltable.Ifthe~tableinthetabledoesnotgiveerror,ifyouput~Igetthiserror.

Myscript:

#!/usr/bin/envpython#coding:utf8importMySQLdbimportpycurlimportbase64importjsonimportdatetimedb=MySQLdb.connect(host="xxx.xxx.x.xx", user="xxxxxx", passwd="xxxxxx", db="xxxxxx", charset = 'utf8')

cursor = db.cursor()

cursor.execute("SELECT DataConsulta, Dias, HoraConsulta, HoraSaida, nome, Consulta, centrodb.LocalConsulta.Descricao, Contato FROM centrodb.RegistoConsultas LEFT OUTER JOIN centrodb.LocalConsulta ON centrodb.LocalConsulta.Id = centrodb.RegistoConsultas.'Local' LEFT OUTER JOIN centrodb.UtentesCons ON centrodb.UtentesCons.codigoutente = centrodb.RegistoConsultas.Utente LEFT OUTER JOIN centrodb.DiasSemana ON centrodb.DiasSemana.Id = centrodb.RegistoConsultas.DiaSemana")

myresult = cursor.fetchall()

for linha in myresult:
 DataConsulta = linha[0]
 Dias = linha[1]
 HoraConsulta = linha[2]
 HoraSaida = linha[3]
 nome = linha[4]
 Consulta = linha[5]
 Descricao = linha[6]
 Contato = linha[7]

 today = datetime.date.today()
 data = today + datetime.timedelta(days=7)

 if DataConsulta == data:
  if __name__ == "__main__":
   url ="https://dashboard.360nrs.com/api/rest/sms"
   usrPass = "xxxxx:xxxxxxxx"
   data = json.dumps({
   "to":[Contato],
   "from":"xxxxxxx",
   "message":"LAR. Consulta de " + Consulta + " em " + DataConsulta + " para " + nome + ". " + Descricao + ". Responda Sim/Não para o acompanhamento. ",
   "encoding":"gsm-pt"       
   })
   b64Val = base64.b64encode(usrPass)
   headers=["Accept:Application/json","Authorization:Basic %s"%b64Val]
   c = pycurl.Curl()
   c.setopt(pycurl.URL, url)
   c.setopt(pycurl.HTTPHEADER,headers)
   c.setopt(pycurl.POST, 1)
   c.setopt(pycurl.POSTFIELDS, data)
   c.setopt(pycurl.SSL_VERIFYHOST, 0)
   c.setopt(pycurl.SSL_VERIFYPEER, 0)
   c.perform()
   http_code = c.getinfo(pycurl.HTTP_CODE)
   print(http_code)
    
asked by anonymous 14.12.2018 / 15:19

1 answer

1

It looks like you're using python 2 ; This version of python automatically renders implicit conversion between bytes (which in python 2 is str ) and unicode ; This can be a serious problem for you, since the json module asks for unicode and you are passing bytes .

One way to work around is to work with unicode everywhere:

data = json.dumps({
    u"to": [Contato],
    u"from": u"xxxxxxx",
    u"message": u"LAR. Consulta de {} em {} para {}. {}. Responda Sim/Não para o acompanhamento. ".format(
        Consulta, DataConsulta, nome, Descricao),
    u"encoding": u"gsm-pt"       
})

This u before strings tells python 2 that they must be unicode objects and not str

This way you will be passing unicode to json.dumps() and it will not give you any more problems.

    
14.12.2018 / 18:03