Search error error invalid [closed]

0

I'm trying to make an application to query a list of zip's that I own, but when the ex: zip = 40717000 does not exist an error is displayed and I can not follow to the next table record, can anyone help please? Thanks

import requests
import json
import pyodbc

conn = pyodbc.connect("DRIVER={SQL Server};Server=54.233.154.67;database=xxxxx;uid=yyyyy;pwd=zzzz")
cursor = conn.cursor()

cursor.execute('select * from cep_sem_referencia')

for row in cursor.fetchall():

    cep = row[1]

    r = requests.get("https://viacep.com.br/ws/%s/json/" % cep)

    #try:
    if r.status_code == requests.codes.ok:

        j = json.loads(r.text)

        cep1 = j['cep']
        uf = j['uf']

        cursor = conn.cursor()

        cursor.execute("INSERT INTO endereco VALUES('%s','%s')" % (cep1, uf))

        conn.comit()

    else:
        print('cep não encontrado')

    #except Exception:

    #print('')
    
asked by anonymous 16.05.2018 / 21:48

1 answer

3

When a theoretically valid CEP (8 characters) is sent to this API (ViaCep) it will return the data or an error field with value true . When I worked with this API I had trouble handling the errors: it does not return an error status code when the zip code is not found, it returns an error object. Try to do the data processing by checking whether the returned JSON field is error .

The image below shows a request made with the CEP 40717000.

Edit:Code

importrequestsimportjsonimportpyodbcconn=pyodbc.connect("DRIVER={SQL Server};Server=54.233.154.67;database=xxxxx;uid=yyyyy;pwd=zzzz")
cursor = conn.cursor()

cursor.execute('select * from cep_sem_referencia')

for row in cursor.fetchall():

    cep = row[1]

    r = requests.get("https://viacep.com.br/ws/%s/json/" % cep)

    #try:
    if r.status_code == requests.codes.ok and 'erro' not in r.json():

        j = json.loads(r.text)

        cep1 = j['cep']
        uf = j['uf']

        cursor = conn.cursor()

        cursor.execute("INSERT INTO endereco VALUES('%s','%s')" % (cep1, uf))

        conn.comit()

    else:
        print('cep não encontrado')

    #except Exception:

    #print('')
    
16.05.2018 / 21:57