passing values from node.js to python function - javascript

I have this code in Node.js
let options = req.body
PythonShell.run('./chat.py', options, function (err, results) {
console.log(results)
})
In my chat.py file, I have this:
import sys
import json
def chatFun():
options = json.loads(sys.argv[1])
print(options)
print(sys.argv[1])
return
chatFun()
When I run my code without the print(sys.argv[1]), and just put print("hello world"), it works, but then I put print(sys.argv[1]) and it gives me:
null
null
Not sure why this is happening. Could anyone share some advice.
value of options:
city: New York,
party_size: 5,
stay: hotel

Related

RTK MySql: how to split variable array into seperate entries

I have
const {data, error, isLoading } = useFetchBulkClassesQuery(something)
to pass data to MySql via this API:
fetchBulkCclasses: builder.query ({
query: (something) => {
return {
url: '/bulkclasses',
params: {
class: something
},
method: 'GET'
at the backend, I have
tyapp.get("/bulkclasses", (req, res) => {
const q = 'select * from recent where ticker in (?)'
db.query(q, [[req.query.ticker]], (err, data) => {
if(err) {return res.json(err)}
return res.json(data)pe here
it al works fine if I use a single variable, like something = 'ClassA'
But I want to use it for multiple entries like ClassA, ClassB, ClassC, ...
But it only takes the first one (or the last one depending on what I try).
What am I doing wrong? Or what haven't I tried (or what do I not know)?
I tries:
Something = ['ClassA', 'ClassB', ...] -> the thing that get passed to the backend is 'ClassA, ClassB' en and it needs to be 'ClassA', 'ClassB', ...
Something = [[ClassA], [ClassB],...] -> same result
It seemed a bit impossible to do, so I did choose the easiest solution: changing the design of my tables and update the query.

Vercel API end point for search sends back only results equal to the query term but not results that includes that term

I have written a component with react hooks, following a tutorial, that fetches result based on one field of an object that has the following structure. { id: 1, text: "Run 10 km", complete: false }
The user is supposed to search by the text of a todo task. I am using axios and I send the request to vercel.com like this:
const getToDosBasedOnQueryTerm = async (query) => {
try {
const response = await axios(`https://todos-api-nuquyjkqpx.now.sh/todos?text=${query}`);
console.log('**************************')
console.log(query);
console.log(response.data);
console.log('**************************')
return response.data;
} catch (error) {
console.log(error);
}
};
Here are all the todos: https://todos-api-nuquyjkqpx.now.sh/todos
There is a problem with this approach. It returns the results that has the exact text as in the query. So, if I search for Do, it returns 'Do' but ignores 'Do More' and 'Do Nothing'.
Is it possible to search for all the records (todos) that contain the word searched by the user?
Please help!
Thanks

Feathers-mongoose : Get by custom attribute in feathers-mongoose

I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.

Uncaught ReferenceError PouchDB

I am currently using PouchDB as my DB and I am using Cloudant for the remote service. I am currently trying to create document, however, when I invoke the function, I have errors.
May I know where did I do wrong? Could it be the URL wrong or my syntax is wrong?
Uncaught Reference Error: PouchDB is not a constructor
This is my javascript code
function pouchdb() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://example.cloudant.com/example");
window.PouchDB = db;
var doc = {
"_id": "Can123",
"name": "You123",
"occupation": "See1",
"age": 3,
"hobbies": [
"Watch 9pm show",
"chasing laser pointers",
"lookin' hella cute"
]
};
db.put(doc);
PouchDB.sync(db, remoteDB);
}
HTML code
<button onclick="pouchdb()">pouchdb</button>
Update
I changed my insert code for this set of code
function pouchdb() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://example.cloudant.com/example");
var todo = {
_id: "mittens1233",
title: "hello",
occupation: "kitten123"
};
db.put(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
The result i got back is Successfully posted a todo!, however, my cloudant dashboard still shows 0 doc. May I know why?
Remove that line
window.PouchDB = db;
I think that's the problem. Once you click the button, the global PouchDB turns the variable db, what makes it not be a constructor anymore.
If the error still continues, #gcampbell comment should be right?

What format does python read Javascript arrays?

I sending parameters to a python script that is acting as my API. One of the params is a Javascript array. When logged in python is shows up as the first index in the array.
Here is my get request using Angular JS:
$http.get(
apiBase + '/deals/timeline', {
params: {
api_key: $scope.settings.apiKey,
start_date: startDate,
interval: interval,
amount: amount,
fieldKeys: $scope.settings.fieldKeys
}
})
Here is my python code:
import config
import json
import requests
def api_deals_timeline(params):
start_date = params.get('start_date')
interval = params.get('interval')
amount = params.get('amount')
field_key = params.get('field_key')
print(field_key)
r = requests.get('url.com/?something={}&somelse={}'.format(start_date, interval))
if r.status_code == 200:
return json.loads(r.text)['data']
else:
return None
Here is the print statement for field_key in my apache logs:
[Thu Aug 14 16:23:56 2014] [error] [u'add_time', u'won_time', u'lost_time', None]
AND here is the console.log for $scope.settings.fieldKeys:
["lost", "won", "new"]
In JavaScript, you need to send this list as JSON
JSON.stringify($scope.settings.fieldKeys);
In python, you need convert the field_key javascript array to a python list. The json library can help you out with this.
json.loads(field_key)

Categories