Refering to a directory in a Flask app doesn't work unless the path is absolute

后端 未结 1 1909
自闭症患者
自闭症患者 2020-11-22 05:28

I downloaded nltk data into the data directory in my Flask app. The views reside in a blueprint in another directory on the same level as the data directory. In the view I\

相关标签:
1条回答
  • 2020-11-22 05:55

    In Python (and most languages), where the code resides in a package is different than what the working directory is when running a program. All relative paths are relative to the current working directory, not the code file it's written in. So you would use the relative path nltk_data/ even from a blueprint, or you would use the absolute path and leave no ambiguity.

    The root_path attribute on an app (or blueprint) refers to the package directory for the app (or blueprint). Join your relative path to that to get the absolute path.

    resource_path = os.path.join(app.root_path, 'enltk_data')
    

    There's probably no reason to be appending this folder every time you call a view. I'm not familiar with nltk specifically, but there's probably a way to structure this so you set up the data path once when you create your app.


    project    /    app    /    blueprint
                           /    data
    
                                ^ join with root_path to get here
                    ^ app.root_path always points here, no matter where cwd is
    ^ current working directory
    
    0 讨论(0)
提交回复
热议问题