Decimal calculation different on my local machine vs Heroku server - python

I have a Django project that I deployed to Heroku. I noticed that the calculations are not working when I used smaller numbers for some reason. Everything works fine on my local Windows machine.
For example this calculation newBalance = Decimal(str(userObj.user_coins)) - Decimal(str(betValue)) when the calculation would be 2000 - 12 I get an answer of 2.0E+3 instead of 1988. If the calculation would be 2000 - 120 I get an answer of 1900 or 1.9E+3 instead of 1880. On my local machine this was working correctly.
I don't understand what might be going wrong here.
//Template script
$('.bet-submit').click(function() {
const betValue = document.getElementById('bet-value').value
betSocket.send(JSON.stringify({
'id': id,
'betValue': betValue
}))
})
betSocket.onmessage = function(e) {
const data = JSON.parse(e.data)
update_coins()
for(const key in data.bets){
document.querySelector('#bets').innerHTML += '<span>' +data.bets[key].bet_value +'$</span>'
}
}
function update_coins() {
$.ajax({
method: "POST",
headers: { "X-CSRFToken": token },
url: "/api/coins/",
data: {},
success: function(data) {
document.querySelector('#user_coins').innerHTML = data.coins
}
})
};
//consumers.py
async def receive(self, text_data):
id= data['id']
betValue = data['betValue']
await save_bet(id, betValue)
bets = await get_bets(round)
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'send_bet',
'bets': bets
}
)
#database_sync_to_async
def save_bet(id, betValue):
userObj = CustomUser.objects.filter(steam_id=steamid)[0]
newBalance = userObj.user_coins - Decimal(betValue)
print(newBalance) // 2.0E+3
CustomUser.objects.filter(steam_id=steamid).update(user_coins=newBalance)
...
#database_sync_to_async
def get_bets(round):
...
bets = {}
for idx, bet in enumerate(betsObj):
bets[str(idx)] = {}
bets[str(idx)].update({
...,
'bet_value': str(bet.bet_value),
})
return bets

I think you'd better use float rather than Decimal.
newBalance = float(str(userObj.user_coins)) - float(str(betValue))

Related

JSONDecodeError in Django after Paypal payment

