I am new with this technology. Please bear with me :) Thank you
Do you have any idea on how to call a python controller function using javascript?
I always get cross-origin-browser error. So I tried this,
.py
#http.route('/custom/createdb', type='json', auth="public", methods=["POST"], website=True)
def createdb(self, db_name):
session = self._authenticate()
if not session:
return json.dumps(False)
# create a new database
headers = {'Content-Type': 'application/json'}
create_db_url = "http://localhost:8090/custom_api/create_db"
data = {"jsonrpc": 2.0, "params": { "name": db_name } }
_logger.debug("Creating database...")
r = session.post(url=create_db_url, data=json.dumps(data), headers=headers)
if r.ok:
return json.dumps(True)
else:
return json.dumps(False)
.js
var session = require('web.session');
$(function()
{
$("#start_trial").click(function()
{
session.rpc('/custom/createdb',
{
// how to get data here
}).then(function (result)
{
// result
});
});
});
just solved my own question.
var db_name = $("input[name='partner_name']").val();
session.rpc('/custom/createdb', {
db_name : db_name
}).then(function() {
console.log("Creating database");
}, function () {
console.log("calling /custom/createdb caused an exception!");
});
I just followed this documentation:
https://www.odoo.com/documentation/10.0/reference/javascript.html#low-level-api-rpc-calls-to-python-side
Related
I already have two working bots in Wikipedia, but they use different method.
Currently, I am trying to create a bot using C#. On the API documentation page, they have provided some sample codes in java, PHP, and python. But unfortunately, they haven't provided any sample code in C#. It is the only language I am familiar with.
This is the Wikimedia API:Edit documentation page. Would someone kindly convert the few words from java (or any other language) to C#?
If I could get only this code converted to C#, I can build the rest of the bot by myself.
I asked help on the relevant noticeboard(s) on the wikimedia site(s), but nobody there is familiar with C#. That's why I am now asking this outside of wikipedia.
Thanks a lot in advance
This is the java source-code:
```
/*
edit.js
MediaWiki API Demos
Demo of `Login` module: Sending post request to login
MIT license
*/
var request = require( 'request' ).defaults( { jar: true } ),
url = 'https://test.wikipedia.org/w/api.php';
// Step 1: GET request to fetch login token
function getLoginToken() {
var params = {
action: 'query',
meta: 'tokens',
type: 'login',
format: 'json'
};
request.get( { url: url, qs: params }, function ( error, res, body ) {
var data;
if ( error ) {
return;
}
data = JSON.parse( body );
loginRequest( data.query.tokens.logintoken );
} );
}
// Step 2: POST request to log in.
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( loginToken ) {
var params = {
action: 'login',
lgname: 'bot_username',
lgpassword: 'bot_password',
lgtoken: loginToken,
format: 'json'
};
request.post( { url: url, form: params }, function ( error, res, body ) {
if ( error ) {
return;
}
console.log( body );
} );
}
// Start From Step 1
getLoginToken();
I can't go so deeply but I hope you can take a look at this page and find out how to do it
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0
You can try something like this
private static async Task LoginRequest(string loginToken)
{
var data = new
{
action = "login",
lgname = "bot_username",
lgpassword = "bot_password",
lgtoken = loginToken,
format = "json"
};
using (var client = new HttpClient())
using (var response = await client.PostAsJsonAsync(LOGIN_URL, data))
{
var responseString = await response.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeObject<JObject>(responseString);
Console.WriteLine(responseObject);
}
}
private static async Task<string?> GetLoginToken()
{
var url = $"{LOGIN_URL}?action=query&meta=tokens&type=login&format=json";
using (var client = new HttpClient())
using (var response = await client.GetAsync(url))
{
var responseString = await response.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeObject<JObject>(responseString);
return responseObject?["query"]?["tokens"]?["logintoken"]?.ToString();
}
}
For converting the response you need
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
You can call these methods from your Main method like this:
const string LOGIN_URL = "https://test.wikipedia.org/w/api.php";
public static async Task Main()
{
var loginToken = await GetLoginToken();
await LoginRequest(loginToken ?? throw new Exception("No login token."));
}
I have a few codes of js which is calling from a controller in python. I am facing an error which is createdb() takes 2 arguments, 1given. May I know what should I put here in the function of my js here? I am still learning with javascript. Thank you for understanding.
.js
$(function(){
$("#start_trial").click(function(){
createDatabase();
});
});
function createDatabase(){
session.rpc('/custom/createdb', {
db_name : db_name
}).then(function() {
console.log("Database created successfully");
});
}, function () {
console.log("calling /custom/createdb caused an exception!");
});
}
.py
#http.route('/custom/createdb', type='json', auth="public", methods=["POST"], website=True)
def createdb(self, db_name):
session = self._authenticate()
if not session:
return json.dumps(False)
# create a new database
headers = {'Content-Type': 'application/json'}
create_db_url = "http://localhost:8090/cus_cus/create_db"
data = {"jsonrpc": 2.0, "params": { "name": db_name } }
_logger.debug("Creating database...")
r = session.post(url=create_db_url, data=json.dumps(data), headers=headers)
if r.ok:
return json.dumps(True)
else:
return json.dumps(False)
I’m having an issue with my project. In my angularjs controller a function is being executed and then my function to make a call to my database to update a record is executing without waiting for the first function to complete and therefore sending over an undefined result variable.
Below you can find my code snippets with my attempts so far.
Submit button function:
$scope.submitNewStarters = function () {
// result is returning as undefined <<<<< Issue
var result = $scope.sendNewStarterDetailsToApi();
$scope.updateArchivedImportFlag(result);
};
Controller function handling the logic:
$scope.sendNewStarterDetailsToApi = function () {
swal({
title: "Confirmation",
text: "Are you sure you want to import the new starter details?",
icon: "info",
dangerMode: true,
buttons: ["No", "Yes"]
}).then(function (approve) {
if (approve) {
// Get each of the new starter details that have been set to true for import.
var newStartsToImport = $scope.tableParams.data.filter(x => x.imported == true);
for (let i = 0; i < newStartsToImport.length; i++) {
// Parses the current new starter object into a stringified object to be sent to the api.
$scope.newStartsToImport = $scope.createApiObject(newStartsToImport[i]);
// A check to ensure that nothing has went wrong and that the stringify object has worked.
if ($scope.newStartsToImport !== "") {
apiFactory.postNewStarterDetailsToApi($scope.newStartsToImport).then(function (response) {
var isSuccessful = response.data.d.WasSuccessful;
if (isSuccessful)
toastr.success("New starter details successfully sent to API.", "Success!");
else {
var errorMessage = response.data.d.ErrorMessage;
toastr.error("New starter details were unsuccessfully sent to API. Please try again. \n" + errorMessage, "Error!");
}
});
}
else {
toastr("An error has occurred when attempting to create the data object to be sent to API. The process has stopped!", "Error!");
break;
}
}
return newStartsToImport;
}
else
toastr.info("No new starter details were sent to API", "Information!");
});
};
Factory function for API call:
postNewStarterDetailsToApi: function (data) {
return $http({
url: "https://www.example.com/services/service.svc/Import",
method: "POST",
data: data,
headers: {
'Content-Type': 'application/json; charset=utf-8',
}
}).then(function successCallbwack(response) {
// this callback will be called asynchronously
// when the response is available
return response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('An error has occured during the function call postNewStarterDetailsToApi(): ', response);
});
}
So with the concept of promises how am I able to execute the sendNewStarterDetailsToApi function, wait for it to complete and then return the populated array? Once the populated array (result) is returned then execute the updateArchivedImportFlag function.
Below I've added an illustration of what I'd like to achieve:
The approach I am using is , save all the promises in an array .
Use any promise library or es6 Promise, and use .all function to wait for all promises to execute
The syntax i wrote is not totally correct. Since you are using angular js , you can use $q.all
$scope.sendNewStarterDetailsToApi = function () {
swal({
title: "Confirmation",
text: "Are you sure you want to import the new starter details?",
icon: "info",
dangerMode: true,
buttons: ["No", "Yes"]
}).then(function (approve) {
var res = [];
if (approve) {
// Get each of the new starter details that have been set to true for import.
var newStartsToImport = $scope.tableParams.data.filter(x => x.imported == true);
for (let i = 0; i < newStartsToImport.length; i++) {
// Parses the current new starter object into a stringified object to be sent to the api.
$scope.newStartsToImport = $scope.createApiObject(newStartsToImport[i]);
// A check to ensure that nothing has went wrong and that the stringify object has worked.
if ($scope.newStartsToImport !== "") {
res.push(apiFactory.postNewStarterDetailsToApi($scope.newStartsToImport))
}
else {
toastr("An error has occurred when attempting to create the data object to be sent to API. The process has stopped!", "Error!");
break;
}
}
return Promise.all(res);
}
else
toastr.info("No new starter details were sent to API", "Information!");
}).then(function (data) {
data.forEach((response) => {
var isSuccessful = response.data.d.WasSuccessful;
if (isSuccessful)
toastr.success("New starter details successfully sent to API.", "Success!");
else {
var errorMessage = response.data.d.ErrorMessage;
toastr.error("New starter details were unsuccessfully sent to API. Please try again. \n" + errorMessage, "Error!");
}
})
}).then((res) => {
//call Submit new starters
})
};
I am developing a web application in Angularjs. I am making some API calls using $http service. I am using factories to call $http services. I have below controller.
(function () {
angular.module('RoslpApp').controller('SavedVechilces', ['$scope','DeleteVechicle', function ($scope,DeleteVechicle)
$scope.deletesavedCar = function (sref) {
DeleteVechicle.deleteCar(sref.CarID).success(function (resposne) { console.log(resposne) }.error(function (error) { console.log(error)}))
}
}]);
})();
RoslpApp.factory("DeleteVechicle", ['$http', '$cookieStore','cfg', function ($http, $cookieStore,cfg) {
var factoryObject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/Vehicle/DeleteSavedVehicle";
factoryObject.deleteCar = function (carID) {
var request = {
url: urlapi,
method: 'POST',
data: {
LoginID: LoginID,
CarID: carID
},
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage
},
};
return $http(request);
}
return factoryObject;
}
]);
When I run above code I will get Unknown provider: DeleteVechicleProvider <- DeleteVechicle <- SavedVechilce error. I injected DeleteVechicle in my controller. May I know the way I am CarID to the factory and returning response is the correct way? Any help would be appreciated. Thank you.
There are two issues, you need to change your controller/factory as,
RoslpApp.controller
also the request should be,
DeleteVechicle.deleteCar(sref.CarID).then(function(response){
console.log(resposne)
},function(error){
console.log(error)
});
I recently started programming on nodeJs.
I am using Angular JS, resource to call API's as
demoApp.factory('class', function ($resource) {
return $resource('/class/:classId', { classId: '#_classId' }, {
update: { method: 'PUT' }
});
});
And in Controller, I have delete method as;
// The class object, e {classId: 1, className: "Pro"}
$scope.deleteClass = function (class) {
var deleteObj = new Class();
deleteObj.classId = class.classId;
deleteObj.$delete({classId : deleteObj.classId}, function() {
growl.success("Class deleted successfully.");
$location.path('/');
},function () {
growl.error("Error while deleting Class.");
}
);
};
Using browser, I verified call goes to :
http://localhost:3000/class/1
Now in node Js, How should I extract value from Url,
In server.js
app.use('/class', classController.getApi);
In classController.js
exports.getApi = function(req, resp){
switch(req.method) {
case 'DELETE':
if (req) {
// how to extract 1 from url.
}
else {
httpMsgs.show404(req, resp);
}
break;
I have tried ,
console.log(req.params);
console.log(req.query);
But no luck.
I am seeing
console.log(req._parsedUrl);
query: null,
pathname: '/class/1',
path: '/class/1',
Any help appreciated.
This should be a get call right ? You can use angular $http service, with method as get. Replace your app.use('/class') with app.get('/class', function). Then you can use req.param('classId') to retrieve data. I think it should work.
Try updating your app.use to app.use('/class/:classId'), then try req.params.classId
Try using req.hostname as in:
`http://host/path'
Check this answer.
Tldr;
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Also read the docs on node url.