Search code examples
pythonjsonpython-requestsocrgoogle-vision

FILE (.json) NOT FOUND


This is my directory where i have activated a virtual environment:

The directory where I have activated a virtual environment

I'm working on a flask project to create a rest API, and I have a JSON credential file (google vision file), but when I run the code it says file not found even if it's in the same directory. I've activated a virtualenv for this particular project. mainone.py is the code I'm trying to run.

This is the error I am getting:

"File {} was not found.".format(filename)
google.auth.exceptions.DefaultCredentialsError: File date_scanner.json was not found. 

And this is the code block where I am using accessing the particular file:

from flask import Flask,request,jsonify
import os,io,re,glob,base64
from google.cloud import vision
from google.cloud.vision import types
from PIL import Image

os.environ['GOOGLE_APPLICATION_CREDENTIALS']=r'date_scanner.json'
client=vision.ImageAnnotatorClient() 

Solution

  • This is likely because the "working folder" of the Python process is not the same as where the file is located. There is a small (albeit convoluted) way to generate filenames which will always work:

    1. Use __file__ to get the filename of the Python file where this is called.
    2. Strip the filename from that path using os.path.dirname
    3. Append the filename that you want to open using os.path.join
    from os.path import dirname, join
    
    
    def get_filename(filename):
        here = dirname(__file__)
        output = join(here, filename)
        return output
    

    Some food for thought

    However, in this case there is something you should be careful about: The file contains security credentials and should not live in your source code. So while the above example will solve the immediate problem, the security of this should be addressed.

    The best way for this is to externalise the filename of the credentials file into a config file. Say, for example you would use a .ini file as config file, you could have something like this in your code somewhere:

    config = configparser.ConfigParser()
    config.read('config.ini')
    vision_creds_file = config.get('google_vision', 'filename')
    

    and then place the following into config.ini:

    [google_vision]
    filename = /path/to/filename.json
    

    This still requires you to place the config.ini file somewhere which should be documented in your application, as you still cannot add this to the source code (maybe a sample file with defaults).