Axios post request error: 422 Unprocessable Entity - python

I've been trying to build this stock prediction web app using Prophet model and FastAPI. I'm stuck at this problem where I'm getting console log error: 422 Unprocessable Entity.
Here's the react code to get API request:
async function GetAPI () {
const [predData, setPred] = React.useState();
const [stock_name, setStock] = React.useState();
const axios = require('axios');
var data = JSON.stringify({
"ticker": stock_name
})
try{
let response = await axios({
method: 'post',
url:'http://0.0.0.0:8000/predict',
headers: {
'accept' : 'application/json',
'Content-Type' : 'application/json'
},
data: data
},
)
if (response.status==200){
console.log(response.data);
setPred(response.data);
}
return {predData}
}
catch(error){
console.log(error);
}
}
This is the FastAPI function in my python backend:
#app.post("/predict")
def prediction(payload: StockIn):
stock_name = payload.stock_name
pred = stock_prediction(stock_name)
a = int(pred)
response_object = {"data" : a }
return response_object
Can anyone help me out here?

First of all, you send {'ticker': '...'}.
And in backend you try to access a property called stock_name.
Most likely this is caused by it.
If that doesn't help, check below.
It seems that your situation is related with your backend, so you can edit the header.
You can check the variables by simply adding
print statements after important parts.
For example;
#app.post("/predict")
def prediction(payload: StockIn):
print('Payload:', payload)
stock_name = payload.stock_name
pred = stock_prediction(stock_name)
print('Pred:', pred)
a = int(pred)
response_object = {"data" : a }
return response_object
NOTE: It's about backend because axios doesn't interfere with the response codes.

Related

Python to GAS translation not working: get bad request error

I want the following code to be translated into GAS from python. I wrote the GAS version pasted below but it is not working. It must be something simple but I don't know the reason why I get this error. Any advice will be appreciated. Thanks.
import requests
requestId = "*******************"
url = "http://myapi/internal/ocr/"+requestid+"/ng"
payload={}
headers = {
'X-Authorization': 'abcdefghijklmn'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I wrote this at the moment but I get bad request error.
function sending(yesorno, requestId) {
var requestId = "*******************"
 var STAGING_KEY = "abcdefghijklmn"
var url = url = "http://myapi/internal/ocr/"+requestId+"/ng"
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': JSON.stringify(data),
'headers': {
'X-Authorization': STAGING_KEY
}
};
//Error processing
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options));
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error')
}
}
Modified Code
function sending() {
var requestId = "*************************"
var STAGING_KEY = "abcdefghijklmn"
var url = "http://myapi/internal/ocr/"+requestId+"/ng";
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': data,
'headers': {
'X-Authorization': STAGING_KEY
}
};
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
Logger.log(response)
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error1')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error2: '+ e.toString())
}
}
Error
error2: Exception: Bad request:
I understood your situation as follows.
Your python script works fine.
You want to convert the python script to Google Apps Script.
When your Google Apps Script is run, an error Exception: Bad request: occurs.
In this case, how about the following modification? When response = requests.request("POST", url, headers=headers, data=payload) is used with payload={}, I think that at Google Apps Script, it's 'payload': {}.
Modified script:
function sending() {
var requestId = "*******************"
var STAGING_KEY = "abcdefghijklmn"
var url = "http://myapi/internal/ocr/" + requestId + "/ng"
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': data,
'headers': {
'X-Authorization': STAGING_KEY
}
};
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
console.log(response)
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error')
}
}
Note:
By the above modification, the request of Google Apps Script is the same as that of the python script. But if an error occurs, please check the URL and your STAGING_KEY, again. And, please check whether the API you want to use can access from the Google side.
Reference:
fetch(url, params)

Stripe IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId

