axios post for multiple data with flask and vuejs - flask

All I want to do is get context_answers and treatment_answers from my web user inputs and bring it on the Flask. (I am very new to this, sorry that I am a vague about what I am doing)
`context_answers = {"a":[1], "b":[2], "c":[3], "d":[4]}
treatment_answers = {"y":[10]}`
I was able to get context_answers doing following:
`methods: {
handleSubmit() {
axios.post("/submit_survey", this.context_answers)
}
}`
and on the Flask
`#app.route("/submit_survey", methods=["POST"])
def submit_survey():
context = request.get_json(force=True)
context_df = pd.DataFrame.from_dict(context)`
But how do you get this.treatments_answers in the same axios post method? and in the submit_survey?
I want to create a data frame that has following:
a b c d y
1 2 3 4 10
Thank you so much!

If do you want past many params you can do this:
methods: {
handleSubmit() {
axios.post("/submit_survey", {context_answers: this.context_answers,
treatments_answers: this.treatments_answers})
.then(
(response) => { console.log(response) },
(error) => { console.log(error) }
)
}
}
or try this:
methods: {
handleSubmit() {
axios.post("/submit_survey", {context_answers: this.context_answers,
treatments_answers: this.treatments_answers})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
}

Related

string data can't be updated without changing the image in vue js

I have a problem with updating data using vue js as the frontend and django as the backend
when updating the data with the data image is changed successfully. but when updating data without an image with an error.
i've fire test using postman and managed to update data without changing image. please find a solution
this is the method for updating the data
ubah() {
let datapengajarstaf = new FormData();
datapengajarstaf.append("nama", this.datapengajarstaf.nama);
datapengajarstaf.append("nip", this.datapengajarstaf.nip);
datapengajarstaf.append("jobs", this.datapengajarstaf.jobs);
datapengajarstaf.append("picture", this.gambar);
_.each(this.datapengajarstaf, (value, key) => {
datapengajarstaf.append(key, value);
});
axios
.put("http://127.0.0.1:8000/api/Detailpengajarstaff/"+this.id, datapengajarstaf,
{
headers: {
"Content-Type":"multipart/form-data"
}
}
)
.then(response => {
this.$router.push("/indexpengajarstaff");
this.$q.notify({
type: "positive",
message: `Data berhasil ditambah.`
});
})
.catch(err => {
if (err.response.status === 422) {
this.errors = [];
_.each(err.response.data.errors, error => {
_.each(error, e => {
this.errors.push(e);
});
});
}
});
}
this is for form-data when the data is updated

How to test async function with axios?

I need to test async function using mocha.
Tried to test function that returns Promise from axios. Looked through many examples with axios-mock-adapter to solve my issue. BUT: axios sends REAL request, not mock as expected.
describe ('login sendRequest', () => {
let sandbox = null;
before(() => {
sandbox = sinon.createSandbox();
});
after(() => {
sandbox.restore();
});
it('should create and return REST promise', done => {
const mockAdapter = new MockAdapter(axios);
const data = { response: true };
mockAdapter.onAny('http://google.com').reply(200, data);
const requestParams = {
method: 'post',
url: 'http://google.com',
data: {},
adapter: adapter,
};
logic.sendRequest(requestParams).then(response => {
console.log(response);
done();
}).catch(err => {
console.log(err);
});
});
});
logic.js
export async function sendRequest(requsetParams) {
return await requestSender.request(requsetParams);
}
Expected to get 200 response and mock data that was set before. Why I don't get the response I need? May someone help?

Mock axios with axios-mock-adapter get undefined resp

I created an axios instance ...
// api/index.js
const api = axios.create({
baseURL: '/api/',
timeout: 2500,
headers: { Accept: 'application/json' },
});
export default api;
And severals modules use it ..
// api/versions.js
import api from './api';
export function getVersions() {
return api.get('/versions');
}
I try to test like ..
// Test
import { getVersions } from './api/versions';
const versions= [{ id: 1, desc: 'v1' }, { id: 2, desc: 'v2' }];
mockAdapter.onGet('/versions').reply(200, versions);
getVersions.then((resp) => { // resp is UNDEFINED?
expect(resp.data).toEqual(versions);
done();
});
Why resp is undefined?
Two things to try here:
Maybe you already have this elsewhere in your code, but be sure to set up mockAdaptor:
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mockAdapter = new MockAdapter(axios);
I haven't found a way to get the mock adapter working when the function you are testing uses 'axios.create' to set up a new axios instance. Try something along the lines of this instead:
// api/index.js
const api = {
get(path) {
return axios.get('/api' + path)
.then((response) => {
return response.data;
});
}
}
export default api;
For anyone still struggling with this.
You need to make sure you iniatilise your MockAdapter outside a test body.
ie.
❌ Incorrect ❌
it('should do a thing', () => {
const mockAdapter = new MockAdapter(axios);
})
✅ Correct ✅
const mockAdapter = new MockAdapter(axios);
it('should pass' () => {})
according to James M. advice, I updated my api/index.js , not using the axios.create...
api/index.js
import http from 'axios'
export default {
fetchShoppingLists: () => {
console.log('API FETCH SHOPPINGLISTS')
return http
.get('http://localhost:3000/shoppinglists')
.then(response => {
return response
})
.catch(error => {
console.log('FETCH ERROR: ', error)
})
}
}
You don't need axios-mock-adapter. Here is how I mock my axios:
// src/__mocks__/axios.ts
const mockAxios = jest.genMockFromModule('axios')
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios

How to test Promise catch with Mocha

I'm trying to test the GET HTTP method from a requests module:
const get = (host, resource, options) => {
...
return new Promise((resolve, reject) => fetch(url, opts)
.then(response => {
if (response.status >= 400) {
reject({
message: `[API request error] response status: ${response.status}`,
status: response.status });
}
resolve(response.json());
})
.catch(error => reject(error)));
};
And here is how I tested the .then part:
it('Wrong request should return a 400 error ', (done) => {
let options = { <parameter>: <wrong value> };
let errorJsonResponse = {
message: '[API request error] response status: 400',
status: 400,
};
let result = {};
result = get(params.hosts.api, endPoints.PRODUCTS, options);
result
.then(function (data) {
should.fail();
done();
},
function (error) {
expect(error).to.not.be.null;
expect(error).to.not.be.undefined;
expect(error).to.be.json;
expect(error).to.be.jsonSchema(errorJsonResponse);
done();
}
);
});
However I didn't find a way to test the catch part (when it gives an error and the response status is not >= 400).
Any suggestions?
It would also help me solve the problem a simple example with another code that tests the catch part of a Promise.
I've ended up writing the following code in order to test the catch:
it('Should return an error with invalid protocol', (done) => {
const host = 'foo://<host>';
const errorMessage = 'only http(s) protocols are supported';
let result = {};
result = get(host, endPoints.PRODUCTS);
result
.then(
() => {
should.fail();
done();
},
(error) => {
expect(error).to.not.be.null;
expect(error).to.not.be.undefined;
expect(error.message).to.equal(errorMessage);
done();
}
);
});

How to upload video to facebook via FB api with javascript?

How can I upload video files to facebook using FB api? I looked around stackoverflow but I can only find answers when the video/picture is already online somewhere, but I want to let the user directly upload a file to facebook via my application.
One solution that can upload to facebook is https://stackoverflow.com/a/8195849/364938, but it assumes I have the picture online somewhere.
Is this even possible? If if is, then how?
This is my code for uploading video using javascript from client side.I used axios for http requests, but you can use your own.
function uploadVideo(adaccount, access_token, file) {
return axios({
method: 'POST',
url: `${adaccount}/advideos`,
params: {
access_token,
upload_phase: 'start',
file_size: file.size
}
})
.then(res => {
return new Promise(resolve => {
resolve(transferVideo(
adaccount,
access_token,
res.data.upload_session_id,
res.data.start_offset,
res.data.end_offset,
file,
1
))
})
})
.catch(err => {
// Note: you can handle your error here
console.log(err)
})
}
function transferVideo(adaccount, token, sessionId, start, end, file, number) {
if (start === end) {
return new Promise(resolve => {
resolve(postVideo(adaccount, token, sessionId, file.name))
})
}
const blob = new Blob([file], {
type: file.type
})
const chunk = blob.slice(start, end, file.type)
const formData = new FormData()
formData.append(
'video_file_chunk',
chunk,
`#chunk${number}.${file.type.split('/')[1]}`
)
return new Promise(resolve => {
resolve(uploadVideoChunk(
adaccount,
token,
start,
sessionId,
formData
))
})
.then(res => {
return new Promise(resolve => {
resolve(transferVideo(
adaccount,
token,
sessionId,
res.start_offset,
res.end_offset,
file,
number++
))
})
})
.catch(err => {
throw new Error(JSON.stringify(err))
})
}
function uploadVideoChunk(adaccount, access_token, start_offset, upload_session_id, formData) {
return axios.post(`${adaccount}/advideos`, formData, {
headers: {
'content-type': 'multipart/form-data'
},
params: {
access_token,
upload_phase: 'transfer',
start_offset,
upload_session_id
}
})
.then(res => res.data)
.catch(err => {
throw new Error(JSON.stringify(err))
})
}
function postVideo(adaccount, access_token, upload_session_id, title) {
return axios({
method: 'POST',
url: `${adaccount}/advideos`,
params: {
access_token,
upload_phase: 'finish',
upload_session_id,
title
}
})
.then(res => res.data)
.catch(err => {
throw new Error(JSON.stringify(err))
})
}