I keep getting the below error when I complete payment via Paypal in development:
JSONDecodeError at /checkout/thankyou
Expecting value: line 1 column 1 (char 0)
I have looked around and I can see that there is some issue with the format of the JSON, and my view can't process it. I can't figure out what the issue with my data is exactly, however. I want to use my Json data to create an order on my Django model once it has pulled through, however I can't get to that stage yet.
checkout.html script:
let bagContents = '{{ bag_products|safe }}';
const csrftoken = getCookie('csrftoken');
const paymentAmount = '{{ total | safe }}';
// Parse bagContents, then for each create a variable for name, id and quantity
let bag = JSON.parse(bagContents);
for (let i = 0; i < bag.length; i++) {
let itemName = bag[i].name;
let itemId = bag[i].id;
let itemQuantity = bag[i].quantity;
console.log(itemName);
console.log(itemId);
console.log(itemQuantity);
}
function completeOrder(){
let url = '{{ success_url }}'
fetch(url, {
method: 'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken': csrftoken,
},
body:JSON.stringify({'bagContents': 'bagContents'})
})
}
paypal.Buttons({
// Sets up the transaction when a payment button is clicked
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [{
amount: {
value: paymentAmount
}
}]
});
},
// Finalize the transaction after payer approval
onApprove: (data, actions) => {
return actions.order.capture().then(function (orderData) {
// Successful capture! For dev/demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
const transaction = orderData.purchase_units[0].payments.captures[0];
completeOrder()
actions.redirect("{{ success_url }}");
// When ready to go live, remove the alert and show a success message within this page. For example:
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
{% endblock %}
Views.py:
def order_success(request):
"""
View that displays the successful order page after an order has been
processed.
"""
print(request.body)
body = json.loads(request.body)
print('BODY:', body)
return JsonResponse('Success!', safe=False)
Print Statements:
b'{"bagContents":"[{\\"name\\": \\"Teddy Bear\\", \\"id\\": 2, \\"quantity\\": 3}, {\\"name\\": \\"Bath Toys\\", \\"id\\": 1, \\"quantity\\": 1}, {\\"name\\": \\"Chew Toy\\", \\"id\\": 4, \\"quantity\\": 2}]"}'
b''
BODY: {'bagContents': '[{"name": "Teddy Bear", "id": 2, "quantity": 3}, {"name": "Bath Toys", "id": 1, "quantity": 1}, {"name": "Chew Toy", "id": 4, "quantity": 2}]'}
Any help would be greatly appreciated!

FLASK request.json not working with React payload

I have a flask route that queries my DB for locations and services based on a radius. Testing and working with POSTMAN.
#bp.route('/provider-locations/<int:radius>', methods=['GET'])
def get_locations_from_radius(radius):
user_latitude = request.json['lat']
user_longitude = request.json['lng']
my_obj = {}
my_obj_container = []
locations = db_session.query(ProviderLocation).filter(\
func.acos(func.sin(func.radians(user_latitude)) \
* func.sin(func.radians(ProviderLocation.latitude)) + \
func.cos(func.radians(user_latitude)) * \
func.cos(func.radians(ProviderLocation.latitude)) * \
func.cos(func.radians(ProviderLocation.longitude) - \
(func.radians(user_longitude)))) * 6371 <= radius)
for location in locations:
services = db_session.query(ProviderService).select_from(ProviderService).join(\
ServiceLocationLink).filter(ServiceLocationLink.location_id == location.id).all()
my_obj = provider_location_list_schema.dump(location)
my_obj['services'] = [provider_service_list_schema.dump(service) for service in services]
my_obj_container.append(my_obj)
return jsonify(my_obj_container)
My error comes in trying to pass this req the expected params from my client (React). I keep receiving a 400 response.
export async function getLocationServicesByRadius(radius, user_address) {
try {
const body = {
lat: user_address.lat,
lng: user_address.lng
}
return await awsApiRequest({
method: 'GET',
path: `/provider-locations/${radius}`,
params: {
body: body
},
});
} catch (err) {
console.log(err.message)
}
}
const fetchLocationServices = async () => {
const userAddress = {
lat: 43.829640,
lng: -79.470310
}
const { data, success, errorMessage } = await getLocationServicesByRadius(userDistance, userAddress)
if (success) {
console.log('RADIUS =>', data)
} else {
console.log(errorMessage)
}
}
I must be missing something somewhere but can not figure out why the req is returning 400.
the body from the client looks as so:
{
lat: 43.82964
lng: -79.47031
}
In flask request.json is used to access POST request body, for GET requests use request.args.

Python program for auto creation of thing,policy,certificate all stuffs needed in aws iot console interface

i have used aws-iot-sdk-node.js for programmatic generation of things.
[https://aws.amazon.com/blogs/compute/implementing-a-serverless-aws-iot-backend-with-aws-lambda-and-amazon-dynamodb/][1]
But i want python program to auto register a raspberry pi by generating thing,policy,certificates and download the certificates for further use.
var AWS = require('aws-sdk');
AWS.config.region = 'region';
AWS.config.update({
accessKeyId: "your Key",
secretAccessKey: "your Key",
});
var iot = new AWS.Iot();
var crypto = require('crypto');
var endpoint = "your endpoint"
var iotdata = new AWS.IotData({endpoint: endpoint});
var topic = "registration";
var type = "MySmartIoTDevice"
//Create 50 AWS IoT Things
for(var i = 1; i < 51; i++) {
var serialNumber = "SN-"+crypto.randomBytes(Math.ceil(12/2)).toString('hex').slice(0,15).toUpperCase();
var clientId = "ID-"+crypto.randomBytes(Math.ceil(12/2)).toString('hex').slice(0,12).toUpperCase();
var activationCode = "AC-"+crypto.randomBytes(Math.ceil(20/2)).toString('hex').slice(0,20).toUpperCase();
var thing = "myThing"+i.toString();
var thingParams = {
thingName: thing
};
iot.createThing(thingParams).on('success', function(response) {
//Thing Created!
}).on('error', function(response) {
console.log(response);
}).send();
//Publish JSON to Registration Topic
var registrationData = '{\n \"serialNumber\": \"'+serialNumber+'\",\n \"clientId\": \"'+clientId+'\",\n \"device\": \"'+thing+'\",\n \"endpoint\": \"'+endpoint+'\",\n\"type\": \"'+type+'\",\n \"activationCode\": \"'+activationCode+'\",\n \"activated\": \"false\",\n \"email\": \"not#registered.yet\" \n}';
var registrationParams = {
topic: topic,
payload: registrationData,
qos: 0
};
iotdata.publish(registrationParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
// else Published Successfully!
});
setTimeout(function(){},50);
}
//Checking all devices were created
iot.listThings().on('success', function(response) {
var things = response.data.things;
var myThings = [];
for(var i = 0; i < things.length; i++) {
if (things[i].thingName.includes("myThing")){
myThings[i]=things[i].thingName;
}
}
if (myThings.length = 50){
console.log("myThing1 to 50 created and registered!");
}
}).on('error', function(response) {
console.log(response);
}).send();
It's my sample javascript code to scale my IOT project.I want to do this same task using python with auto creation of thing,policy,certificates and download the certificates.After this i want to store the sensor data to dynamo db through thing shadow.Suggest me the proper way to do this task.
Here is a complete reference for python program from here:
For thing creation
iot.create_thing(thingName="t_name")
For creating certificates and storing it in your repository
with open(certname, "w") as pem_file:
# out_file.write(things[i][thing_name])
pem = things[i][t_name]['certificatePem']
pem_file.write(pem)
log.info("Thing Name: {0} and PEM file: {1}".format(
t_name, certname))
with open(public_key_file, "w") as pub_file:
pub = things[i][t_name]['keyPair']['PublicKey']
pub_file.write(pub)
log.info("Thing Name: {0} Public Key File: {1}".format(
t_name, public_key_file))
with open(private_key_file, "w") as prv_file:
prv = things[i][t_name]['keyPair']['PrivateKey']
prv_file.write(prv)
log.info("Thing Name: {0} Private Key File: {1}".format(
t_name, private_key_file))
For creating and attaching policy
tp = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
# "iot:*"
"iot:Connect",
"iot:Publish",
"iot:Receive",
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:{0}:*:*".format(region)
]
}]
}
iot = _get_iot_session(region, cli.profile_name)
policy_name = 'policy-{0}'.format(thing_name)
policy = json.dumps(tp)
log.debug('[_create_and_attach_policy] policy:{0}'.format(policy))
p = iot.create_policy(
policyName=policy_name,
policyDocument=policy
)
Yeah your java script code is working,i also searching the same question you asked.I found some usefull reference here.

