【问题标题】:Is it possible to access to a pickle file saved in a directory in Django views?是否可以访问保存在 Django 视图目录中的泡菜文件?
【发布时间】:2021-03-15 09:44:30
【问题描述】:

让我解释一下,这是我的问题: 为了不被数据库打扰,我在 Django 项目的一个文件夹中的 .pickle 中保存了两个机器学习模型。 然后在对应的views.py中我要打开并使用这个模型。 事实是,当我在本地运行服务器时,所有这一切都运行良好,但一旦部署在 heroku 上,就无法访​​问这些模型并且该站点无法运行。

您有什么想法,是否可以在部署后使用此方法,还是我必须将它们保存在数据库中

项目文件组织:

 main_folder >
       models_folder >
              saved_models_folder >
                     my_model.pickle (here the model that I want to open)

       app_folder >
              views.py  ( here is the file in which I try to open the .pickle model)

其实我有这段代码,但是我打开它时因为不在models文件夹中,所以无法运行。

    def open_model(file_name):
        base_dir = 'models_folder\\saved_models_folder'
        file_path = os.path.join(base_dir, file_name)
        if os.path.exists(file_path):
            print("Loading Trained Model")
            model = pickle.load(open(file_path, "rb"))

       else:
          print('No model with this name, check this and retry')
          model = None
       return model

如果有人有一点想法,我会非常感兴趣。 谢谢。

【问题讨论】:

    标签: python django pickle


    【解决方案1】:

    当然可以,但正如您所注意到的,您需要注意您所在的目录。

    您可以使用的现代Django default settings come with a BASE_DIR Path 对象:

    from django.conf import settings
    
    def open_model(file_name):
        models_folder = settings.BASE_DIR / 'models_folder' / 'saved_models_folder'
        file_path = os.path.join(models_folder, os.path.basename(file_name))
        # ...
    

    注意我添加了os.path.basename() 来包装file_name 以避免目录遍历攻击(例如,有人传入../../../secret_file 作为文件名)。

    【讨论】:

    • 谢谢你的回答,我会用的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多