Page 1 of 1

From two addresses, get distance and route summary - using google api.

Posted: Sat Aug 11, 2018 12:19 am
by fangis
Hi
This script uses google api,
it gets two addresses as input and retrieves the distance in Km and a summary of the route.
It is started by the start() function.

Code: Select all


import socket
def start():
    found = 0
    origem = input("origem:")
    origem = origem.replace(" ",",")
    destino = input("destino:")
    destino = destino.replace(" ",",")
    a = socket.getaddrinfo("googleapis.com", 80)
    a = a[0][-1]
    s = socket.socket()
    s.connect(a)
    s.sendall("GET /maps/api/directions/json?origin=")
    s.sendall(origem)
    s.sendall("&destination=")
    s.sendall(destino)
    s.sendall("&sensor=false")
    s.sendall("\r\n\r\n")
    while True:
      try:
        linha = str(s.readline(), 'utf8')
        if "km" in linha:
          if found == 1: continue
          print(linha.split('"')[3])   
          found = 1
        elif "ummary" in linha:
          print(linha.split('"')[3])
          s.close()
          break     
      except:
        print("Exception.\r\n")
        s.close()
        break         

The script usually works. However, for bigger distances, the large reply by google api causes a memory error and the exception gets called.
A simpler way using urequests is what I have tried first, but it gets even more memory errors.
Do you know how to improve the code and make it work? If so, please show it.

thanks

Re: From two addresses, get distance and route summary - using google api.

Posted: Sat Aug 11, 2018 3:44 am
by pythoncoder
I would try forcing a garbage collect on each iteration of the loop:

Code: Select all

import socket
import gc
# code omitted
    while True:
      gc.collect()
      try:
        linha = str(s.readline(), 'utf8')

Re: From two addresses, get distance and route summary - using google api.

Posted: Sat Aug 11, 2018 11:48 pm
by fangis
Thanks for the reply, pythoncoder.

I tried it and it seemed to work, but then I realized I was still getting the exceptions sometimes.
I started to wonder, and was even going to ask you, what really cause these memory errors since the data is being sent line by line, how then would this possibly flood the memory? Then I thought, maybe one single line is causing the error. This seemed to be the answer.
It seems some of the lines sent by google are quite large, possibly causing the crashes.
I searched more about the readline method and found that I can do the following:

Code: Select all

s.readline(200)
which has made the script much more stable! it's now working even without the gc collect.