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 !
Related
I am sending the message from a Python script as follows.
import firebase_admin
from firebase_admin import credentials, messaging
# initializations
cred = credentials.Certificate('Full path to firebase-admin-sdk.json')
print('Connecting...')
firebase_admin.initialize_app(cred)
registration_tokens = [
'valid_registration_token_from_client',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
tokens = registration_tokens
)
response = messaging.send_multicast(message)
print('{0} messages were sent successfully.'.format(response.success_count))
After executing the above code, it prints 1 message sent successfully. I looked at my Firebase console and found that the number of sent notifications increased by 1. However, my React Js client does not seem to receive the message.
In react app,
Root public folder has firebase-messaging-sw.js file,
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";
import { onBackgroundMessage } from "firebase/messaging/sw";
const firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "FIREBASE_APP_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
In App.js,
import React, {Component} from "react";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
export default class App extends Component {
constructor(props) {
super(props);
this.connectButtonPressed = this.connectButtonPressed.bind(this);
}
render() {
return (
<div><button onClick={this.connectButtonPressed}>Click</button></div>
)
}
connectButtonPressed(e) {
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve a registration token for use with FCM.
// Get registration token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
});
getToken(messaging, { vapidKey: 'VAPID_KEY_FROM_CONSOLE' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log('currentToken: ', currentToken);
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
} else {
console.log('Unable to get permission to notify.');
}
});
}
}
The client can successfully request for and receive the registration token to which I send the message from the Python script. However, the onMessage event is not being triggered which makes me think that the client might not be receiving the message even though I sent the message to the token associated with this client.
What might be the issue here? What am I missing?
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 very new to nodejs what I try to do is upload an image with some data to nodejs API but before saving data to Mongo DB I try to do some process to this uploaded image using Python class then I will save the results to DB
so can I send uploaded image to python code and waite the result before saving any data to DB
my code is here
router.post('/img2text', upload.single('photo'), (req, res) => {
// Create the object for insertion into database
const Img2text = new img2text({
imgPath: req.file.path,
sender: req.body.sender,
processed: 0,
resultText: "no result",
});
/////////////////////////////////////////////////////////////start
var exec = require("child_process").exec;
exec(`python uploads/hello.py ${req.file.path}`,(error, stdout, stderr) => {
if (error) {
Img2text.processed=0;
Img2text.resultText='no result'
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
Img2text.processed=1;
Img2text.resultText=stdout.toString('utf8');
console.log(`stderr: ${stderr}`);
console.log(req.query.firstname);
});
/////////////////////////////////////////////////////////end
// Save into database
Img2text.save((err) => {
// Check if error
if (err) {
res.json({ success: false, message: err });
} else {
console.log("img saved !!")
res.json({ success: true, message:img.resultText }); // Return success message
}
});
});
if the python code takes so long time my object will be empty?
any answer will be greatly appreciated
Have you tried to use Promise,If not refer this link Promise MDN. Just wrap your process in a Promise and when you finish with your process resolve it and save it to database.
router.post('/img2text', upload.single('photo'), (req, res) => {
// Receive your image
let pythonProcess = new Promise((resolve, reject)=>{
// do your process
reolve() // resolve with updated data
})
pythonProcess.then(img =>{
//save to db
})
})
Now In Your case best possible, I prefer is to use aync/await Async/await MDN. Do not take it as another way to do it, It is just modern way to use promise. As internally await also setup promise chain. You have both options, either you can go it through promises you will get handy to the one of the best thing of javascript or If you want small piece of code go with await.
router.post('/img2text', upload.single('photo'), async(req, res) => { // To use await function need to be a async function
// Create the object for insertion into database
const Img2text = new img2text({
imgPath: req.file.path,
sender: req.body.sender,
processed: 0,
resultText: "no result",
});
/////////////////////////////////////////////////////////////start
var exec = require("child_process").exec;
await exec(`python uploads/hello.py ${req.file.path}`,(error, stdout, stderr) => {
if (error) {
Img2text.processed=0;
Img2text.resultText='no result'
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
Img2text.processed=1;
Img2text.resultText=stdout.toString('utf8');
console.log(`stderr: ${stderr}`);
console.log(req.query.firstname);
});
/////////////////////////////////////////////////////////end
// Save into database
Img2text.save((err) => {
// Check if error
if (err) {
res.json({ success: false, message: err });
} else {
console.log("img saved !!")
res.json({ success: true, message:img.resultText }); // Return success message
}
});
});
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'
})
});
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")