[英]How to import pickled python object into Django view.py file
This file runs perfectly well on its own:该文件本身运行良好:
import pickle
with open('model.obj', 'rb') as f:
model = pickle.load(f)
print(model)
But what I really want to do is to use model, which is a very large stored python dictionary, in my Django views.py file, like so:但我真正想做的是在我的 Django views.py 文件中使用 model,这是一个非常大的存储 python 字典,如下所示:
from django.shortcuts import render
from modeler.load_model import model
def page(request):
return render(request, 'page.html', {'model':model})
However, when I try this, I get the error below:但是,当我尝试这个时,我收到以下错误:
File "C:\Users\mmm\PycharmProjects\MyProject\modeler\load_model.py", line 3, in <module>
with open('model.obj', 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'model.obj'
I don't understand why, because if I run the first file directly it works fine - the only extra step here is importing it into views.py (I tried including the entire load_model.py code within views.py at first, but got this error, so then tried it in this separate file and it worked on its own, so obviously the issue is that I don't know how to correctly load/import my python model objects or files within Django.我不明白为什么,因为如果我直接运行第一个文件,它工作正常 - 这里唯一的额外步骤是将其导入views.py(我首先尝试在views.py中包含整个load_model.py代码,但得到了这个错误,所以然后在这个单独的文件中尝试它并且它自己工作,所以显然问题是我不知道如何正确加载/导入我的 python model 对象或 ZEF0F93C83E374876A61DA0D4D16F 中的文件。
I found the answer, Apparently.我找到了答案,显然。 all I had to do was to put the absolute path to 'model,obj' in my open statement, not just the relative path: like this:
我所要做的就是在我的开放语句中放入“模型,obj”的绝对路径,而不仅仅是相对路径:像这样:
with open('C:\\Users\\mmm\\PycharmProjects\\MyProject\\modeler\\model.obj', 'rb') as f:
model = pickle.load(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.