Search error cep invalido

Asked

Viewed 188 times

0

I am trying to make an application to query a list of cep’s that I have, but when ex: cep=40717000 does not exist is displayed an error and I can’t proceed to the next record of the table, can anyone please help? Thank you

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('')
  • "an error is displayed", what mistake?

1 answer

3

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

The image below shows a request made with CEP 40717000.

JSON de retorno com CEP teoricamente válido (8 caracteres), mas que não existe

Edit: Code

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 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('')
  • Hello, yes colleague that’s exactly the mistake I’m having, but how do I make the program ignore and move on to the next record? thank you.

  • Thanks Vinicius helped a lot. abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.