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
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...
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).
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
Related
i want to have a javascript file accessible using url.
like i have myfile.js and i want that file to apear on localhost:3000/myfile.js
is there any way to do that in create react app or if not how can i do that using webpack? CopyWebPackPlugin should work? by the way i want to use es module like import thing in that file so i guess i can't have it inside public folder but its fine if i get the compliled one by webpack.
or if there is some other way of doing this would be very much helpful.
I have a react app that loads data from a local json file using
import data from './data.json'
it is all working fine without any issues and I'm able to open my index.html in 3000 and also open it as simple HTML page in browser.
Now I run npm run build which creates the build directory. However, my json values become kind of stagnant as it is hardcoded in the javascript in the build. So the question is how can my code in build directory reads json files from a specific location dynamically.
My question: Why not use fetch and serve the JSON from a server side API?
To partially answer your question:
Without changing any webpack configuration, you can use the import() function, instead of import, and a chunk will be built with the json content within a js file.
async function fn() {
const json = await import("./foo.json")
document.title = json.bar
}
On the other hand, probably, webpack has a way to configure this output to be json, but for that you'll need to npm run eject or use a tool to override the webpack production config.
Apart from other alternatives, what you're looking for vanilla Javascript is called fetch API. It's possible to read from either local or remote URLs via fetch method.
As per the example you provided above, instead of doing below;
import data from './data.json'
You can make use of it like;
fetch('./data.json')
Also it works pretty same way as per any URL;
// Sample working URL example to mock some real data
fetch('https://jsonmock.hackerrank.com/api/football_competitions?year=2015')
And best part of it, the parameter fetch method accept can be modified easily since it both accepts local file path and a URL as a variable very same way;
let baseURL = 'https://jsonmock.hackerrank.com/api',
endpointToCall = 'football_competitions',
year = '2015',
URL;
URL = `baseURL/${endpointToCall}?year=${year}`;
fetch(URL);
Note: With the last example above, my point is to destructure the same API endpoint used with previous example before, via dynamic variables in order to being able to more clearer. Please let me know if it's not and you need more clarification.
What you can do it before you run the npm run build you make a request to your server to get the data.json file and then just run the npm run build when it loads. You can write a simple script for it.
For example:
#!/bin/bash
# Get the file from the server
curl https://yourServer/data.zip -o data.zip
# Unzip the file, you can also use unzip
zip -d data.json
# Move the file to the desired directory
mv data.json /yourApp/data/data.json is
# Navigate to the directory where the npm package is
cd /yourApp/
# This one is optional but you should run a test to see if the app won't crash with the new json data that you fetched
# Run tests
npm run tests
# Run the build command for React
npm run build
You can modify this script with your paths and it should work.
Summary
Get the json data with curl
Unzip it
Move it to your react app where data.json is and replace it
Run the tests (optional)
Run the build
You're done.
Hope this helps.
I am trying to call a function in a python file from a js file, I got this to work through my console, but I am now trying to implement it in a mobile app using expo.
The way I had set this up is, I have the JS file for a certain screen in my app, this then calls a function in a separate JS file, which then calls the function in the python file.
I am using the child_process module to talk to python from JS.
And as I said, this was working before I tried to export the JS function to my screen file.
index.js
export function foo(process, sentence){
const spawn = require("child_process").spawn;
const process = spawn("python3", ["./python.py", sentence]);
...
}
screen.js
*other imports
import { foo } from "./filepath..."
...
But when I run npm start I get the following error:
Failed building JavaScript bundle.
While trying to resolve module `child_process` from file `/Users/mee/Documents/GitHub/project/app/screens/screen.js`, the package `/Users/mee/Documents/GitHub/project/node_modules/child_process/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/Documents/GitHub/project/node_modules/child_process/app/screens/screen.js`. Indeed, none of these files exist:
How can I fix this?
It won't work for few reasons
child_process is part of the node standard library, it's not available in other environments like react-native or browser
even if above was not true, there is no python3 executable on your phone
python.py file from your local directory wouldn't be even uploaded to the phone because bundler is only uploading one big js file with entire js code combined + assets, python.py is neither of those.
Only solution that make sense it to rewrite that code to javascript.
Technically it's not impossible, there might be a way to do that, by compiling python interpreter for mobile platform, or using some tool that translates python code into js, but it's not something that you should consider.
I'm trying to run typed.js on my homepage for a headline. On its website it gives installation instructions for npm, bower, and grunt. I installed it via npm.
To make it accessible as a static file I added the following line to my app.js file:
app.use('/scripts', express.static(__dirname + '/node_modules/typed.js/src/'));
This works fine.
However, when it's read from the browser, I get the error mentioned in the question title.
It pertains to the first two lines of the file:
import { initializer } from './initializer.js';
import { htmlParser } from './html-parser.js';
These are two other files found in node_modules/typed.js/src.
I understand that if this file was being interpreted on the server the import command would not be an issue.
However, AFAIK I have to serve this file from the browser in order for it to be rendered at all.
How do you import code from another javascript file in the browser?
Or does this have to be interpreted on the server?
I'm not using babel or mocha or anything else when trying to deliver this file, unlike many of the other questions on this topic.
I have webpage that needs to run some computation on start up. I want to keep this computation on the server side so the client cannot access the source code. I discovered pico, a module that is supposed to be "a bridge between server-side python and client side JavaScript".
I have a simply test.py:
import pico
def hello():
return "Hello World"
My JavaScript is also simple:
pico.load("../../../test.py");
pico.main = function() {
var displayMessage = function(message){
console.log("hello2");
console.log(message);
}
test.hello(displayMessage);
}
"../../../test.py" is the relative location of the python script to the pico folder
I then run "python -m pico.server" on the command line. When I go to my web page, open inspector, and go to the console I get the error: "Uncaught SyntaxError: Unexpected token i". 'i' is presumably from the first line import. Note that this same error happens if I don't run the pico.server command.
Any help would be great, as well as suggestions for alternative methods of doing this serverside vs clientside.
I may have an answer for you, however I have not been able to replicate the same error.
pico.load does not seem to work when file extensions are included in the argument, this is due to the function being designed to load sub-modules directly (i.e. module.sub_module) as in the pico API:
pico.load(module, [callback])
Load the Python module named module. The module will be available as a global >variable of the same name.
Submodules may be loaded by using dotted notation e.g. module.sub_module
To make sure I included ".py" file extension on the pico test page I have been working on and it failed to load the module, so this may be a problem if you are using the file extension.
Another possible issue was mentioned in a comment by holderweb. In the first pico example HTML the file client.js is included in an external <script> tag, this includes the functionality required to use pico. So you must have something similar to the following tag in your index.html head section:
<script type="text/javascript" src="/pico/client.js"></script>
For more insight I would be interested in seeing what/if the server logs at command line when the error occurs, and also the contents of your index.html page. Hope this helped!