2

I have a Flask app running on Heroku that connects to the Google Maps API during a request. Something like this:

client = geocoders.GoogleV3(
            client_id=self.config['GM_CLIENT_ID'],
            secret_key=self.config['GM_SECRET_KEY']
        )
client.do_geocoding(...)

Right now I am creating a new client for every request. How can I have one connection that persists across multiple requests?

Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75
  • 1
    Can't you create this client upon starting your application and just pass the client object so it can be used by the rest of your app? – idjaw Oct 12 '16 at 00:17
  • Can I? The app is actually really complicated so realistically I think I would need to make the client a global variable to get this to work. But it seems like global varibles are a bad idea in flask? (http://stackoverflow.com/questions/32815451/are-global-variables-thread-safe-in-flask) Maybe it's ok in this case because the client is read-only? If I sound confused, it's because I am... – Jesse Aldridge Oct 12 '16 at 00:25
  • Overall design practice, globals are really never good to use. However, I have no idea how your current code is structured to know what kind of refactoring nightmare you might be dealing with here :). If the code snippet you are showing is in a method, maybe you can set the client being initialized in that class, so you can simply change your client calls to use your instance client -> self.client. – idjaw Oct 12 '16 at 00:28
  • Yeah, looks like simply using a global variable works. As long as you understand that the data is local to the flask process and thread this seems to work fine. Thanks for the tips. Feel free to post an answer along these lines if you want some points. – Jesse Aldridge Oct 12 '16 at 01:01
  • All good, dude. Glad you worked it out. Good luck. Cheers! :) – idjaw Oct 12 '16 at 01:02

1 Answers1

0

Turns out it's as simple as storing the client instance in a global variable.

Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75