Search code examples
google-drive-apifolium

How to save folium map directly to google drive


I'm working on a script that will update automatically some folium maps in google drive daily.

I got the whole thing working correctly, locally, without issues, except for one thing: since this will be running automatically on a remote server daily, I don't want to save the created maps in the server first and then upload them to google drive. If possible, I would like to create the maps as some kind of file object in the memory, upload them to google drive, and that's it... without having to create multiple physical map files on the server. Is this possible? If yes, how?

This is my code where, after placing markers and clusters, I save the maps as html files in the file system (this is inside a cycle, as I need to update maps for several cities):

    folium.LayerControl().add_to(mymap) 
    mymap.add_child(MeasureControl()) 
    mymap.render()
    mymap.save('leads_'+city+'_'+code+'.html')

Then, for each map, this is the code for saving the html map into google drive (using pydrive):

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

file1 = drive.CreateFile({'parents': [{'id': 'xxxfolder_idxxx'}]})
file1.SetContentFile('leads_'+city+'_'+code+'.html')
file1.Upload()

As I said, this all works fine, but I don't want to saturate the server file system with map files. Is there a way to do this without having to first save the map in the local file system?


Solution

  • If you meant to directly save the html file to drive (without saving it to local), then you can try this:

    file1 = drive.CreateFile({'parents': [{'id': 'xxxfolder_idxxx'}], 'mimeType': 'text/html', 'name': 'leads_'+city+'_'+code+'.html'})
    # access the html string of the object and set it via SetContentString
    file1.SetContentString(m.get_root().render())
    file1.Upload()
    

    Reference: