首页 > 解决方案 > Django + Cython 在 django 应用程序视图中导入 cython 模块

问题描述

django 和 Cython 的新手。我正在 django 中创建一个应用程序,需要从 cythonized 模块导入 views.py 中的函数。以下是我的应用程序中的views.py。

from django.shortcuts import render
import sys
import numpy as np
import random
import math
from cython_node_val import node_val

def home(request):
    return render(request,'Home.html',{"name":"user"})

def shortest_path1(request):

    K=int(request.POST['number of layers'])
    if ((K%2!=0) or (K < 0)):
        return render(request,"shortest_path1.html",{'shortest_path1':"K must be an even integer"})
    else:
    ......
        
    Node_val=node_val(Hash,C,K) #node_val is from cython_node_val which is a .pyx file, Hash C and K 
                                are defined in body after else statement.  

    sPath=np.zeros((K,3))
    sPath[K-1,:]=Node_val[n-1,:]
    for m in range(K-2,-1,-1):
             sPath[m,:]=Node_val[int(sPath[m+1,1])]
    return render(request,"shortest_path1.html",{'shortest_path1':sPath[:,3]})'''

我的项目目录如下: 项目目录 Django

我的应用程序目录看起来像这样 app 目录,其中突出显示了内置的 cython 代码和支持文件

cython_node_val.pyx 在导入普通的 .py 文件时工作正常,但是在我的应用程序中执行相同的内部 views.py 时,它会抛出以下错误

File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\urls.py", line 9, in <module>
    from . import views
  File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\views.py", line 6, in <module>
    from cython_node_val import node_val
ModuleNotFoundError: No module named 'cython_node_val'

我相信如果 views.py 是一个 python 文件并且我们可以进行操作,它应该拉 cython_node_val 和相关函数。我哪里错了?

谢谢你的时间。

标签: djangocython

解决方案


使用 os.getcwd() 从脚本views.py 调试您正在运行的位置:

import os
print(os.getcwd()) 

ModuleNotFoundError: No module named 'cimport'

然后根据需要调整路径

当您尝试引用不在 python 运行路径脚本中的内容 + 您在脚本中提供的路径时,通常是一个错误。


推荐阅读