First time using Gulp and I'm following a couple of tutorials that don't seem to be working quite right for me. I have a real basic project and I just want to learn how to use Gulp for standard things like JavaScript/CSS minification, image reduction, and browser sync.
When I run my watch task with Browsersync, it goes to the right URL of localhost:8000, but it shows Cannot GET / instead of rendering my page. How do I fix this so I can use Browsersync with Django?
File directory:
gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('sass', function() {
return gulp.src('polls/static/polls/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('polls/static/polls/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('browserSync', function() {
browserSync.init({
server: "mysite",
port: 8000
});
});
gulp.task('watch', ['browserSync', 'sass'], function() {
gulp.watch('polls/static/polls/scss/**/*.scss', ['sass']);
})
Just had to make another task called runserver which runs in the cmd python manage.py runserver. Put the task as one of the dependencies for Browsersync, set the proxy and port, and I was set to go.
var exec = require('child_process').exec didn't require any extra npm install. I think it's automatically built in.
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var exec = require('child_process').exec;
gulp.task('sass', function() {
return gulp.src('polls/static/polls/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('polls/static/polls/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('runserver', function() {
var proc = exec('python manage.py runserver')
})
gulp.task('browserSync', ['runserver'], function() {
browserSync.init({
notify: false,
port: 8000,
proxy: 'localhost:8000'
})
});
gulp.task('watch', gulp.series('browserSync', 'sass'), function() {
gulp.watch('polls/static/polls/scss/**/*.scss', ['sass']);
gulp.watch('polls/static/polls/scripts/**/*.js', browserSync.reload);
gulp.watch('polls/templates/**/*.html', browserSync.reload);
})
Using Gulp 4, here is a copy of my code:
const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const exec = require('child_process').exec;
gulp.task('runserver', function() {
var proc = exec('python manage.py runserver');
return new Promise(function(resolve, reject) {
console.log("HTTP Server Started");
resolve();
});
})
gulp.task('browserSync', gulp.series('runserver'), function() {
browserSync.init({
notify: false,
port: 8000,
proxy: 'localhost:8000'
});
});
gulp.task('watch', gulp.series('browserSync'), function() {
gulp.watch('polls/static/polls/scripts/**/*.js', browserSync.reload);
gulp.watch('polls/templates/**/*.html', browserSync.reload);
})
gulp.task('browserSync', ['runserver'], function() {
browserSync.init({
notify: false,
proxy: 'localhost:8000'
})
});
Related
my Nodejs server with python scripts are combined via socket.io
I can run my python scripts and call its functions it works well until I send correct data.
the problem is when the python functions got error I can not handle them in node js
I want to understand before the python Scripts crashed I don't run them
I hope could explain the problem fluently
JS
function startScripts() {
let child = spawn('python', ['-u', __dirname + '/pyScripts/' + 'config.py']);
sockets.on('connection', function (socket) {
socket.join('config');
socks = socket;
});
child.stderr.on('data', function (err) {
console.log(err.toString());
});
child.stdout.on('data', function (data) {
console.log(data.toString());
});
}
function runPyFunction(data, callback) {
sockets.to('config').emit('run', data);
const handleResponse = (res) => {
if (res) {
return callback({ 'message': res, 'status': 'ok' }, null);
}
else {
return callback(null, { 'message': 'Function or file is not found', 'status': 'failed' });
}
};
socks.removeAllListeners();
socks.on('response', handleResponse);
}
app.post('/py', (req, res) => {
let data = req.body;
let userData = {
'filename': 'test',
'function': 'multiplication',
'args':[3]
}
runPyFunction(userData, (res2, err) => {
if (res) {
console.log('here is message');
console.log(res);
res.end(JSON.stringify(res2))
} else {
console.log('here is error');
console.log(err);
}
})
})
Python Config.py
def run_function(data):
for module in globals():
if data['filename'] == module:
for function in getmembers(globals()[module], isfunction):
if data['function'] == function[0]:
print(data)
if 'args' in data:
return sio.emit('response', function[1](*data['args']))
else:
return sio.emit('response', function[1]())
# Emit false if function or file not found
return sio.emit('response', False)
test.py
import os
def multiplication(number):
return number*number*number
Problem is : how to handle Errors when python scipts Die or crash ?
on the Code Above I made a communication between node js and py scipts
I added an API '/py' I send data to it (here is Mock data) and I tell I want to execute this File.py and this function name with these args
it searches to find the exact function.
it works fine; the problem is for example on the code above I must give int variable to py function when I send String data it downs and I can not handle it with my controller in node js.
how can I understand py Errors in node js ?
I'm working on a project and I need to send image(frame) in realtime.
Server is NodeJs, and I will process this image using OpenCV in python-shell
But I don't know how to send Image through python shell, to python code..
can you tell me how to send image from nodejs to python?
var PythonShell = require('python-shell');
var options = {
mode: 'text',
pythonOptions:['-u'],
scriptPath:'C:/Users/multi/'
};
PythonShell.PythonShell.run("pycudacode.py",options,function(err){
if(err) console.log('err msg:', err);
console.log('finishied');
}
)
this is my code.
thank you.
global.pyshell = require('python-shell');
var fs = require("fs");
var data = fs.readFileSync("testimg.jpg"); // I will get video frame from the client.
var base64 = data.toString("base64");
var options = {
mode: 'text',
pythonOptions:['-u'],
scriptPath:'C:/Users/multi/'
};
shell = new pyshell.PythonShell("sendex.py",options,function(err){
if(err) console.log('err msg:', err);
console.log('finishied');
}
)
shell.send(base64);
shell.on("message", rebase64 => {
var err = null;
result = Buffer.from(rebase64, "base64");
console.log(result);
console.timeEnd("time")
fs.writeFileSync("result.jpeg",result);
});
shell.end(err=>{
if(err){
console.log(err);
}
});
I solved it and it is my code.
I want to access a python script and pass an image then wait for a json response . I should do this inside the "upload" function after getting the image.
Been searching but was not able to find a python-shell with sails. Since sails is built on top of node.js then there most be a way.
module.exports = {
fileUpload: function(req, res) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end(
'<form action="http://localhost:1337/postIts/upload" enctype="multipart/form-data" method="post">' +
'<input type="text" name="title"><br>' +
'<input type="file" name="uploadFile"><br>' +
'<input type="submit" value="Upload">' +
'</form>'
)
},
upload: function(req, res) {
var uploadFile = req.file('uploadFile')
uploadFile.upload({
saveAs: 'image.png'
}, function onUploadComplete(err, files) {
if (err)
return res.serverError(err);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files[0]
});
});
}
};
I want to pass this uploaded image to python script and wait for a json output which I will return to the client. I havent tried anything because I am not sure of the proper way of doing this.
It should be something similar to this but i dont know the proper way. of doing it in my Controller.
there should be an import python-shell somewhere, maybe before the module.export ?
var PythonShell = require('python-shell');
var courseid=req.param('courseid');
sails.log.debug(coursed);
var options = {
args: [courseid]
};
PythonShell.run('word2vec.py', options, function (err, results) {
if (err) throw err;
console.log('results: %s', results[0]);
});
return res.ok();
So far I have tried installing pythonshell then tried an import from the controller and add the codes to the upload function which calls for the .py script but I get an error, I will upload a picture of the error. And here is the new code:
import { PythonShell } from 'python-shell';
var PythonShell = require('python-shell');
module.exports = {
upload: function(req, res) {
var uploadFile = req.file('uploadFile')
uploadFile.upload({
saveAs: 'image.png',
}, function onUploadComplete(err, files) {
let options = {
mode: 'text',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: sails.config.pythonPath,
args: ['1233ID', files[0].fd]
};
PythonShell.run('main2.py', options, function(err, results) {
if (err) throw err;
console.log('results: %s', results);
});
if (err)
return res.serverError(err);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files[0].fd
});
});
}
};
see the screenshot for the error
how can i send a RPC message (based on rabbitmq)from a reactJs project in frontend to a python project in backend .
i tried to use amqplib to send my message but i think i can't use it in a browser .
any help !
this is my code :
export function callService() {
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost:8000', function (err, conn) {
console.log("gggggggg")
conn.createChannel(function(err, ch) {
var q = 'frontend';
var msg = 'Hello!';
let messsage_body="http://www.documents.sergic.com/photos/photo-location-appartement-1-piece-pontoise-95300_563687_1_101_S.JPG";
var headers={'type': 'get_similarity', 'customer': 'sergic'};
console.log('cc ', num);
ch.consume(q.queue, function(msg) {
if (msg.properties.correlationId === corr) {
console.log(' [.] Got %s', msg.content.toString());
setTimeout(function() { conn.close(); process.exit(0) }, 500);
}
}, {noAck: true});
});
}
and i want to run it in a browser by clicking on a picture !
I've set a nodejs server along with simple python script with redis-py.
I have this on my nodejs server:
var http = require('http');
var server=http.createServer(onRequest).listen(3000);
var io = require('socket.io')(server);
var redis = require('redis');
var fs= require('fs');
var sub = redis.createClient();
sub.subscribe('channel');
function onRequest(req,res){
var index;
fs.readFile('./index.html', function (err, data) {
if (err) {
throw err;
}
index = data;
res.writeHead(200,{'Content-Type':'text/html'});
res.write(index);
res.end();
});
};
var sockets=[];
io.on('connection', function(socket){
console.log('a user connected');
sockets.push(socket);
console.log(sockets.length);
sub.on('message', function(channel, message){
console.log(message);
sockets[0].emit('chat message',message);
});
io.emit('chat message', "enter nickname");
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
This is just a simple test where I've tried to find out why my messages are sent multiple times.
I've figured that sub.on('message') is fired twice for each message that I send from python. Why?
The python code is pretty simple:
import redis
r=redis.StrictRedis()
pubsub=r.pubsub()
r.publish('channel',"HHHHHHH")