I get Expecting value: line 1 column 1 (char 0) error on the page when my cart is empty but works when cart is populated. I'm expecting the error but that doesn't help either. Same continues on the other template also if data is empty. Maybe it has to do something not being returned.
def cartdetails(request):
if request.session.get('token', None) != None:
tokenid = request.session.get("token")
headers = {'Authorization': 'token ' + str(tokenid[0])}
url = 'https://api-ecommerce.datavivservers.in/mobile_api/CartDetails/'
jsondata = requests.get(url, headers=headers).json()
print(jsondata)
try:
return render(request, 'cart.html', {
"order_id": jsondata['order_id'],
"user_id": jsondata['user_id'],
"wallet_amount": jsondata['wallet_amount'],
"payable_amount": jsondata['payable_amount'],
"payment_status": jsondata['payment_status'],
"payment_mode": jsondata['payment_mode'],
"order_status": jsondata['order_status'],
"delivery_status": jsondata['delivery_status'],
"order_delivery_type": jsondata['order_delivery_type'],
"get_cart_total_discount": jsondata['get_cart_total_discount'],
"get_cart_total_GST": jsondata['get_cart_total_GST'],
"get_cart_total": jsondata['get_cart_total'],
"get_cart_sub_total": jsondata['get_cart_sub_total'],
"get_cart_quantities": jsondata['get_cart_quantities'],
"get_cart_items": jsondata['get_cart_items'],
"deliveryCharges": jsondata['deliveryCharges'],
"subscription_type": jsondata['subscription_type'],
"subscriptionId": jsondata['subscriptionId'],
"products": jsondata['products']
})
except simplejson.errors.JSONDecodeError:
return render(request, 'cart.html', {})
else:
print("login")
return redirect('login')
Related
I am trying to connect silicon pay (a payment API) but I have failed to understand how to handle the callback URL to check if the transfer was successful or not in order to give value to my customers
#login_required(login_url='accounts:login')
def mobile_deposit(request):
if request.method == 'POST':
form = MobileDepositForm(request.POST or None)
if form.is_valid():
pending_amount = form.cleaned_data.get('pending_amount')
if pending_amount >= 37000:
account = Account.objects.get(user=request.user)
data_req = {
"req": "mobile_money",
"currency": "UGX",
"phone": str(account.user.phone_number),
"encryption_key": "",
"amount": str(pending_amount),
"emailAddress": str(account.user.email),
'call_back': "https://41ab-137-63-181-131.in.ngrok.io/callback",
"txRef": generate_txRef()
}
account.txRef = data_req['txRef']
account.save()
headers = {
'Content-Type': 'application/json'
}
response = requests.post('https://silicon-pay.com/process_payments', data=json.dumps(data_req), headers=headers)
print(response.text)
account.save()
messages.success(request, "Please confirm your Transaction on your phone")
return redirect("accounts:mobile-deposit")
else:
messages.warning(request, "Minimum deposit is UGX 37000")
return redirect('accounts:mobile-deposit')
else:
messages.warning(request, "Form error")
return redirect('accounts:mobile-deposit')
else:
form = MobileDepositForm(request.POST or None)
context = {
'form':form
}
return render(request, "mobile_deposit.html", context)
def generate_txRef():
return "CTF-"+str(random.randrange(111111,999999))
I have tried reading the documentation on silicon pay but its in PHP yet am implementing mine in python. My solution has crushed the site
I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not
def paytes(request):
payload ={
"USERID": code_id,
"MSISDN": serviceCode,
"MSGTYPE": type_msg,
"USERDATA": text,
"SESSIONID": session_id,
"MSG": response,
}
print('MSG: ',response)
# headers = {
# 'Content-Type': 'application/json'
# }
# response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
return JsonResponse(payload)
url = 'https://prod.theteller.net/v1.1/transaction/process'
transaction_id = random.randint(100000000000, 999999999999)
amounte = "000000000080"
amount = str(amounte)
data = {
"amount" :amount,
"processing_code" : "000200",
"transaction_id" : transaction_id,
"desc" : "Mobile Money Payment Test",
"merchant_id" : "TTM-00000727",
"subscriber_number" : "233244491909",
"r-switch" : "MTN",
}
encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=') # change this as well
headers = {
'Content-Type': 'application/json',
'Authorization': f'Basic {encoded.decode("utf-8")}',
'Cache-Control': 'no-cache'
}
res = requests.post(url, data=json.dumps(data), headers=headers)
print(res.text)
response_data = res.json()
status = response_data["status"]
print(response_data)
print(status)
return HttpResponse(res)
All the code after the first return statement is executed won't be executed, so if you want to return both of those variables then put them inside the same dictionary and return that:
return_val = {}
return_val['payload'] = payload
return_val['response'] = res
return JsonResponse(return_val)
I'm creating an app where the client upload a CSV file and the server doesn't store it but only read it to perform tasks and return the content of the CSV as a JSON.
I followed some tutorials and posts and I came to this code:
Flask:
#app.route('/analyse_dataset', methods=['GET','POST'])
def analyse_dataset_route():
print('/analyse_dataset called', file=sys.stderr)
try:
# check if the post request has the dataset part
if 'file' not in request.files:
data = {'error': 'Dataset not in requested files'}
return Response(data, status=400, mimetype='application/json')
print('request.files : ' + str(request.files))
uploaded_file = request.files['file']
# no dataset
if uploaded_file.filename == '':
logger.debug('Dataset not found, returning to /')
return redirect('/')
# dataset ok
if uploaded_file:
print('uploaded_file ok', file=sys.stderr)
filename = secure_filename(uploaded_file.filename)
#uploaded_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
uploaded_file.stream.seek(0)
myfile = uploaded_file.file
print('uploaded_file name: ' + filename, file=sys.stderr)
dataframe = pd.read_csv(myfile)
return Response(dumps(dataframe), status=200, mimetype='application/json')
else:
data = {'error': 'Something went wrong...'}
return Response(data, status=400, mimetype='application/json')
except Exception as e:
logger.error('An error occurred while analysing dataset')
logger.error(e, exc_info=True)
print(e)
data = {'error': 'An error occurred while analysing dataset'}
return Response(data, status=400, mimetype='application/json')
client side:
onClickHandler = () => {
if (this.state.selectedFile == null) {
toast.error('No file selected')
} else {
const data = new FormData()
data.append('file', this.state.selectedFile)
let req = "http://localhost:5001/analyse_dataset"
axios.post(req, data, {
onUploadProgress: ProgressEvent => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total * 100),
loading: true
})
},
})
.then(res => { // then print response status
console.log("file processed: " + res.data)
this.setState({
redirect: true,
jsondata: res.data
})
})
.catch(err => { // then print response status
console.log(err)
this.setState({
selectedFile: null,
loaded: 0,
loading: false
})
setTimeout(() => {
toast.error("Process failed, be sure to upload a correct file.")
}, 500)
})
}
}
So there is this issue where it's "" working "" with a large CSV file but it isn't working with a smaller one and I can't figure out why. Also I'd like to return a JSON containing each line of the CSV to the client but for the moment it isn't working aswell.
Here is the error :
Your code is likely failing on myfile = uploaded_file.file. Try changing the line to myfile = uploaded_file.stream.
If you are using Python 3, then pandas.read_csv requires text file/stream i.e. unicode. Convert the stream and it should work.
myfile = io.StringIO(myfile.getvalue().decode())
Once you have your pd.DataFrame object, you can use pd.DataFrame.to_json to convert your files. See the docs here.
I am unsure as to exactly why larger files work.
here I am creating a new customer and save it into a customers.json file
new_user = appregister.newDocument('customers', username_1)
new_user.set('username', username_1)
new_user.set('email', email)
new_user.save()
new_user = format_customers()
print(new_user)
body_json = json.dumps(new_user)
scriptuser = util.get_app_parameter("scriptuser", "beta")
username = scriptuser["username"]
password = scriptuser["password"]
url = 'https://****.***.**/*****-****-1-0/****-****/customers.json'
headers = {'Content-Type': 'application/json'}
new_items = new_user
body_json = json.dumps(new_items)
status, headers, data = network.request(url, method='PUT',
headers=headers,
body=body_json,
encoding='UTF-8',
username=username,
password=password)
here I want to send a mail to the customer(like when i register a new customer so the customer get an email with some random code) I don't think that I am accessing the customer email
sources = ["customers.json"]
for source in sources:
data = util.get_data_item(source)
if data is None or len(data) == 0:
continue
register = json.loads(data)
for json_obj in register['customers']:
try:
emailaddress = json_obj['email']
print(email) # I get NONE here
except Exception as e:
emailaddress = None
if emailaddress:
if email == json_obj['email'].lower().strip():
code = "".join( [random.choice(string.digits) for i in xrange(6)] )
HTML = util.get_data_item("send_code2.html")
subject = (app_properties.get(EMAIL_TITLE_KEY))
try:
messageText = 'Your code is : '+ code
except Exception, e:
response = {'status' : 'error', 'message' : str(e)}
return json.dumps(response), responseHeaders, 400
p = Properties()
p.load(StringReader(util.get_data_item('messages.properties')))
title = (p.getProperty('email.title', ''))
color = json.loads(util.get_data_item('theme.json'))['colors']['tint'][-6:]
imagedata = base64.b64encode(util.get_data_item_bytes('logo.png'))
messageHtml = Environment().from_string(HTML).render(code=code, title=title, color=color, imagedata=imagedata)
try:
sendEmail('no-reply#ggg.com', email, subject, messageHtml, messageText)
except Exception, e:
logger.error("ERROR " + str(e))
response = {'status' : 'error', 'message' : str(e)}
return json.dumps(response), responseHeaders, 400
appRegister.put('activationcode', code);
appRegister.put('state', 'pending')
appRegister.put('activationtries', '0')
appRegister.put('email', email)
return json.dumps({}), responseHeaders, 200
error = {'title': app_properties[REGISTRATION_ERROR_TITLE_KEY], 'message' : app_properties[REGISTRATION_ERROR_KEY]}
return "200", responseHeaders
this is how my customers.json file looks like
{
"customers": {
"Osar": {
"email": "gmail#gmail.com"
},
"eeforetzr": {
"email": "email1#hotmail.com"
},
"aaxel": {
"email": "hotmail#hotmail.com"
}
"Mark": {
"email": "mark#gmail.com"
}
}
}
# view code:
response_data = []
for p in product:
response_record = {}
response_record['pname'] = p.name
response_data.append(response_record) ...
# make json type array end
return HttpResponse(json.dumps(response_data, default=date_handler,
sort_keys=True), "application/json")
For example, i want to get values like response.product.pname in ajax response:
# expected json output:
{
["product": {"pname": 'a', "pid": '2'}]
}
I finaly found choice
view:
def search(request):
if request.method == 'POST' and request.is_ajax():
value = request.POST.get('value')
products = product.objects.filter(p_name__icontains=u'%s' % value)#Convert to unicode
#make json type array begin
response_data = []
final_response = {}
for p in product:
response_record = {}
response_record['pname'] = p.name
response_record['pid'] = p.id
response_data.append(response_record)
final_response["product"] = response_data
#make json type array end
return HttpResponse(json.dumps(final_response, default=date_handler, sort_keys=True), "application/json")
else:
return HttpResponse("Bad Request Detected!! :(")
JS:
$.ajax({
type: 'POST',
url: '/Search/',
data:{value:val},
dataType: "json",
success:function(response)
{
$.each(response.product, function (i, val)
{
alert(val.pname+" "+val.pid);
}
);
}