I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new r (https://js.stripe.com/v3/:1:6143)
at Js (https://js.stripe.com/v3/:1:165350)
at $s (https://js.stripe.com/v3/:1:165646)
at https://js.stripe.com/v3/:1:166758
at Qs (https://js.stripe.com/v3/:1:166769)
at nc (https://js.stripe.com/v3/:1:167275)
at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030)
at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39
Here's the Vue.js method responsible for this:
<script src="https://js.stripe.com/v3/"></script>
<script>
const PlansApp = {
data() {
return {
}
},
delimiters: ['[[', ']]'],
methods: {
subscribe(plan) {
console.log('Subscribe:', plan);
const stripe = Stripe('{{ stripe_pub_key }}');
fetch('/dashboard/myaccount/teams/api/create_checkout_session/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({
'plan': plan
})
})
.then(function(response) {
return response.json()
})
.then(function(session) {
console.log(session)
return stripe.redirectToCheckout({ sessionId: session.sessionId })
})
.then(function(result) {
if (result.error) {
console.log('Error:', result.error.message)
}
})
.catch(function(error) {
console.log('Error:', error);
});
}
}
}
Vue.createApp(PlansApp).mount('#plans-app')
</script>
And here's the Django code that creates the session on the backend:
#login_required
def create_checkout_session(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
data = json.loads(request.body)
plan = data['plan']
if plan == 'basic':
price_id = settings.STRIPE_BASIC_PRICE_ID
else:
price_id = settings.STRIPE_PRO_PRICE_ID
try:
checkout_session = stripe.checkout.Session.create(
client_reference_id = request.user.userprofile.active_team_id,
success_url = '%s%s?session_id={CHECKOUT_SESSION_ID}' % (settings.WEBSITE_URL, reverse('team:plans_thankyou')),
cancel_url = '%s%s' % (settings.WEBSITE_URL, reverse('team:plans')),
payment_method_types = ['card'],
mode = 'subscription',
line_items = [
{
'price': price_id,
'quantity': 1
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
I'm struggling to find out why I'm getting the error that I'm getting and would be grateful for any help!
I guest the problem come from the 'success_url' and the 'cancel_url'.
Try to add http:// or https:// in your url
Cordially

Flutter Post Request to a Flask API

i want to send a request Post from my App coded in Flutter in which there is an image converted in Base 64. Here is the following code that I am using :
Future<List<Result>> postJSON(String imageP, String iP, String port) async {
final String jsonEndpoint = "http://$iP:$port/todo/api/v1.0/tasks/mdrv";
final response = await http.post('$jsonEndpoint', body:
{
"id": "3",
"title_image": "Test",
"b64Image": "$imageP",
"done": "false",
},);
if (response.statusCode == 200){
List results = jsonDecode(response.body);
return results
.map(
(result) => new Result.fromJson(result))
.toList();
} else {
throw Exception('Erreur dans le chargement, veuillez réessayer');
}
}
But, when i do the request, i have the following TypeError on my Flask API :
description = JSON["b64Image"]
TypeError: 'NoneType' object is not subscriptable
I am using the following Python code :
def send_client():
Lresult_algo=[]
JSON = request.get_json()
id = JSON['id']
'description':JSON['b64Image']
server=Server(description)
description1=server.B64_array(description)
description2=Image.fromarray(description1)
description2.save(r"C:\Users\vince\Desktop\test2.png")
queryPath=r"C:\Users\vince\Desktop\test2.png"
Lresult_algo=server.send(queryPath)
maskedBodies_b64 = []
for matrice in Lresult_algo:
matrice1=matrice.astype('uint8')
maskedBodies_b64.append(base64.b64encode(cv2.imencode('.jpg', matrice1)[1]))
maskedBodies_b64=[str(b64) for b64 in maskedBodies_b64]
data = {
'Image_1' : maskedBodies_b64[0],
'Image_2' : maskedBodies_b64[1],
'Image_3' : maskedBodies_b64[2],
'Image_4' : maskedBodies_b64[3],
'Image_5' : maskedBodies_b64[4]
}
resp=json.dumps(data)
return resp
Do you think is this a typing problem ? How could I fix it ?
I changed my code like this but there is still the same mistake :
Future<List<Result>> postJSON(String imageP, String iP, String port) async {
final String jsonEndpoint = 'http://$iP:$port/api/v1.0/tasks/mdrv';
Map<String, dynamic> data = {
'id': 1,
'title_image': "Test",
'b64Image': "$imageP",
'done': false,
};
var client = new http.Client();
var body = jsonEncode(data);
var response = await client.post('$jsonEndpoint',headers: {"Content-Type": "application/json"}, body: body,);
if (response.statusCode == 200){
List results = jsonDecode(response.body);
return results
.map(
(result) => new Result.fromJson(result))
.toList();
} else {
throw Exception('Erreur dans le chargement, veuillez réessayer');
}
}

Cant get desired response in react js from flask api

I am using the fetch library from reactjs for getting and pushing data to/from my flask API. But can't get the desired response from the my api.
This is my flask api:
#app.route('/adduser',methods=['POST'])
def indx():
data=request.get_json(force=True)
email=request.get_json()["email"]
password=request.get_json()['password']
try:
auth.create_user_with_email_and_password(email,password)
except:
userexists="User Already Exists"
try:
user=auth.sign_in_with_email_and_password(email,password)
id = auth.get_account_info(user['idToken'])
db.child("users").push(id)
except:
invalidCredentials="Wrong Credentials"
if request.get_json(force=True):
x={
"name":"sarmad",
"roll":"052"
}
s=json.dumps(x)
return s
else:
return ""
This is react js code:
fetch('http://127.0.0.1:5000/adduser', {
mode:'no-cors',
method: 'POST',
headers: {
'Accept': 'application/json',
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json'
},
body: JSON.stringify({
'email': this.state.email,
password: this.state.password,
name: this.state.name,
// userType: userTy,
dob:this.state.DOB,
address:this.state.Address,
gender:'male',
phone:'090078601',
// roles:roles
})
}).then((response) => response).then((responseJson) => {
console.log(responseJson);
//this.setState({pressed: false});
})
I need to receive the data passed back from the Flask API either as a string or json. This is my current response back:
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" _proto_: Response
Any help would be greatly appreciated!
Just do it with .json()
}).then((response) => response.json()).then((responseJson) => {
console.log(responseJson);
//this.setState({pressed: false});
})

S3 Ajax CORS Error

I have been trying to solve this for the past few hours.
I am using the Heroku S3 python app direct upload method outlined here.
Basically, I have a file input which I get the file from with
$('#files').on('change', function() {
var files = document.getElementById("files").files;
var file = files[0];
if(!file){
return alert("No file selected.");
}
getSignedRequest(file);
})
In getSignedRequest, I make a request to my sign_s3 route
function getSignedRequest(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", "/sign_s3?file_name="+file.name+"&file_type="+file.type);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
var response = JSON.parse(xhr.responseText);
uploadFile(file, response.data, response.url);
}
else{
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
The sign_s3 route is defined as follows
#main.route('/sign_s3/')
def sign_s3():
S3_BUCKET = os.environ.get('S3_BUCKET')
file_name = request.args.get('file_name')
file_type = request.args.get('file_type')
s3 = boto3.client('s3')
presigned_post = s3.generate_presigned_post(
Bucket = S3_BUCKET,
Key = file_name,
Fields = {"acl": "public-read", "Content-Type": file_type},
Conditions = [
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn = 3600
)
return json.dumps({
'data': presigned_post,
'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name)
})
The uploadFile function is defined as follows
function uploadFile(file, s3Data, url){
var xhr = new XMLHttpRequest();
xhr.open("POST", s3Data.url);
var postData = new FormData();
for(key in s3Data.fields){
postData.append(key, s3Data.fields[key]);
}
postData.append('file', file);
console.log(file);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4){
if(xhr.status === 200 || xhr.status === 204){
document.getElementById("preview").src = url;
document.getElementById("avatar-url").value = url;
}
else{
alert("Could not upload file.");
}
}
};
xhr.send(postData);
}
});
My bucket CORS config is as follows
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://localhost:5000</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
But I keep getting the following error upon fileUpload
Failed to load https://mhealth-beta-1.s3.amazonaws.com/: Redirect from 'https://mhealth-beta-1.s3.amazonaws.com/' to 'https://mhealth-beta-1.s3-us-west-2.amazonaws.com/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.
The error is mentioning a redirect. I'm not familiar with how 302 redirects interact with CORS but try this:
In your backend route, use the dns name including the region.
so 'https://%s.s3.%s.amazonaws.com/%s' % (S3_BUCKET, region, file_name)

Categories

Resources