Multipart File upload in Ionic - python

I'm trying to upload a picture to my server with some additional data. My angularJs code is that:
function create_question(question, callback){
var form = new FormData()
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"processData": false,
"data": form
}
$cordovaFile.readAsDataURL(cordova.file.dataDirectory, question.name)
.then(function (success) {
form.append("file", success)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(Utf8Decode(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}
In my server, I have that view:
#parser_classes((MultiPartParser, ))
class CreateQuestion(APIView):
def post(self, request, format=None):
picture = request.data['file']
question_id = request.data['question_id']
project_id = request.data['project_id']
options = request.data['options']
title = request.data['title']
correct_option = request.data['correct_option']
username = request.user.username
project = Project.objects.get(project_id=project_id)
if project.owner_user.username == username:
ext = '.jpg'
aws = AWSClient()
picture_name = question_id + ext
picture_url = aws.put(picture, 'question_pictures', picture_name)
question = Question.objects.create(question_id=question_id, title=title,
picture_url=picture_url, options=options, owner_project=project,
correct_option=correct_option)
project.question_count += 1
project.picture_url = picture_url
project.save()
serializer = QuestionSerializer(question, context={"request": request})
return JsonResponse(serializer.data)
else:
return JsonResponse({"result": "fail"})
After I made the request, question was created and the picture file was uploaded to Amazon S3. However, I could not open the resulting file in my pc. Where am I doing mistake?

After a long search on the internet, I found the answer. First, I read file with
$cordovaFile.readAsArrayBuffer(directory,filename)
After that, I created a Blob object with the file:
var imgBlob = new Blob([success], { type: "image/jpeg" } );
My final angularJS code is:
function create_question(question, callback){
var form = new FormData()
$cordovaFile.readAsArrayBuffer(cordova.file.dataDirectory, question.name)
.then(function (success) {
var imgBlob = new Blob([success], { type: "image/jpeg" } );
form.append("file", imgBlob)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"filename": question.id,
"processData": false,
"data": form,
"file": success,
"filename": "file"
}
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(JSON.stringify(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}

Related

Django request.session don't save data

I'm trying to retrieve the session data after login but it doesn't seem to be saving the information
.
class getSession(View):
def post(self, request):
print('====================>')
print(request.session.get('usuario'))
sesion = request.session.get('usuario')
return JsonResponse({'nombre': sesion.nombre, 'rut':sesion.rut})
class Login(View):
def post(self, request):
data = json.loads(request.body)
try:
usuario = Usuario.objects.get(rut=data['rut'], password=data['password'])
request.session['usuario'] = {'nombre': usuario.idpersona.name, 'rut': usuario.rut}
request.session.modified = True
#print(self.request.session['usuario'])
return JsonResponse({'usuario':usuario.rut})
except:
return JsonResponse({'usuario':'no existe'})
I'm get this error.
AttributeError: 'NoneType' object has no attribute 'nombre'
I'am using fetch with react.
async login() {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
rut: this.state.rut,
password: this.state.password,
}),
};
const response = await fetch("http://127.0.0.1:8000/test", requestOptions);
const data = await response.json();
if (data.usuario == "no existe") {
mensajeError("RUT o contraseña inválidos.");
} else {
mensajeExitoso("Usuario validado correctamente.");
setTimeout(() => {
window.location.href = "/Inicio";
}, 2000);
}
console.log(data.usuario);
}
try setting SESSION_SAVE_EVERY_REQUEST = True in settings.py

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)

FastApi cannot write cookie in reponse, in docker on vps, how to fix?

Cannot to sign in, i run localy in docker my container, i can sign-in on my machine and docker no error, but on my remote server i cannot to login, it doesn't write cookie in reponse, have no error, just don't write response. It just redirect me on my page which i setted,and after that i got error, cause i have no my cookie authorization key inside cookie.
video
My SignIn method
#auth_router.post('/signin')
async def sign_in(response: Response, username: str = Form(...), password: str = Form(...), recaptchav3: str = Form(...)) -> dict:
is_human = await verify_recaptcha(recaptchav3)
if is_human['success']:
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid username or password',
)
user_obj = await User_Pydantic.from_tortoise_orm(user)
user_token = await generate_token(user_obj)
response.set_cookie(key="Authorization", value=user_token, httponly=True, secure=True, expires=(8*60*60))
response.headers["Authorization"] = user_token
user.jwt_token = user_token
await user.save()
return {
'access_token': user_token,
'token_type': 'bearer'
}
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid captcha',
)
How i submit my form js
const request = (method, url, data = null, redirectPage) => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(method, url, true)
// xhr.setRequestHeader('Content-Type', 'multipart/form-data')
xhr.onerror = function (event) {
alert(event)
console.log(event);
};
xhr.onload = () => {
if (xhr.status === 200) {
return window.location.href = redirectPage;
return resolve(JSON.parse(xhr.responseText || '{}'))
} else {
alert(`Request failed with status ${xhr.status}`)
reject(new Error(`Request failed with status ${xhr.status}`))
return window.location.reload();
}
}
if (data) {
if (typeof data === 'string' || data instanceof String || typeof data.constructor == Object){
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
}
} else {
xhr.send()
}
})
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData, 'dashboard');
} else{
alert('Перезагрузите страницу');
}
}
})
I cannot understand why using the built-in method in fastapi it does not write on the remote server, it worked on the local one, but I solved the problem by writing. token via js.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(cookieValue) {
var user = getCookie("Authorization");
if (user == "") {
if (cookieValue != "" && cookieValue != null) {
setCookie("Authorization", cookieValue, 365);
}
}
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData);//, 'dashboard');
isLogened.then(result => {
checkCookie(result.access_token);
return window.location.href = 'dashboard';
}, result => {
log('Cant get response')
});
} else{
alert('Перезагрузите страницу');
}
}
})

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

Django Ajax Call to Return Quantity

Currently using the django-carton app, I have a django view that returns JSON data that I use in an ajax call. Broadly speaking, I have got it working but struggling to work out how I can pass my item quantity (using ajax).
Within the template I can call my item quantities using:
{% for item in cart.items %}
{{ item.quantity }}
The ajax call connects to the view to return the Json data:
def cart_detail_api_view(request):
# cart_obj, new_obj = Cart.objects.new_or_get(request)
cart = Cart(request.session)
products = [{"name": x.name, "price": x.price} for x in cart.products]
cart_data = {"products": products, "total": cart.total}
return JsonResponse(cart_data)
This is my Jquery/Ajax call:
$(document).ready(function() {
var productForm = $(".form-product-ajax") // #form-product-ajax
productForm.submit(function(event) {
event.preventDefault();
// console.log("Form is not sending")
var thisForm = $(this)
//var actionEndpoint = thisForm.attr("action");
var actionEndpoint = thisForm.attr("data-endpoint");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function(data) {
var submitSpan = thisForm.find(".submit-span")
if (data.added) {
submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>")}
var currentPath = window.location.href
if (currentPath.indexOf("") != -1) {
refreshCart()
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
})
function refreshCart() {
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
var productRows = cartBody.find(".cart-product")
var cartTotal = cartTable.find(".cart-total-sec")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 1) {
$(cartBody).empty()
productRows.html("")
$.each(data.products, function(index, value) {
console.log(value)
console.log(data.count)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
cartTotal.find(".cart-total").text(data.total)
console.log(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
You have to instruct your $.ajax() call that you are expecting data in JSON format, so the data is parsed properly in your success callback:
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
dataType: 'json', // <- here
success: function(data) {
// ...
},
error: function(errorData) {
// ...
}
})

Categories

Resources