Django+Cython import cython module in django app views [duplicate] - django

This question already has an answer here:
Python Package "No module named..."
(1 answer)
Closed 2 years ago.
a newbie to django and Cython. I am creating an app in django and need to import function in views.py from cythonized module. following is views.py inside my app.
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]})'''
the directory of my project is like following:
my app directory looks like this
cython_node_val.pyx works fine when importing into a normal .py file, but when doing the same inside views.py in my app it throws me following error
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'
I believe if views.py is a python file and we can do operations, it should pull cython_node_val and associated functions. Where am i wrong?
Thanks for your time.

Use os.getcwd() to debug where you are running from your script views.py:
import os
print(os.getcwd())
ModuleNotFoundError: No module named 'cimport'
Then adjust the path to your needs
Is usually an error when you are trying to reference something that isn't in the python running path script + the path that you are giving inside your script.

Related

I just setup python django and Im unable to import

I just finished installing Python and Django. I followed everything in a tutorial video and I wrote the most simple code:
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
return HttpResponse("<h1>Hello world!</h1>")
I imported it to the URL and it works as expected but the problem is I get this error:Unable to import I don't know why it is saying this because it works well. what is wrong with the program?
And I have the same import problem on other files too.

ModuleNotFoundError for model class in django

I ran into the following ModuleNotFoundError error.
File "C:\django-project\CodingWithMitchBlog\demoproject\Blog\api\urls.py", line 3, in <module>
from demoproject.Blog.api.views import api_detail_BlogPost_view
ModuleNotFoundError: No module named 'demoproject.Blog'
'Blog' is my appname.
This is my project structure.
This might be due to incorrect import statements used in the files. If the import statements has the projectname prefixed try removing it and run again.
For example change:
from demoproject.Blog.models import ModelClass
to
from Blog.models import ModelClass
in the urls.py file

Flask Application returning ImportError: No module named user_auth.views

I'm in the beginning stages of a Flask application. The problems I'm having is that whenever I attempt to run the application I get:
app/application/___init___.py, line 11 in <module>
from user_auth.views import auth
ImportError: No module named user_auth.views
I have no idea what the problem is. The import for the home.view did this as well, then it stopped and worked fine on the local server. Been trying to figure this out for the longest, there aren't that many moving parts in the application as of yet, so not sure why this is happeninng. File structure and code below:
|app
|-application
|--__ init __.py
|--home
|--user_auth
|----forms.py
|----views.py
|----templates
|----static
My application/__ init __.py file:
from flask import Flask
app = Flask(__name__)
app.config.from_object('_config')
from home.views import home
from user_auth.views import auth
app.register_blueprint(home)
app.register_blueprint(auth)
My application/user_auth/views.py
from flask import Blueprint
auth = Blueprint('auth', __name__,
url_prefix='/user_auth',
template_folder='templates',
static_folder='static')
You're missing an __init__.py file under ./user_auth/ to make user_auth a module.
There's more information about modules in the docs.

Shelve import module error python 2.7

I try to import a custom Class Instance that I shelved but I am getting an:
Import Error: No module named MyModule
All my python modules are located within a directory that contains __init__.py
Here is my puttoshelve.py template to perform the shelve:
from MyModule import MyModule
import shelve
import copy
mymodule = MyModule()
cmymodule = copy.deepcopy(mymodule)
pathtomyshelve ="/some/path/shelve"
cshelve = shelve.open(pathtomyshelve)
cshelve['object'] = cmymodule
cshelve.close()
this actually perform a shelve. If I run an ipython session within the same import shelve and:
from MyModule import MyModule
import shelve
pathtomyshelve ="/some/path/shelve"
shelve_p = shelve.open(pathtomyshelve)
obj = shelve_p['object']
obj
then I get:
{'object': <MyModule.MyModule object at 0x2139510>}
BUT
When I use my outofshelve.py to retrieve my object, which is basically the same code that I ran from the ipython console, I receive:
Import Error: No module named MyModule
What am I missing here? (complete error below)
File "/home/pierre/.qgis2/python/plugins/sig40/sig40_ZR_dialog.py", line 100, in __init__
self.mymodule = shelve_p['object']
File "/usr/lib/python2.7/shelve.py", line 122, in __getitem__
value = Unpickler(f).load()
File "/usr/lib/python2.7/dist-packages/qgis/utils.py", line 454, in _import
mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named MyModule
I had he same Problem when i tried to use my own Logwriter.
I found that solution. (But it is python 3. so the code may change a bit)
cDir = os.path.dirname(os.path.abspath("logWriter.py"))
sys.path.append(os.path.dirname(cDir))
import logClasses.logWriter as log
My Folder Structure is like that
logClasses
init.py
logWriter.py
mailClasses
init.py
sendMail.py <-- This uses the logWriter.py
I hope that solution work for you like it did for me

Calling a model's method from outside Django

I have a Django model with some static methods. I'd like to call the methods from outside the application (cronjob).
The model I have:
class Job(models.Job):
#Irrelevant information
#staticmethod
def methodIwantToCall():
#statements
I have the following python file that I'm using for the cron job:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from myapp.models import Job
Job.methodIwantToCall()
At first, I was having an error about DJANGO_SETTINGS_MODULE not being set and I fixed that, however, now I have the following error: No module named myapp.utils
I feel like I'm doing something that I'm not supposed to do. So how do I call that static method the way I want it to be called?
EDIT: It looks like the paths are getting messed up when I'm importing from outside Django. For example, I have an import in my models file, when I call the cron file it fails importing with the message ImportError: No module named myapp.utils even though it's working.
The proper solution is to create custom manage.py command.
Assuming your cron job code resides in the same directory as your settings file, use the following setup code at the beginning:
from django.core.management import setup_environ
import settings
setup_environ(settings)