Tornado: Updated data from mysql not showing in frontend served by tornado. Only shows after restarting the server

I have a tornado backend which serves an Angular frontend. On updating the database, the updated data is not being fetched by the tornado api. It only appears after I restart the server. Can someone please help me with this? I want the data fetched to be updated real-time.
AngularJS ajax request:
$http({
method: "GET",
url: "http://localhost:9915/api/"
}).then(function mySuccess(response) {
console.log(response);
$scope.data = response.data;
sharedData.set(response.data);
for (var i = $scope.data.length - 1; i >= 0; i--) {
var coverageVal = $scope.data[i].Coverage;
var coverageHealth = $scope.data[i].Health;
if (coverageVal >= 95.00) {
$scope.data[i]["colorCoverage"] = "cyan";
} else if (coverageVal >= 90.00 && coverageVal < 95.00) {
$scope.data[i]["colorCoverage"] = "warning";
} else {
$scope.data[i]["colorCoverage"] = "danger";
}
if (coverageHealth >= 95.00) {
$scope.data[i]["colorHealth"] = "cyan";
} else if (coverageHealth >= 90.00 && coverageHealth < 95.00) {
$scope.data[i]["colorHealth"] = "warning";
} else {
$scope.data[i]["colorHealth"] = "danger";
}
}
}, function myError(err) {
console.log("error");
console.log(err);
});
Tornado api to fetch data:
class ApiRequestHandler(web.RequestHandler):
def get(self):
cur = conn.cursor()
cur.execute("SELECT * from db.table")
res = []
for row in cur:
res.append(row)
self.write(json.dumps(res))
You don't said what mysql connector are you using, but if you are using mysqldb try something like this:
class ApiRequestHandler(web.RequestHandler):
def get(self):
cur = conn.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * from db.table")
rows = cur.fetchall()
self.write(json.dumps(rows))
Also I recommend you to start using asyncio calls, for example using python 3.5 or up, you can use the aiomysql
class ApiRequestHandler(web.RequestHandler):
async def get(self):
cur = await conn.cursor()
await cur.execute("SELECT * from db.table")
rows = await cur.fetchall()
self.write(json.dumps(rows))

error 405 get method not allowed

Angularjs code
var app = angular.module('myApp', []);
app.factory('httpSend', ['$http', '$q', function($http, $q) {
var app = {};
app.sendToServer = function(data) {
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-type': 'application/x-www-form.urlencoded;'
}
}).then(function(response) {
debugger
var result = data;
});
}
app.getfromServer = function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
return app;
}]);
app.controller('myCtrl', ['$scope', '$http', 'httpSend', '$filter', function($scope, $http, httpSend, $filter) {
$scope.names = ["ankit patidar", "adhishi ahari", "kritin joshi", "kautilya bharadwaj", "punita ojha", "manvi agarwal", "apeksha purohit", "shipra jain", "mansi nangawat", "praveen soni"];
$scope.data = [];
$scope.names.forEach(function(name) {
$scope.data.push({
name: name,
checkin: "",
checkout: ""
})
});
$scope.login = [];
$scope.check = function(name, doing) {
debugger
name[doing] = new Date();
name[doing] = $filter('date')(name[doing], 'dd-MM-yyyy hh:mm:ss');
$scope.login.push(angular.copy(name));
if (doing == "checkout") {
var q = JSON.stringify($scope.login);
httpSend.sendToServer(q);
}
}
$scope.getData = function() {
httpSend.getfromServer();
}
}]);
`
Python Code
def get(self):
logging.info('get is triggered')
obj = CheckIn.query().fetch()
emp_obj = []
for x in obj:
logging.info('I am inside for loop ')
emp_obj.append({
'name': x.name,
'Check_in': x.inDate,
'check_out': x.outDate
})
logging.info('I am inside emp_obj')
self.response.write(json.dumps(emp_obj))
i need to fetch all the data stored on ndb datastore on front end view thats why i m using http get method but error is showed method not allowed. can u please help e despite using query fetch and showing its response on python ad triggering get method, why error is coming, is there a mistake in control flow or something is missing in my get method, as for now i m able to post nd store data
Change your factory to the following. Don't use the same variable app that you are using for initialising your module for your controller logic.
app.factory('httpSend',['$http', '$q',function($http, $q){
return {
'sendToServer': function(data) {
var def = $q.defer();
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
debugger
var result = response.data;
def.resolve(result );
});
return def.promise;
},
'getfromServer': function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
}
}]);

Categories