Eman S.
Eman S.

Reputation: 145

Django views to run python script

I have chatbot web application in Django framework. So far everything is working, but now, I want to run the chatbot python script using ajax and calling the view for it from the Javascript file. I have an API using REST and the view for the python script and the ajax to call that view.

view.py:

from chat.chatbot1 import main_chatbot

def run_python_script(request):
    os.system('python3 main_chatbot.py')
    return HttpResponse("OK")

index.js:

 function run_chatbot_script(){
     $.ajax({
        type: 'GET',
        url: 'http://127.0.0.1:8000/chatbot/run_python_script/',});

and the python script folder is located in the chat app inside the chatbot django project.

The problem is that the view can't find the file and this error appears:

python3: can't open file 'main_chatbot.py': [Errno 2] No such file or directory

Upvotes: 0

Views: 5948

Answers (3)

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22942

You ought to give the full path of main_chatbot.py.

The best way to do that, could be using pkg_resources.resource_filename, like this:

import pkg_resources
script_path = pkg_resources.resource_filename('chat', 'main_chatbot.py")

Where chat is the name of the package which contains your script.

To run the script, it could be a good idea to use the same Python executable as your Project's executable (your virtualenv).

Do do that, you can use sys.executable to get the Python path used by your virtualenv:

import sys
python_path = sys.executable

It is a best practice to replace os.system by subprocess.check_call, like this:

import subprocess
subprocess.check_call([python_path, script_path]

See Replacing Older Functions with the subprocess Module

Upvotes: 0

wobbily_col
wobbily_col

Reputation: 11879

Your Django application will probably have the working directory as the location your manage.py file, so it will expect the python script in the same directory.

Use the full path to the script, or the path relative to the directory where mange.py is.

so maybe something like :

os.system('python3 chat/main_chatbot.py')

or

os.system('python3 /home/user/django_project/chat/main_chatbot.py')

(The answer suggesting importing the script is probably a better way of doing it unless there is a specific need to run it as a separate process).

Upvotes: 0

If is in the same folder you should import it:

Example if is the same folder as the view.py

import .run_python_script 

Then just call the functions you want... You can also put the full path in the os.system but it doesnt seem alright...

Upvotes: 2

Related Questions